Spaces:
Running
on
A10G
Running
on
A10G
update requirements
Browse files
.ipynb_checkpoints/app-checkpoint.py
ADDED
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import json
|
3 |
+
import torch
|
4 |
+
import wavio
|
5 |
+
from tqdm import tqdm
|
6 |
+
from huggingface_hub import snapshot_download
|
7 |
+
|
8 |
+
from audioldm.audio.stft import TacotronSTFT
|
9 |
+
from audioldm.variational_autoencoder import AutoencoderKL
|
10 |
+
|
11 |
+
from transformers import AutoTokenizer, T5ForConditionalGeneration
|
12 |
+
from modelling_deberta_v2 import DebertaV2ForTokenClassificationRegression
|
13 |
+
|
14 |
+
import sys
|
15 |
+
sys.path.insert(0, "diffusers/src")
|
16 |
+
|
17 |
+
from diffusers import DDPMScheduler
|
18 |
+
from models import MusicAudioDiffusion
|
19 |
+
|
20 |
+
from gradio import Markdown
|
21 |
+
|
22 |
+
class MusicFeaturePredictor:
|
23 |
+
def __init__(self, path, device="cuda:0", cache_dir=None, local_files_only=False):
|
24 |
+
self.beats_tokenizer = AutoTokenizer.from_pretrained(
|
25 |
+
"microsoft/deberta-v3-large",
|
26 |
+
cache_dir=cache_dir,
|
27 |
+
local_files_only=local_files_only,
|
28 |
+
)
|
29 |
+
self.beats_model = DebertaV2ForTokenClassificationRegression.from_pretrained(
|
30 |
+
"microsoft/deberta-v3-large",
|
31 |
+
cache_dir=cache_dir,
|
32 |
+
local_files_only=local_files_only,
|
33 |
+
)
|
34 |
+
self.beats_model.eval()
|
35 |
+
self.beats_model.to(device)
|
36 |
+
|
37 |
+
beats_ckpt = f"{path}/beats/microsoft-deberta-v3-large.pt"
|
38 |
+
beats_weight = torch.load(beats_ckpt, map_location="cpu")
|
39 |
+
self.beats_model.load_state_dict(beats_weight)
|
40 |
+
|
41 |
+
self.chords_tokenizer = AutoTokenizer.from_pretrained(
|
42 |
+
"google/flan-t5-large",
|
43 |
+
cache_dir=cache_dir,
|
44 |
+
local_files_only=local_files_only,
|
45 |
+
)
|
46 |
+
self.chords_model = T5ForConditionalGeneration.from_pretrained(
|
47 |
+
"google/flan-t5-large",
|
48 |
+
cache_dir=cache_dir,
|
49 |
+
local_files_only=local_files_only,
|
50 |
+
)
|
51 |
+
self.chords_model.eval()
|
52 |
+
self.chords_model.to(device)
|
53 |
+
|
54 |
+
chords_ckpt = f"{path}/chords/flan-t5-large.bin"
|
55 |
+
chords_weight = torch.load(chords_ckpt, map_location="cpu")
|
56 |
+
self.chords_model.load_state_dict(chords_weight)
|
57 |
+
|
58 |
+
def generate_beats(self, prompt):
|
59 |
+
tokenized = self.beats_tokenizer(
|
60 |
+
prompt, max_length=512, padding=True, truncation=True, return_tensors="pt"
|
61 |
+
)
|
62 |
+
tokenized = {k: v.to(self.beats_model.device) for k, v in tokenized.items()}
|
63 |
+
|
64 |
+
with torch.no_grad():
|
65 |
+
out = self.beats_model(**tokenized)
|
66 |
+
|
67 |
+
max_beat = (
|
68 |
+
1 + torch.argmax(out["logits"][:, 0, :], -1).detach().cpu().numpy()
|
69 |
+
).tolist()[0]
|
70 |
+
intervals = (
|
71 |
+
out["values"][:, :, 0]
|
72 |
+
.detach()
|
73 |
+
.cpu()
|
74 |
+
.numpy()
|
75 |
+
.astype("float32")
|
76 |
+
.round(4)
|
77 |
+
.tolist()
|
78 |
+
)
|
79 |
+
|
80 |
+
intervals = np.cumsum(intervals)
|
81 |
+
predicted_beats_times = []
|
82 |
+
for t in intervals:
|
83 |
+
if t < 10:
|
84 |
+
predicted_beats_times.append(round(t, 2))
|
85 |
+
else:
|
86 |
+
break
|
87 |
+
predicted_beats_times = list(np.array(predicted_beats_times)[:50])
|
88 |
+
|
89 |
+
if len(predicted_beats_times) == 0:
|
90 |
+
predicted_beats = [[], []]
|
91 |
+
else:
|
92 |
+
beat_counts = []
|
93 |
+
for i in range(len(predicted_beats_times)):
|
94 |
+
beat_counts.append(float(1.0 + np.mod(i, max_beat)))
|
95 |
+
predicted_beats = [[predicted_beats_times, beat_counts]]
|
96 |
+
|
97 |
+
return max_beat, predicted_beats_times, predicted_beats
|
98 |
+
|
99 |
+
def generate(self, prompt):
|
100 |
+
max_beat, predicted_beats_times, predicted_beats = self.generate_beats(prompt)
|
101 |
+
|
102 |
+
chords_prompt = "Caption: {} \\n Timestamps: {} \\n Max Beat: {}".format(
|
103 |
+
prompt,
|
104 |
+
" , ".join([str(round(t, 2)) for t in predicted_beats_times]),
|
105 |
+
max_beat,
|
106 |
+
)
|
107 |
+
|
108 |
+
tokenized = self.chords_tokenizer(
|
109 |
+
chords_prompt,
|
110 |
+
max_length=512,
|
111 |
+
padding=True,
|
112 |
+
truncation=True,
|
113 |
+
return_tensors="pt",
|
114 |
+
)
|
115 |
+
tokenized = {k: v.to(self.chords_model.device) for k, v in tokenized.items()}
|
116 |
+
|
117 |
+
generated_chords = self.chords_model.generate(
|
118 |
+
input_ids=tokenized["input_ids"],
|
119 |
+
attention_mask=tokenized["attention_mask"],
|
120 |
+
min_length=8,
|
121 |
+
max_length=128,
|
122 |
+
num_beams=5,
|
123 |
+
early_stopping=True,
|
124 |
+
num_return_sequences=1,
|
125 |
+
)
|
126 |
+
|
127 |
+
generated_chords = self.chords_tokenizer.decode(
|
128 |
+
generated_chords[0],
|
129 |
+
skip_special_tokens=True,
|
130 |
+
clean_up_tokenization_spaces=True,
|
131 |
+
).split(" n ")
|
132 |
+
|
133 |
+
predicted_chords, predicted_chords_times = [], []
|
134 |
+
for item in generated_chords:
|
135 |
+
c, ct = item.split(" at ")
|
136 |
+
predicted_chords.append(c)
|
137 |
+
predicted_chords_times.append(float(ct))
|
138 |
+
|
139 |
+
return predicted_beats, predicted_chords, predicted_chords_times
|
140 |
+
|
141 |
+
|
142 |
+
class Mustango:
|
143 |
+
def __init__(
|
144 |
+
self,
|
145 |
+
name="declare-lab/mustango",
|
146 |
+
device="cuda:0",
|
147 |
+
cache_dir=None,
|
148 |
+
local_files_only=False,
|
149 |
+
):
|
150 |
+
path = snapshot_download(repo_id=name, cache_dir=cache_dir)
|
151 |
+
|
152 |
+
self.music_model = MusicFeaturePredictor(
|
153 |
+
path, device, cache_dir=cache_dir, local_files_only=local_files_only
|
154 |
+
)
|
155 |
+
|
156 |
+
vae_config = json.load(open(f"{path}/configs/vae_config.json"))
|
157 |
+
stft_config = json.load(open(f"{path}/configs/stft_config.json"))
|
158 |
+
main_config = json.load(open(f"{path}/configs/main_config.json"))
|
159 |
+
|
160 |
+
self.vae = AutoencoderKL(**vae_config).to(device)
|
161 |
+
self.stft = TacotronSTFT(**stft_config).to(device)
|
162 |
+
self.model = MusicAudioDiffusion(
|
163 |
+
main_config["text_encoder_name"],
|
164 |
+
main_config["scheduler_name"],
|
165 |
+
unet_model_config_path=f"{path}/configs/music_diffusion_model_config.json",
|
166 |
+
).to(device)
|
167 |
+
|
168 |
+
vae_weights = torch.load(
|
169 |
+
f"{path}/vae/pytorch_model_vae.bin", map_location=device
|
170 |
+
)
|
171 |
+
stft_weights = torch.load(
|
172 |
+
f"{path}/stft/pytorch_model_stft.bin", map_location=device
|
173 |
+
)
|
174 |
+
main_weights = torch.load(
|
175 |
+
f"{path}/ldm/pytorch_model_ldm.bin", map_location=device
|
176 |
+
)
|
177 |
+
|
178 |
+
self.vae.load_state_dict(vae_weights)
|
179 |
+
self.stft.load_state_dict(stft_weights)
|
180 |
+
self.model.load_state_dict(main_weights)
|
181 |
+
|
182 |
+
print("Successfully loaded checkpoint from:", name)
|
183 |
+
|
184 |
+
self.vae.eval()
|
185 |
+
self.stft.eval()
|
186 |
+
self.model.eval()
|
187 |
+
|
188 |
+
self.scheduler = DDPMScheduler.from_pretrained(
|
189 |
+
main_config["scheduler_name"], subfolder="scheduler"
|
190 |
+
)
|
191 |
+
|
192 |
+
def generate(self, prompt, steps=100, guidance=3, samples=1, disable_progress=True):
|
193 |
+
"""Genrate music for a single prompt string."""
|
194 |
+
|
195 |
+
with torch.no_grad():
|
196 |
+
beats, chords, chords_times = self.music_model.generate(prompt)
|
197 |
+
latents = self.model.inference(
|
198 |
+
[prompt],
|
199 |
+
beats,
|
200 |
+
[chords],
|
201 |
+
[chords_times],
|
202 |
+
self.scheduler,
|
203 |
+
steps,
|
204 |
+
guidance,
|
205 |
+
samples,
|
206 |
+
disable_progress,
|
207 |
+
)
|
208 |
+
mel = self.vae.decode_first_stage(latents)
|
209 |
+
wave = self.vae.decode_to_waveform(mel)
|
210 |
+
|
211 |
+
return wave[0]
|
212 |
+
|
213 |
+
|
214 |
+
# Initialize Mustango
|
215 |
+
if torch.cuda.is_available():
|
216 |
+
mustango = Mustango()
|
217 |
+
else:
|
218 |
+
mustango = Mustango(device="cpu")
|
219 |
+
|
220 |
+
def gradio_generate(prompt, steps, guidance):
|
221 |
+
output_wave = mustango.generate(prompt, steps, guidance)
|
222 |
+
# output_filename = f"{prompt.replace(' ', '_')}_{steps}_{guidance}"[:250] + ".wav"
|
223 |
+
output_filename = "temp.wav"
|
224 |
+
wavio.write(output_filename, output_wave, rate=16000, sampwidth=2)
|
225 |
+
|
226 |
+
return output_filename
|
227 |
+
|
228 |
+
# description_text = """
|
229 |
+
# <p><a href="https://huggingface.co/spaces/declare-lab/mustango/blob/main/app.py?duplicate=true"> <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a> For faster inference without waiting in queue, you may duplicate the space and upgrade to a GPU in the settings. <br/><br/>
|
230 |
+
# Generate music using Mustango by providing a text prompt.
|
231 |
+
# <br/><br/> Meet Mustango, an exciting addition to the vibrant landscape of Multimodal Large Language Models \
|
232 |
+
# designed for controlled music generation. Mustango leverages Latent Diffusion Model (LDM), Flan-T5, and \
|
233 |
+
# musical features to do the magic! \
|
234 |
+
# <p/>
|
235 |
+
# """
|
236 |
+
description_text = ""
|
237 |
+
# Gradio input and output components
|
238 |
+
input_text = gr.inputs.Textbox(lines=2, label="Prompt")
|
239 |
+
output_audio = gr.outputs.Audio(label="Generated Music", type="filepath")
|
240 |
+
denoising_steps = gr.Slider(minimum=100, maximum=200, value=100, step=1, label="Steps", interactive=True)
|
241 |
+
guidance_scale = gr.Slider(minimum=1, maximum=10, value=3, step=0.1, label="Guidance Scale", interactive=True)
|
242 |
+
|
243 |
+
# Gradio interface
|
244 |
+
gr_interface = gr.Interface(
|
245 |
+
fn=gradio_generate,
|
246 |
+
inputs=[input_text, denoising_steps, guidance_scale],
|
247 |
+
outputs=[output_audio],
|
248 |
+
title="Mustango: Toward Controllable Text-to-Music Generation",
|
249 |
+
description=description_text,
|
250 |
+
allow_flagging=False,
|
251 |
+
examples=[
|
252 |
+
["This techno song features a synth lead playing the main melody. This is accompanied by programmed percussion playing a simple kick focused beat. The hi-hat is accented in an open position on the 3-and count of every bar. The synth plays the bass part with a voicing that sounds like a cello. This techno song can be played in a club. The chord sequence is Gm, A7, Eb, Bb, C, F, Gm. The beat counts to 2. The tempo of this song is 128.0 beats per minute. The key of this song is G minor."],
|
253 |
+
["This is a new age piece. There is a flute playing the main melody with a lot of staccato notes. The rhythmic background consists of a medium tempo electronic drum beat with percussive elements all over the spectrum. There is a playful atmosphere to the piece. This piece can be used in the soundtrack of a children's TV show or an advertisement jingle."],
|
254 |
+
["The song is an instrumental. The song is in medium tempo with a classical guitar playing a lilting melody in accompaniment style. The song is emotional and romantic. The song is a romantic instrumental song. The chord sequence is Gm, F6, Ebm. The time signature is 4/4. This song is in Adagio. The key of this song is G minor."],
|
255 |
+
["This folk song features a female voice singing the main melody. This is accompanied by a tabla playing the percussion. A guitar strums chords. For most parts of the song, only one chord is played. At the last bar, a different chord is played. This song has minimal instruments. This song has a story-telling mood. This song can be played in a village scene in an Indian movie. The chord sequence is Bbm, Ab. The beat is 3. The tempo of this song is Allegro. The key of this song is Bb minor."],
|
256 |
+
["This is a live performance of a classical music piece. There is an orchestra performing the piece with a violin lead playing the main melody. The atmosphere is sentimental and heart-touching. This piece could be playing in the background at a classy restaurant. The chord progression in this song is Am7, Gm, Dm, A7, Dm. The beat is 3. This song is in Largo. The key of this song is D minor."],
|
257 |
+
["This is a techno piece with drums and beats and a leading melody. A synth plays chords. The music kicks off with a powerful and relentless drumbeat. Over the pounding beats, a leading melody emerges. In the middle of the song, a flock of seagulls flies over the venue and make loud bird sounds. It has strong danceability and can be played in a club. The tempo is 120 bpm. The chords played by the synth are Am, Cm, Dm, Gm."],
|
258 |
+
],
|
259 |
+
cache_examples=False,
|
260 |
+
)
|
261 |
+
|
262 |
+
# Launch Gradio app
|
263 |
+
gr_interface.launch()
|
.ipynb_checkpoints/models-checkpoint.py
ADDED
@@ -0,0 +1,738 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import yaml
|
2 |
+
import random
|
3 |
+
import inspect
|
4 |
+
import numpy as np
|
5 |
+
from tqdm import tqdm
|
6 |
+
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
import torch.nn.functional as F
|
10 |
+
|
11 |
+
from einops import repeat
|
12 |
+
from tools.torch_tools import wav_to_fbank
|
13 |
+
|
14 |
+
from audioldm.audio.stft import TacotronSTFT
|
15 |
+
from audioldm.variational_autoencoder import AutoencoderKL
|
16 |
+
from audioldm.utils import default_audioldm_config, get_metadata
|
17 |
+
|
18 |
+
from transformers import CLIPTokenizer, AutoTokenizer, AutoProcessor
|
19 |
+
from transformers import CLIPTextModel, T5EncoderModel, AutoModel, ClapAudioModel, ClapTextModel
|
20 |
+
|
21 |
+
import sys
|
22 |
+
sys.path.insert(0, "diffusers/src")
|
23 |
+
|
24 |
+
import diffusers
|
25 |
+
from diffusers.utils import randn_tensor
|
26 |
+
from diffusers import DDPMScheduler, UNet2DConditionModel, UNet2DConditionModelMusic
|
27 |
+
from diffusers import AutoencoderKL as DiffuserAutoencoderKL
|
28 |
+
from layers.layers import chord_tokenizer, beat_tokenizer, Chord_Embedding, Beat_Embedding, Music_PositionalEncoding, Fundamental_Music_Embedding
|
29 |
+
|
30 |
+
def build_pretrained_models(name):
|
31 |
+
checkpoint = torch.load(get_metadata()[name]["path"], map_location="cpu")
|
32 |
+
scale_factor = checkpoint["state_dict"]["scale_factor"].item()
|
33 |
+
|
34 |
+
vae_state_dict = {k[18:]: v for k, v in checkpoint["state_dict"].items() if "first_stage_model." in k}
|
35 |
+
|
36 |
+
config = default_audioldm_config(name)
|
37 |
+
vae_config = config["model"]["params"]["first_stage_config"]["params"]
|
38 |
+
vae_config["scale_factor"] = scale_factor
|
39 |
+
|
40 |
+
vae = AutoencoderKL(**vae_config)
|
41 |
+
vae.load_state_dict(vae_state_dict)
|
42 |
+
|
43 |
+
fn_STFT = TacotronSTFT(
|
44 |
+
config["preprocessing"]["stft"]["filter_length"],
|
45 |
+
config["preprocessing"]["stft"]["hop_length"],
|
46 |
+
config["preprocessing"]["stft"]["win_length"],
|
47 |
+
config["preprocessing"]["mel"]["n_mel_channels"],
|
48 |
+
config["preprocessing"]["audio"]["sampling_rate"],
|
49 |
+
config["preprocessing"]["mel"]["mel_fmin"],
|
50 |
+
config["preprocessing"]["mel"]["mel_fmax"],
|
51 |
+
)
|
52 |
+
|
53 |
+
vae.eval()
|
54 |
+
fn_STFT.eval()
|
55 |
+
return vae, fn_STFT
|
56 |
+
|
57 |
+
|
58 |
+
class AudioDiffusion(nn.Module):
|
59 |
+
def __init__(
|
60 |
+
self,
|
61 |
+
text_encoder_name,
|
62 |
+
scheduler_name,
|
63 |
+
unet_model_name=None,
|
64 |
+
unet_model_config_path=None,
|
65 |
+
snr_gamma=None,
|
66 |
+
freeze_text_encoder=True,
|
67 |
+
uncondition=False,
|
68 |
+
|
69 |
+
):
|
70 |
+
super().__init__()
|
71 |
+
|
72 |
+
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"
|
73 |
+
|
74 |
+
self.text_encoder_name = text_encoder_name
|
75 |
+
self.scheduler_name = scheduler_name
|
76 |
+
self.unet_model_name = unet_model_name
|
77 |
+
self.unet_model_config_path = unet_model_config_path
|
78 |
+
self.snr_gamma = snr_gamma
|
79 |
+
self.freeze_text_encoder = freeze_text_encoder
|
80 |
+
self.uncondition = uncondition
|
81 |
+
|
82 |
+
# https://huggingface.co/docs/diffusers/v0.14.0/en/api/schedulers/overview
|
83 |
+
self.noise_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler")
|
84 |
+
self.inference_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler")
|
85 |
+
|
86 |
+
if unet_model_config_path:
|
87 |
+
unet_config = UNet2DConditionModel.load_config(unet_model_config_path)
|
88 |
+
self.unet = UNet2DConditionModel.from_config(unet_config, subfolder="unet")
|
89 |
+
self.set_from = "random"
|
90 |
+
print("UNet initialized randomly.")
|
91 |
+
else:
|
92 |
+
self.unet = UNet2DConditionModel.from_pretrained(unet_model_name, subfolder="unet")
|
93 |
+
self.set_from = "pre-trained"
|
94 |
+
self.group_in = nn.Sequential(nn.Linear(8, 512), nn.Linear(512, 4))
|
95 |
+
self.group_out = nn.Sequential(nn.Linear(4, 512), nn.Linear(512, 8))
|
96 |
+
print("UNet initialized from stable diffusion checkpoint.")
|
97 |
+
|
98 |
+
if "stable-diffusion" in self.text_encoder_name:
|
99 |
+
self.tokenizer = CLIPTokenizer.from_pretrained(self.text_encoder_name, subfolder="tokenizer")
|
100 |
+
self.text_encoder = CLIPTextModel.from_pretrained(self.text_encoder_name, subfolder="text_encoder")
|
101 |
+
elif "t5" in self.text_encoder_name:
|
102 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name)
|
103 |
+
self.text_encoder = T5EncoderModel.from_pretrained(self.text_encoder_name)
|
104 |
+
else:
|
105 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name)
|
106 |
+
self.text_encoder = AutoModel.from_pretrained(self.text_encoder_name)
|
107 |
+
|
108 |
+
def compute_snr(self, timesteps):
|
109 |
+
"""
|
110 |
+
Computes SNR as per https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
|
111 |
+
"""
|
112 |
+
alphas_cumprod = self.noise_scheduler.alphas_cumprod
|
113 |
+
sqrt_alphas_cumprod = alphas_cumprod**0.5
|
114 |
+
sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
|
115 |
+
|
116 |
+
# Expand the tensors.
|
117 |
+
# Adapted from https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L1026
|
118 |
+
sqrt_alphas_cumprod = sqrt_alphas_cumprod.to(device=timesteps.device)[timesteps].float()
|
119 |
+
while len(sqrt_alphas_cumprod.shape) < len(timesteps.shape):
|
120 |
+
sqrt_alphas_cumprod = sqrt_alphas_cumprod[..., None]
|
121 |
+
alpha = sqrt_alphas_cumprod.expand(timesteps.shape)
|
122 |
+
|
123 |
+
sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(device=timesteps.device)[timesteps].float()
|
124 |
+
while len(sqrt_one_minus_alphas_cumprod.shape) < len(timesteps.shape):
|
125 |
+
sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod[..., None]
|
126 |
+
sigma = sqrt_one_minus_alphas_cumprod.expand(timesteps.shape)
|
127 |
+
|
128 |
+
# Compute SNR.
|
129 |
+
snr = (alpha / sigma) ** 2
|
130 |
+
return snr
|
131 |
+
|
132 |
+
def encode_text(self, prompt):
|
133 |
+
device = self.text_encoder.device
|
134 |
+
batch = self.tokenizer(
|
135 |
+
prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt"
|
136 |
+
)
|
137 |
+
input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
|
138 |
+
|
139 |
+
if self.freeze_text_encoder:
|
140 |
+
with torch.no_grad():
|
141 |
+
encoder_hidden_states = self.text_encoder(
|
142 |
+
input_ids=input_ids, attention_mask=attention_mask
|
143 |
+
)[0]
|
144 |
+
else:
|
145 |
+
encoder_hidden_states = self.text_encoder(
|
146 |
+
input_ids=input_ids, attention_mask=attention_mask
|
147 |
+
)[0]
|
148 |
+
|
149 |
+
boolean_encoder_mask = (attention_mask == 1).to(device)
|
150 |
+
return encoder_hidden_states, boolean_encoder_mask
|
151 |
+
|
152 |
+
def forward(self, latents, prompt, validation_mode=False):
|
153 |
+
device = self.text_encoder.device
|
154 |
+
num_train_timesteps = self.noise_scheduler.num_train_timesteps
|
155 |
+
self.noise_scheduler.set_timesteps(num_train_timesteps, device=device)
|
156 |
+
|
157 |
+
encoder_hidden_states, boolean_encoder_mask = self.encode_text(prompt)
|
158 |
+
|
159 |
+
if self.uncondition:
|
160 |
+
mask_indices = [k for k in range(len(prompt)) if random.random() < 0.1]
|
161 |
+
if len(mask_indices) > 0:
|
162 |
+
encoder_hidden_states[mask_indices] = 0
|
163 |
+
|
164 |
+
bsz = latents.shape[0]
|
165 |
+
|
166 |
+
if validation_mode:
|
167 |
+
timesteps = (self.noise_scheduler.num_train_timesteps//2) * torch.ones((bsz,), dtype=torch.int64, device=device)
|
168 |
+
else:
|
169 |
+
# Sample a random timestep for each instance
|
170 |
+
timesteps = torch.randint(0, self.noise_scheduler.num_train_timesteps, (bsz,), device=device)
|
171 |
+
# print('in if ', timesteps)
|
172 |
+
timesteps = timesteps.long()
|
173 |
+
# print('outside if ' , timesteps)
|
174 |
+
noise = torch.randn_like(latents)
|
175 |
+
noisy_latents = self.noise_scheduler.add_noise(latents, noise, timesteps)
|
176 |
+
|
177 |
+
# Get the target for loss depending on the prediction type
|
178 |
+
if self.noise_scheduler.config.prediction_type == "epsilon":
|
179 |
+
target = noise
|
180 |
+
elif self.noise_scheduler.config.prediction_type == "v_prediction":
|
181 |
+
target = self.noise_scheduler.get_velocity(latents, noise, timesteps)
|
182 |
+
else:
|
183 |
+
raise ValueError(f"Unknown prediction type {self.noise_scheduler.config.prediction_type}")
|
184 |
+
|
185 |
+
if self.set_from == "random":
|
186 |
+
model_pred = self.unet(
|
187 |
+
noisy_latents, timesteps, encoder_hidden_states,
|
188 |
+
encoder_attention_mask=boolean_encoder_mask
|
189 |
+
).sample
|
190 |
+
|
191 |
+
elif self.set_from == "pre-trained":
|
192 |
+
compressed_latents = self.group_in(noisy_latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
|
193 |
+
model_pred = self.unet(
|
194 |
+
compressed_latents, timesteps, encoder_hidden_states,
|
195 |
+
encoder_attention_mask=boolean_encoder_mask
|
196 |
+
).sample
|
197 |
+
model_pred = self.group_out(model_pred.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
|
198 |
+
|
199 |
+
if self.snr_gamma is None:
|
200 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
201 |
+
else:
|
202 |
+
# Compute loss-weights as per Section 3.4 of https://arxiv.org/abs/2303.09556.
|
203 |
+
# Adaptef from huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image.py
|
204 |
+
snr = self.compute_snr(timesteps)
|
205 |
+
mse_loss_weights = (
|
206 |
+
torch.stack([snr, self.snr_gamma * torch.ones_like(timesteps)], dim=1).min(dim=1)[0] / snr
|
207 |
+
)
|
208 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
|
209 |
+
loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
|
210 |
+
loss = loss.mean()
|
211 |
+
|
212 |
+
return loss
|
213 |
+
|
214 |
+
@torch.no_grad()
|
215 |
+
def inference(self, prompt, inference_scheduler, num_steps=20, guidance_scale=3, num_samples_per_prompt=1,
|
216 |
+
disable_progress=True):
|
217 |
+
device = self.text_encoder.device
|
218 |
+
classifier_free_guidance = guidance_scale > 1.0
|
219 |
+
batch_size = len(prompt) * num_samples_per_prompt
|
220 |
+
|
221 |
+
if classifier_free_guidance:
|
222 |
+
prompt_embeds, boolean_prompt_mask = self.encode_text_classifier_free(prompt, num_samples_per_prompt)
|
223 |
+
else:
|
224 |
+
prompt_embeds, boolean_prompt_mask = self.encode_text(prompt)
|
225 |
+
prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
|
226 |
+
boolean_prompt_mask = boolean_prompt_mask.repeat_interleave(num_samples_per_prompt, 0)
|
227 |
+
|
228 |
+
inference_scheduler.set_timesteps(num_steps, device=device)
|
229 |
+
timesteps = inference_scheduler.timesteps
|
230 |
+
|
231 |
+
num_channels_latents = self.unet.in_channels
|
232 |
+
latents = self.prepare_latents(batch_size, inference_scheduler, num_channels_latents, prompt_embeds.dtype, device)
|
233 |
+
|
234 |
+
num_warmup_steps = len(timesteps) - num_steps * inference_scheduler.order
|
235 |
+
progress_bar = tqdm(range(num_steps), disable=disable_progress)
|
236 |
+
|
237 |
+
for i, t in enumerate(timesteps):
|
238 |
+
# expand the latents if we are doing classifier free guidance
|
239 |
+
latent_model_input = torch.cat([latents] * 2) if classifier_free_guidance else latents
|
240 |
+
latent_model_input = inference_scheduler.scale_model_input(latent_model_input, t)
|
241 |
+
|
242 |
+
noise_pred = self.unet(
|
243 |
+
latent_model_input, t, encoder_hidden_states=prompt_embeds,
|
244 |
+
encoder_attention_mask=boolean_prompt_mask
|
245 |
+
).sample
|
246 |
+
|
247 |
+
# perform guidance
|
248 |
+
if classifier_free_guidance:
|
249 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
250 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
251 |
+
|
252 |
+
# compute the previous noisy sample x_t -> x_t-1
|
253 |
+
latents = inference_scheduler.step(noise_pred, t, latents).prev_sample
|
254 |
+
|
255 |
+
# call the callback, if provided
|
256 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % inference_scheduler.order == 0):
|
257 |
+
progress_bar.update(1)
|
258 |
+
|
259 |
+
if self.set_from == "pre-trained":
|
260 |
+
latents = self.group_out(latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
|
261 |
+
return latents
|
262 |
+
|
263 |
+
def prepare_latents(self, batch_size, inference_scheduler, num_channels_latents, dtype, device):
|
264 |
+
shape = (batch_size, num_channels_latents, 256, 16)
|
265 |
+
latents = randn_tensor(shape, generator=None, device=device, dtype=dtype)
|
266 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
267 |
+
latents = latents * inference_scheduler.init_noise_sigma
|
268 |
+
return latents
|
269 |
+
|
270 |
+
def encode_text_classifier_free(self, prompt, num_samples_per_prompt):
|
271 |
+
device = self.text_encoder.device
|
272 |
+
batch = self.tokenizer(
|
273 |
+
prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt"
|
274 |
+
)
|
275 |
+
input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
|
276 |
+
|
277 |
+
with torch.no_grad():
|
278 |
+
prompt_embeds = self.text_encoder(
|
279 |
+
input_ids=input_ids, attention_mask=attention_mask
|
280 |
+
)[0]
|
281 |
+
|
282 |
+
prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
|
283 |
+
attention_mask = attention_mask.repeat_interleave(num_samples_per_prompt, 0)
|
284 |
+
|
285 |
+
# get unconditional embeddings for classifier free guidance
|
286 |
+
uncond_tokens = [""] * len(prompt)
|
287 |
+
|
288 |
+
max_length = prompt_embeds.shape[1]
|
289 |
+
uncond_batch = self.tokenizer(
|
290 |
+
uncond_tokens, max_length=max_length, padding="max_length", truncation=True, return_tensors="pt",
|
291 |
+
)
|
292 |
+
uncond_input_ids = uncond_batch.input_ids.to(device)
|
293 |
+
uncond_attention_mask = uncond_batch.attention_mask.to(device)
|
294 |
+
|
295 |
+
with torch.no_grad():
|
296 |
+
negative_prompt_embeds = self.text_encoder(
|
297 |
+
input_ids=uncond_input_ids, attention_mask=uncond_attention_mask
|
298 |
+
)[0]
|
299 |
+
|
300 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
|
301 |
+
uncond_attention_mask = uncond_attention_mask.repeat_interleave(num_samples_per_prompt, 0)
|
302 |
+
|
303 |
+
# For classifier free guidance, we need to do two forward passes.
|
304 |
+
# We concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes
|
305 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
306 |
+
prompt_mask = torch.cat([uncond_attention_mask, attention_mask])
|
307 |
+
boolean_prompt_mask = (prompt_mask == 1).to(device)
|
308 |
+
|
309 |
+
return prompt_embeds, boolean_prompt_mask
|
310 |
+
|
311 |
+
|
312 |
+
class MusicAudioDiffusion(nn.Module):
|
313 |
+
def __init__(
|
314 |
+
self,
|
315 |
+
text_encoder_name,
|
316 |
+
scheduler_name,
|
317 |
+
unet_model_name=None,
|
318 |
+
unet_model_config_path=None,
|
319 |
+
snr_gamma=None,
|
320 |
+
freeze_text_encoder=True,
|
321 |
+
uncondition=False,
|
322 |
+
|
323 |
+
d_fme = 1024, #FME
|
324 |
+
fme_type = "se",
|
325 |
+
base = 1,
|
326 |
+
if_trainable = True,
|
327 |
+
translation_bias_type = "nd",
|
328 |
+
emb_nn = True,
|
329 |
+
d_pe = 1024, #PE
|
330 |
+
if_index = True,
|
331 |
+
if_global_timing = True,
|
332 |
+
if_modulo_timing = False,
|
333 |
+
d_beat = 1024, #Beat
|
334 |
+
d_oh_beat_type = 7,
|
335 |
+
beat_len = 50,
|
336 |
+
d_chord = 1024, #Chord
|
337 |
+
d_oh_chord_type = 12,
|
338 |
+
d_oh_inv_type = 4,
|
339 |
+
chord_len = 20,
|
340 |
+
|
341 |
+
):
|
342 |
+
super().__init__()
|
343 |
+
|
344 |
+
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"
|
345 |
+
|
346 |
+
self.text_encoder_name = text_encoder_name
|
347 |
+
self.scheduler_name = scheduler_name
|
348 |
+
self.unet_model_name = unet_model_name
|
349 |
+
self.unet_model_config_path = unet_model_config_path
|
350 |
+
self.snr_gamma = snr_gamma
|
351 |
+
self.freeze_text_encoder = freeze_text_encoder
|
352 |
+
self.uncondition = uncondition
|
353 |
+
|
354 |
+
# https://huggingface.co/docs/diffusers/v0.14.0/en/api/schedulers/overview
|
355 |
+
self.noise_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler")
|
356 |
+
self.inference_scheduler = DDPMScheduler.from_pretrained(self.scheduler_name, subfolder="scheduler")
|
357 |
+
|
358 |
+
if unet_model_config_path:
|
359 |
+
unet_config = UNet2DConditionModelMusic.load_config(unet_model_config_path)
|
360 |
+
self.unet = UNet2DConditionModelMusic.from_config(unet_config, subfolder="unet")
|
361 |
+
self.set_from = "random"
|
362 |
+
print("UNet initialized randomly.")
|
363 |
+
else:
|
364 |
+
self.unet = UNet2DConditionModel.from_pretrained(unet_model_name, subfolder="unet")
|
365 |
+
self.set_from = "pre-trained"
|
366 |
+
self.group_in = nn.Sequential(nn.Linear(8, 512), nn.Linear(512, 4))
|
367 |
+
self.group_out = nn.Sequential(nn.Linear(4, 512), nn.Linear(512, 8))
|
368 |
+
print("UNet initialized from stable diffusion checkpoint.")
|
369 |
+
|
370 |
+
if "stable-diffusion" in self.text_encoder_name:
|
371 |
+
self.tokenizer = CLIPTokenizer.from_pretrained(self.text_encoder_name, subfolder="tokenizer")
|
372 |
+
self.text_encoder = CLIPTextModel.from_pretrained(self.text_encoder_name, subfolder="text_encoder")
|
373 |
+
elif "t5" in self.text_encoder_name:
|
374 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name)
|
375 |
+
self.text_encoder = T5EncoderModel.from_pretrained(self.text_encoder_name)
|
376 |
+
else:
|
377 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.text_encoder_name)
|
378 |
+
self.text_encoder = AutoModel.from_pretrained(self.text_encoder_name)
|
379 |
+
|
380 |
+
self.device = self.text_encoder.device
|
381 |
+
#Music Feature Encoder
|
382 |
+
self.FME = Fundamental_Music_Embedding(d_model = d_fme, base= base, if_trainable = False, type = fme_type,emb_nn=emb_nn,translation_bias_type = translation_bias_type)
|
383 |
+
self.PE = Music_PositionalEncoding(d_model = d_pe, if_index = if_index, if_global_timing = if_global_timing, if_modulo_timing = if_modulo_timing, device = self.device)
|
384 |
+
# self.PE2 = Music_PositionalEncoding(d_model = d_pe, if_index = if_index, if_global_timing = if_global_timing, if_modulo_timing = if_modulo_timing, device = self.device)
|
385 |
+
self.beat_tokenizer = beat_tokenizer(seq_len_beat=beat_len, if_pad = True)
|
386 |
+
self.beat_embedding_layer = Beat_Embedding(self.PE, d_model = d_beat, d_oh_beat_type = d_oh_beat_type)
|
387 |
+
self.chord_embedding_layer = Chord_Embedding(self.FME, self.PE, d_model = d_chord, d_oh_type = d_oh_chord_type, d_oh_inv = d_oh_inv_type)
|
388 |
+
self.chord_tokenizer = chord_tokenizer(seq_len_chord=chord_len, if_pad = True)
|
389 |
+
|
390 |
+
|
391 |
+
def compute_snr(self, timesteps):
|
392 |
+
"""
|
393 |
+
Computes SNR as per https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
|
394 |
+
"""
|
395 |
+
alphas_cumprod = self.noise_scheduler.alphas_cumprod
|
396 |
+
sqrt_alphas_cumprod = alphas_cumprod**0.5
|
397 |
+
sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
|
398 |
+
|
399 |
+
# Expand the tensors.
|
400 |
+
# Adapted from https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L1026
|
401 |
+
sqrt_alphas_cumprod = sqrt_alphas_cumprod.to(device=timesteps.device)[timesteps].float()
|
402 |
+
while len(sqrt_alphas_cumprod.shape) < len(timesteps.shape):
|
403 |
+
sqrt_alphas_cumprod = sqrt_alphas_cumprod[..., None]
|
404 |
+
alpha = sqrt_alphas_cumprod.expand(timesteps.shape)
|
405 |
+
|
406 |
+
sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(device=timesteps.device)[timesteps].float()
|
407 |
+
while len(sqrt_one_minus_alphas_cumprod.shape) < len(timesteps.shape):
|
408 |
+
sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod[..., None]
|
409 |
+
sigma = sqrt_one_minus_alphas_cumprod.expand(timesteps.shape)
|
410 |
+
|
411 |
+
# Compute SNR.
|
412 |
+
snr = (alpha / sigma) ** 2
|
413 |
+
return snr
|
414 |
+
|
415 |
+
def encode_text(self, prompt):
|
416 |
+
device = self.text_encoder.device
|
417 |
+
batch = self.tokenizer(
|
418 |
+
prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt"
|
419 |
+
)
|
420 |
+
input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device) #cuda
|
421 |
+
if self.freeze_text_encoder:
|
422 |
+
with torch.no_grad():
|
423 |
+
encoder_hidden_states = self.text_encoder(
|
424 |
+
input_ids=input_ids, attention_mask=attention_mask
|
425 |
+
)[0] #batch, len_text, dim
|
426 |
+
else:
|
427 |
+
encoder_hidden_states = self.text_encoder(
|
428 |
+
input_ids=input_ids, attention_mask=attention_mask
|
429 |
+
)[0]
|
430 |
+
boolean_encoder_mask = (attention_mask == 1).to(device) ##batch, len_text
|
431 |
+
return encoder_hidden_states, boolean_encoder_mask
|
432 |
+
|
433 |
+
def encode_beats(self, beats):
|
434 |
+
# device = self.beat_embedding_layer.device
|
435 |
+
out_beat = []
|
436 |
+
out_beat_timing = []
|
437 |
+
out_mask = []
|
438 |
+
for beat in beats:
|
439 |
+
tokenized_beats,tokenized_beats_timing, tokenized_beat_mask = self.beat_tokenizer(beat)
|
440 |
+
out_beat.append(tokenized_beats)
|
441 |
+
out_beat_timing.append(tokenized_beats_timing)
|
442 |
+
out_mask.append(tokenized_beat_mask)
|
443 |
+
out_beat, out_beat_timing, out_mask = torch.tensor(out_beat).cuda(), torch.tensor(out_beat_timing).cuda(), torch.tensor(out_mask).cuda() #batch, len_beat
|
444 |
+
embedded_beat = self.beat_embedding_layer(out_beat, out_beat_timing)
|
445 |
+
|
446 |
+
return embedded_beat, out_mask
|
447 |
+
|
448 |
+
def encode_chords(self, chords,chords_time):
|
449 |
+
out_chord_root = []
|
450 |
+
out_chord_type = []
|
451 |
+
out_chord_inv = []
|
452 |
+
out_chord_timing = []
|
453 |
+
out_mask = []
|
454 |
+
for chord, chord_time in zip(chords,chords_time): #batch loop
|
455 |
+
tokenized_chord_root, tokenized_chord_type, tokenized_chord_inv, tokenized_chord_time, tokenized_chord_mask = self.chord_tokenizer(chord, chord_time)
|
456 |
+
out_chord_root.append(tokenized_chord_root)
|
457 |
+
out_chord_type.append(tokenized_chord_type)
|
458 |
+
out_chord_inv.append(tokenized_chord_inv)
|
459 |
+
out_chord_timing.append(tokenized_chord_time)
|
460 |
+
out_mask.append(tokenized_chord_mask)
|
461 |
+
#chords: (B, LEN, 4)
|
462 |
+
out_chord_root, out_chord_type, out_chord_inv, out_chord_timing, out_mask = torch.tensor(out_chord_root).cuda(), torch.tensor(out_chord_type).cuda(), torch.tensor(out_chord_inv).cuda(), torch.tensor(out_chord_timing).cuda(), torch.tensor(out_mask).cuda()
|
463 |
+
embedded_chord = self.chord_embedding_layer(out_chord_root, out_chord_type, out_chord_inv, out_chord_timing)
|
464 |
+
return embedded_chord, out_mask
|
465 |
+
# return out_chord_root, out_mask
|
466 |
+
|
467 |
+
|
468 |
+
def forward(self, latents, prompt, beats, chords,chords_time, validation_mode=False):
|
469 |
+
device = self.text_encoder.device
|
470 |
+
num_train_timesteps = self.noise_scheduler.num_train_timesteps
|
471 |
+
self.noise_scheduler.set_timesteps(num_train_timesteps, device=device)
|
472 |
+
|
473 |
+
encoder_hidden_states, boolean_encoder_mask = self.encode_text(prompt)
|
474 |
+
|
475 |
+
# with torch.no_grad():
|
476 |
+
encoded_beats, beat_mask = self.encode_beats(beats) #batch, len_beats, dim; batch, len_beats
|
477 |
+
encoded_chords, chord_mask = self.encode_chords(chords,chords_time)
|
478 |
+
|
479 |
+
|
480 |
+
if self.uncondition:
|
481 |
+
mask_indices = [k for k in range(len(prompt)) if random.random() < 0.1]
|
482 |
+
if len(mask_indices) > 0:
|
483 |
+
encoder_hidden_states[mask_indices] = 0
|
484 |
+
encoded_chords[mask_indices] = 0
|
485 |
+
encoded_beats[mask_indices] = 0
|
486 |
+
|
487 |
+
bsz = latents.shape[0]
|
488 |
+
|
489 |
+
if validation_mode:
|
490 |
+
timesteps = (self.noise_scheduler.num_train_timesteps//2) * torch.ones((bsz,), dtype=torch.int64, device=device)
|
491 |
+
else:
|
492 |
+
timesteps = torch.randint(0, self.noise_scheduler.num_train_timesteps, (bsz,), device=device)
|
493 |
+
|
494 |
+
|
495 |
+
timesteps = timesteps.long()
|
496 |
+
|
497 |
+
noise = torch.randn_like(latents)
|
498 |
+
noisy_latents = self.noise_scheduler.add_noise(latents, noise, timesteps)
|
499 |
+
|
500 |
+
# Get the target for loss depending on the prediction type
|
501 |
+
if self.noise_scheduler.config.prediction_type == "epsilon":
|
502 |
+
target = noise
|
503 |
+
elif self.noise_scheduler.config.prediction_type == "v_prediction":
|
504 |
+
target = self.noise_scheduler.get_velocity(latents, noise, timesteps)
|
505 |
+
else:
|
506 |
+
raise ValueError(f"Unknown prediction type {self.noise_scheduler.config.prediction_type}")
|
507 |
+
|
508 |
+
if self.set_from == "random":
|
509 |
+
# model_pred = torch.zeros((bsz,8,256,16)).to(device)
|
510 |
+
model_pred = self.unet(
|
511 |
+
noisy_latents, timesteps, encoder_hidden_states, encoded_beats, encoded_chords,
|
512 |
+
encoder_attention_mask=boolean_encoder_mask, beat_attention_mask = beat_mask, chord_attention_mask = chord_mask
|
513 |
+
).sample
|
514 |
+
|
515 |
+
elif self.set_from == "pre-trained":
|
516 |
+
compressed_latents = self.group_in(noisy_latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
|
517 |
+
model_pred = self.unet(
|
518 |
+
compressed_latents, timesteps, encoder_hidden_states,
|
519 |
+
encoder_attention_mask=boolean_encoder_mask
|
520 |
+
).sample
|
521 |
+
model_pred = self.group_out(model_pred.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
|
522 |
+
|
523 |
+
if self.snr_gamma is None:
|
524 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
525 |
+
else:
|
526 |
+
# Compute loss-weights as per Section 3.4 of https://arxiv.org/abs/2303.09556.
|
527 |
+
# Adaptef from huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image.py
|
528 |
+
snr = self.compute_snr(timesteps)
|
529 |
+
mse_loss_weights = (
|
530 |
+
torch.stack([snr, self.snr_gamma * torch.ones_like(timesteps)], dim=1).min(dim=1)[0] / snr
|
531 |
+
)
|
532 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
|
533 |
+
loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
|
534 |
+
loss = loss.mean()
|
535 |
+
|
536 |
+
return loss
|
537 |
+
|
538 |
+
@torch.no_grad()
|
539 |
+
def inference(self, prompt, beats, chords,chords_time, inference_scheduler, num_steps=20, guidance_scale=3, num_samples_per_prompt=1,
|
540 |
+
disable_progress=True):
|
541 |
+
device = self.text_encoder.device
|
542 |
+
classifier_free_guidance = guidance_scale > 1.0
|
543 |
+
batch_size = len(prompt) * num_samples_per_prompt
|
544 |
+
|
545 |
+
if classifier_free_guidance:
|
546 |
+
prompt_embeds, boolean_prompt_mask = self.encode_text_classifier_free(prompt, num_samples_per_prompt)
|
547 |
+
encoded_beats, beat_mask = self.encode_beats_classifier_free(beats, num_samples_per_prompt) #batch, len_beats, dim; batch, len_beats
|
548 |
+
encoded_chords, chord_mask = self.encode_chords_classifier_free(chords, chords_time, num_samples_per_prompt)
|
549 |
+
else:
|
550 |
+
prompt_embeds, boolean_prompt_mask = self.encode_text(prompt)
|
551 |
+
prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
|
552 |
+
boolean_prompt_mask = boolean_prompt_mask.repeat_interleave(num_samples_per_prompt, 0)
|
553 |
+
|
554 |
+
encoded_beats, beat_mask = self.encode_beats(beats) #batch, len_beats, dim; batch, len_beats
|
555 |
+
encoded_beats = encoded_beats.repeat_interleave(num_samples_per_prompt, 0)
|
556 |
+
beat_mask = beat_mask.repeat_interleave(num_samples_per_prompt, 0)
|
557 |
+
|
558 |
+
encoded_chords, chord_mask = self.encode_chords(chords,chords_time)
|
559 |
+
encoded_chords = encoded_chords.repeat_interleave(num_samples_per_prompt, 0)
|
560 |
+
chord_mask = chord_mask.repeat_interleave(num_samples_per_prompt, 0)
|
561 |
+
|
562 |
+
# print(f"encoded_chords:{encoded_chords.shape}, chord_mask:{chord_mask.shape}, prompt_embeds:{prompt_embeds.shape},boolean_prompt_mask:{boolean_prompt_mask.shape} ")
|
563 |
+
inference_scheduler.set_timesteps(num_steps, device=device)
|
564 |
+
timesteps = inference_scheduler.timesteps
|
565 |
+
|
566 |
+
num_channels_latents = self.unet.in_channels
|
567 |
+
latents = self.prepare_latents(batch_size, inference_scheduler, num_channels_latents, prompt_embeds.dtype, device)
|
568 |
+
|
569 |
+
num_warmup_steps = len(timesteps) - num_steps * inference_scheduler.order
|
570 |
+
progress_bar = tqdm(range(num_steps), disable=disable_progress)
|
571 |
+
|
572 |
+
for i, t in enumerate(timesteps):
|
573 |
+
# expand the latents if we are doing classifier free guidance
|
574 |
+
latent_model_input = torch.cat([latents] * 2) if classifier_free_guidance else latents
|
575 |
+
latent_model_input = inference_scheduler.scale_model_input(latent_model_input, t)
|
576 |
+
|
577 |
+
noise_pred = self.unet(
|
578 |
+
latent_model_input, t, encoder_hidden_states=prompt_embeds,
|
579 |
+
encoder_attention_mask=boolean_prompt_mask,
|
580 |
+
beat_features = encoded_beats, beat_attention_mask = beat_mask, chord_features = encoded_chords,chord_attention_mask = chord_mask
|
581 |
+
).sample
|
582 |
+
|
583 |
+
# perform guidance
|
584 |
+
if classifier_free_guidance: #should work for beats and chords too
|
585 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
586 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
587 |
+
|
588 |
+
# compute the previous noisy sample x_t -> x_t-1
|
589 |
+
latents = inference_scheduler.step(noise_pred, t, latents).prev_sample
|
590 |
+
|
591 |
+
# call the callback, if provided
|
592 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % inference_scheduler.order == 0):
|
593 |
+
progress_bar.update(1)
|
594 |
+
|
595 |
+
if self.set_from == "pre-trained":
|
596 |
+
latents = self.group_out(latents.permute(0, 2, 3, 1).contiguous()).permute(0, 3, 1, 2).contiguous()
|
597 |
+
return latents
|
598 |
+
|
599 |
+
def prepare_latents(self, batch_size, inference_scheduler, num_channels_latents, dtype, device):
|
600 |
+
shape = (batch_size, num_channels_latents, 256, 16)
|
601 |
+
latents = randn_tensor(shape, generator=None, device=device, dtype=dtype)
|
602 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
603 |
+
latents = latents * inference_scheduler.init_noise_sigma
|
604 |
+
return latents
|
605 |
+
|
606 |
+
def encode_text_classifier_free(self, prompt, num_samples_per_prompt):
|
607 |
+
device = self.text_encoder.device
|
608 |
+
batch = self.tokenizer(
|
609 |
+
prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt"
|
610 |
+
)
|
611 |
+
input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
|
612 |
+
|
613 |
+
with torch.no_grad():
|
614 |
+
prompt_embeds = self.text_encoder(
|
615 |
+
input_ids=input_ids, attention_mask=attention_mask
|
616 |
+
)[0]
|
617 |
+
|
618 |
+
prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
|
619 |
+
attention_mask = attention_mask.repeat_interleave(num_samples_per_prompt, 0)
|
620 |
+
|
621 |
+
# get unconditional embeddings for classifier free guidance
|
622 |
+
# print(len(prompt), 'this is prompt len')
|
623 |
+
uncond_tokens = [""] * len(prompt)
|
624 |
+
|
625 |
+
max_length = prompt_embeds.shape[1]
|
626 |
+
uncond_batch = self.tokenizer(
|
627 |
+
uncond_tokens, max_length=max_length, padding="max_length", truncation=True, return_tensors="pt",
|
628 |
+
)
|
629 |
+
uncond_input_ids = uncond_batch.input_ids.to(device)
|
630 |
+
uncond_attention_mask = uncond_batch.attention_mask.to(device)
|
631 |
+
|
632 |
+
with torch.no_grad():
|
633 |
+
negative_prompt_embeds = self.text_encoder(
|
634 |
+
input_ids=uncond_input_ids, attention_mask=uncond_attention_mask
|
635 |
+
)[0]
|
636 |
+
|
637 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
|
638 |
+
uncond_attention_mask = uncond_attention_mask.repeat_interleave(num_samples_per_prompt, 0)
|
639 |
+
|
640 |
+
# For classifier free guidance, we need to do two forward passes.
|
641 |
+
# We concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes
|
642 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
643 |
+
prompt_mask = torch.cat([uncond_attention_mask, attention_mask])
|
644 |
+
boolean_prompt_mask = (prompt_mask == 1).to(device)
|
645 |
+
|
646 |
+
return prompt_embeds, boolean_prompt_mask
|
647 |
+
|
648 |
+
|
649 |
+
def encode_beats_classifier_free(self, beats, num_samples_per_prompt):
|
650 |
+
with torch.no_grad():
|
651 |
+
out_beat = []
|
652 |
+
out_beat_timing = []
|
653 |
+
out_mask = []
|
654 |
+
for beat in beats:
|
655 |
+
tokenized_beats,tokenized_beats_timing, tokenized_beat_mask = self.beat_tokenizer(beat)
|
656 |
+
out_beat.append(tokenized_beats)
|
657 |
+
out_beat_timing.append(tokenized_beats_timing)
|
658 |
+
out_mask.append(tokenized_beat_mask)
|
659 |
+
out_beat, out_beat_timing, out_mask = torch.tensor(out_beat).cuda(), torch.tensor(out_beat_timing).cuda(), torch.tensor(out_mask).cuda() #batch, len_beat
|
660 |
+
embedded_beat = self.beat_embedding_layer(out_beat, out_beat_timing)
|
661 |
+
|
662 |
+
embedded_beat = embedded_beat.repeat_interleave(num_samples_per_prompt, 0)
|
663 |
+
out_mask = out_mask.repeat_interleave(num_samples_per_prompt, 0)
|
664 |
+
|
665 |
+
uncond_beats = [[[],[]]] * len(beats)
|
666 |
+
|
667 |
+
max_length = embedded_beat.shape[1]
|
668 |
+
with torch.no_grad():
|
669 |
+
out_beat_unc = []
|
670 |
+
out_beat_timing_unc = []
|
671 |
+
out_mask_unc = []
|
672 |
+
for beat in uncond_beats:
|
673 |
+
tokenized_beats, tokenized_beats_timing, tokenized_beat_mask = self.beat_tokenizer(beat)
|
674 |
+
out_beat_unc.append(tokenized_beats)
|
675 |
+
out_beat_timing_unc.append(tokenized_beats_timing)
|
676 |
+
out_mask_unc.append(tokenized_beat_mask)
|
677 |
+
out_beat_unc, out_beat_timing_unc, out_mask_unc = torch.tensor(out_beat_unc).cuda(), torch.tensor(out_beat_timing_unc).cuda(), torch.tensor(out_mask_unc).cuda() #batch, len_beat
|
678 |
+
embedded_beat_unc = self.beat_embedding_layer(out_beat_unc, out_beat_timing_unc)
|
679 |
+
|
680 |
+
embedded_beat_unc = embedded_beat_unc.repeat_interleave(num_samples_per_prompt, 0)
|
681 |
+
out_mask_unc = out_mask_unc.repeat_interleave(num_samples_per_prompt, 0)
|
682 |
+
|
683 |
+
embedded_beat = torch.cat([embedded_beat_unc, embedded_beat])
|
684 |
+
out_mask = torch.cat([out_mask_unc, out_mask])
|
685 |
+
|
686 |
+
return embedded_beat, out_mask
|
687 |
+
|
688 |
+
|
689 |
+
def encode_chords_classifier_free(self, chords, chords_time, num_samples_per_prompt):
|
690 |
+
|
691 |
+
with torch.no_grad():
|
692 |
+
out_chord_root = []
|
693 |
+
out_chord_type = []
|
694 |
+
out_chord_inv = []
|
695 |
+
out_chord_timing = []
|
696 |
+
out_mask = []
|
697 |
+
for chord, chord_time in zip(chords,chords_time): #batch loop
|
698 |
+
tokenized_chord_root, tokenized_chord_type, tokenized_chord_inv, tokenized_chord_time, tokenized_chord_mask = self.chord_tokenizer(chord, chord_time)
|
699 |
+
out_chord_root.append(tokenized_chord_root)
|
700 |
+
out_chord_type.append(tokenized_chord_type)
|
701 |
+
out_chord_inv.append(tokenized_chord_inv)
|
702 |
+
out_chord_timing.append(tokenized_chord_time)
|
703 |
+
out_mask.append(tokenized_chord_mask)
|
704 |
+
out_chord_root, out_chord_type, out_chord_inv, out_chord_timing, out_mask = torch.tensor(out_chord_root).cuda(), torch.tensor(out_chord_type).cuda(), torch.tensor(out_chord_inv).cuda(), torch.tensor(out_chord_timing).cuda(), torch.tensor(out_mask).cuda()
|
705 |
+
embedded_chord = self.chord_embedding_layer(out_chord_root, out_chord_type, out_chord_inv, out_chord_timing)
|
706 |
+
|
707 |
+
embedded_chord = embedded_chord.repeat_interleave(num_samples_per_prompt, 0)
|
708 |
+
out_mask = out_mask.repeat_interleave(num_samples_per_prompt, 0)
|
709 |
+
|
710 |
+
chords_unc=[[]] * len(chords)
|
711 |
+
chords_time_unc=[[]] * len(chords_time)
|
712 |
+
|
713 |
+
max_length = embedded_chord.shape[1]
|
714 |
+
|
715 |
+
with torch.no_grad():
|
716 |
+
out_chord_root_unc = []
|
717 |
+
out_chord_type_unc = []
|
718 |
+
out_chord_inv_unc = []
|
719 |
+
out_chord_timing_unc = []
|
720 |
+
out_mask_unc = []
|
721 |
+
for chord, chord_time in zip(chords_unc,chords_time_unc): #batch loop
|
722 |
+
tokenized_chord_root, tokenized_chord_type, tokenized_chord_inv, tokenized_chord_time, tokenized_chord_mask = self.chord_tokenizer(chord, chord_time)
|
723 |
+
out_chord_root_unc.append(tokenized_chord_root)
|
724 |
+
out_chord_type_unc.append(tokenized_chord_type)
|
725 |
+
out_chord_inv_unc.append(tokenized_chord_inv)
|
726 |
+
out_chord_timing_unc.append(tokenized_chord_time)
|
727 |
+
out_mask_unc.append(tokenized_chord_mask)
|
728 |
+
out_chord_root_unc, out_chord_type_unc, out_chord_inv_unc, out_chord_timing_unc, out_mask_unc = torch.tensor(out_chord_root_unc).cuda(), torch.tensor(out_chord_type_unc).cuda(), torch.tensor(out_chord_inv_unc).cuda(), torch.tensor(out_chord_timing_unc).cuda(), torch.tensor(out_mask_unc).cuda()
|
729 |
+
embedded_chord_unc = self.chord_embedding_layer(out_chord_root_unc, out_chord_type_unc, out_chord_inv_unc, out_chord_timing_unc)
|
730 |
+
|
731 |
+
|
732 |
+
embedded_chord_unc = embedded_chord_unc.repeat_interleave(num_samples_per_prompt, 0)
|
733 |
+
out_mask_unc = out_mask_unc.repeat_interleave(num_samples_per_prompt, 0)
|
734 |
+
|
735 |
+
embedded_chord = torch.cat([embedded_chord_unc, embedded_chord])
|
736 |
+
out_mask = torch.cat([out_mask_unc, out_mask])
|
737 |
+
|
738 |
+
return embedded_chord, out_mask
|
.ipynb_checkpoints/requirements-checkpoint.txt
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch==1.13.1
|
2 |
+
torchaudio==0.13.1
|
3 |
+
torchvision==0.14.1
|
4 |
+
transformers==4.27.0
|
5 |
+
accelerate==0.18.0
|
6 |
+
datasets==2.1.0
|
7 |
+
einops==0.6.1
|
8 |
+
h5py==3.8.0
|
9 |
+
huggingface_hub==0.13.3
|
10 |
+
importlib_metadata==6.3.0
|
11 |
+
librosa==0.9.2
|
12 |
+
matplotlib==3.5.2
|
13 |
+
numpy==1.23.0
|
14 |
+
omegaconf==2.3.0
|
15 |
+
packaging==23.1
|
16 |
+
pandas==1.4.1
|
17 |
+
progressbar33==2.4
|
18 |
+
protobuf==3.20.*
|
19 |
+
resampy==0.4.2
|
20 |
+
sentencepiece==0.1.99
|
21 |
+
scikit_image==0.19.3
|
22 |
+
scikit_learn==1.2.2
|
23 |
+
scipy==1.8.0
|
24 |
+
soundfile==0.12.1
|
25 |
+
ssr_eval==0.0.6
|
26 |
+
torchlibrosa==0.1.0
|
27 |
+
tqdm==4.63.1
|
28 |
+
wandb==0.12.14
|
29 |
+
ipython==8.12.0
|
30 |
+
gradio==3.28.1
|
31 |
+
wavio==0.0.7
|
requirements.txt
CHANGED
@@ -17,6 +17,7 @@ pandas==1.4.1
|
|
17 |
progressbar33==2.4
|
18 |
protobuf==3.20.*
|
19 |
resampy==0.4.2
|
|
|
20 |
scikit_image==0.19.3
|
21 |
scikit_learn==1.2.2
|
22 |
scipy==1.8.0
|
|
|
17 |
progressbar33==2.4
|
18 |
protobuf==3.20.*
|
19 |
resampy==0.4.2
|
20 |
+
sentencepiece==0.1.99
|
21 |
scikit_image==0.19.3
|
22 |
scikit_learn==1.2.2
|
23 |
scipy==1.8.0
|