Spaces:
Running
on
Zero
Running
on
Zero
keshavbhandari
commited on
Commit
•
2876fc2
1
Parent(s):
1a26908
added model
Browse files- .gitignore +1 -0
- app.py +44 -9
- artifacts/vocab_remi.pkl +3 -0
- requirements.txt +4 -1
- transformer_model.py +1417 -0
.gitignore
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
artifacts/pytorch_model_95.bin
|
app.py
CHANGED
@@ -5,6 +5,11 @@ import soundfile as sf
|
|
5 |
import wavio
|
6 |
import os
|
7 |
import subprocess
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
|
10 |
def save_wav(filepath):
|
@@ -26,14 +31,44 @@ def save_wav(filepath):
|
|
26 |
return wav_filepath
|
27 |
|
28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
# @spaces.GPU(duration=120)
|
30 |
def gradio_generate(prompt, temperature):
|
|
|
|
|
|
|
31 |
# Convert midi to wav
|
32 |
-
filename = "
|
33 |
save_wav(filename)
|
34 |
filename = filename.replace(".mid", ".wav")
|
35 |
-
#
|
36 |
-
# filename = librosa.ex('trumpet')
|
37 |
output_wave, samplerate = sf.read(filename, dtype='float32')
|
38 |
output_filename = "temp.wav"
|
39 |
wavio.write(output_filename, output_wave, rate=16000, sampwidth=2)
|
@@ -71,12 +106,12 @@ gr_interface = gr.Interface(
|
|
71 |
description=description_text,
|
72 |
allow_flagging=False,
|
73 |
examples=[
|
74 |
-
["
|
75 |
-
["
|
76 |
-
["
|
77 |
-
["This
|
78 |
-
["
|
79 |
-
["
|
80 |
],
|
81 |
cache_examples="lazy",
|
82 |
)
|
|
|
5 |
import wavio
|
6 |
import os
|
7 |
import subprocess
|
8 |
+
import pickle
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
from transformers import T5Tokenizer
|
12 |
+
from transformer_model import Transformer
|
13 |
|
14 |
|
15 |
def save_wav(filepath):
|
|
|
31 |
return wav_filepath
|
32 |
|
33 |
|
34 |
+
def generate_midi(caption, temperature=0.9, max_len=3000):
|
35 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
36 |
+
artifact_folder = 'artifacts'
|
37 |
+
|
38 |
+
tokenizer_filepath = os.path.join(artifact_folder, "vocab_remi.pkl")
|
39 |
+
# Load the tokenizer dictionary
|
40 |
+
with open(tokenizer_filepath, "rb") as f:
|
41 |
+
r_tokenizer = pickle.load(f)
|
42 |
+
|
43 |
+
# Get the vocab size
|
44 |
+
vocab_size = len(r_tokenizer)
|
45 |
+
print("Vocab size: ", vocab_size)
|
46 |
+
model = Transformer(vocab_size, 768, 8, 5000, 18, 1024, False, 8, device=device)
|
47 |
+
model.load_state_dict(torch.load('/artifacts/pytorch_model_95.bin', map_location=device))
|
48 |
+
model.eval()
|
49 |
+
tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-base")
|
50 |
+
|
51 |
+
# caption = "A cinematic electronic soundtrack that evokes an epic and dark atmosphere, featuring cello, contrabass, and drums. The song is set in A minor with a moderate tempo and a 4/4 time signature, creating an emotional and action-packed ambiance suitable for film."
|
52 |
+
inputs = tokenizer(caption, return_tensors='pt', padding=True, truncation=True)
|
53 |
+
input_ids = nn.utils.rnn.pad_sequence(inputs.input_ids, batch_first=True, padding_value=0)
|
54 |
+
input_ids = input_ids.to(device)
|
55 |
+
attention_mask =nn.utils.rnn.pad_sequence(inputs.attention_mask, batch_first=True, padding_value=0)
|
56 |
+
attention_mask = attention_mask.to(device)
|
57 |
+
output = model.generate(input_ids, attention_mask, max_len=max_len,temperature = temperature)
|
58 |
+
output_list = output[0].tolist()
|
59 |
+
generated_midi = r_tokenizer.decode(output_list)
|
60 |
+
generated_midi.dump_midi("output.mid")
|
61 |
+
|
62 |
# @spaces.GPU(duration=120)
|
63 |
def gradio_generate(prompt, temperature):
|
64 |
+
# Generate midi
|
65 |
+
generate_midi(prompt, temperature)
|
66 |
+
|
67 |
# Convert midi to wav
|
68 |
+
filename = "output.mid"
|
69 |
save_wav(filename)
|
70 |
filename = filename.replace(".mid", ".wav")
|
71 |
+
# Read the generated WAV file
|
|
|
72 |
output_wave, samplerate = sf.read(filename, dtype='float32')
|
73 |
output_filename = "temp.wav"
|
74 |
wavio.write(output_filename, output_wave, rate=16000, sampwidth=2)
|
|
|
106 |
description=description_text,
|
107 |
allow_flagging=False,
|
108 |
examples=[
|
109 |
+
["A cheerful and melodic pop Christmas song featuring piano, acoustic guitar, vibraphone, bass, and drums, set in the key of Eb minor with a fast tempo of 123 bpm and a 4/4 time signature, creating a joyful and relaxing atmosphere."],
|
110 |
+
["A melodic electronic song with ambient elements, featuring piano, acoustic guitar, alto saxophone, string ensemble, and electric bass. Set in G minor with a 4/4 time signature, it moves at a lively Presto tempo. The composition evokes a blend of relaxation and darkness, with hints of happiness and a meditative quality."],
|
111 |
+
["This motivational electronic and pop song features a clean electric guitar, rock organ, synth voice, acoustic guitar, and vibraphone, creating a melodic and uplifting atmosphere. Set in the key of G# minor with a 4/4 time signature, the track moves at an energetic Allegro tempo of 120 beats per minute. The chord progression of Bbm7 and F# adds to the song's inspiring and corporate feel."],
|
112 |
+
["This short electronic song in C minor features a brass section, string ensemble, tenor saxophone, clean electric guitar, and slap bass, creating a melodic and slightly dark atmosphere. With a tempo of 124 BPM (Allegro) and a 4/4 time signature, the track incorporates a chord progression of C7/E, Eb6, and Bbm6, adding a touch of corporate and motivational vibes to the overall composition."],
|
113 |
+
["An energetic and melodic electronic trance track with a space and retro vibe, featuring drums, distortion guitar, flute, synth bass, and slap bass. Set in A minor with a fast tempo of 138 BPM, the song maintains a 4/4 time signature throughout its duration."],
|
114 |
+
["A short but energetic rock fragment in C minor, featuring overdriven guitars, electric bass, and drums, with a vivacious tempo of 155 BPM and a 4/4 time signature, evoking a blend of dark and melodic tones."],
|
115 |
],
|
116 |
cache_examples="lazy",
|
117 |
)
|
artifacts/vocab_remi.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:513a5e8df7d53624930fd74139f6d2451d07c172504e0d0ee074d8ecb2a40d26
|
3 |
+
size 1540482
|
requirements.txt
CHANGED
@@ -1,2 +1,5 @@
|
|
1 |
librosa==0.10.2
|
2 |
-
wavio==0.0.9
|
|
|
|
|
|
|
|
1 |
librosa==0.10.2
|
2 |
+
wavio==0.0.9
|
3 |
+
torch
|
4 |
+
transformers
|
5 |
+
st-moe-pytorch
|
transformer_model.py
ADDED
@@ -0,0 +1,1417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# from aria.tokenizer import AbsTokenizer
|
2 |
+
# aria_tokenizer = AbsTokenizer()
|
3 |
+
import copy
|
4 |
+
import json
|
5 |
+
from typing import Optional, Any, Union, Callable
|
6 |
+
import torch.multiprocessing as mp
|
7 |
+
from torch.nn import DataParallel
|
8 |
+
import jsonlines
|
9 |
+
import math
|
10 |
+
import time
|
11 |
+
import torch
|
12 |
+
import os
|
13 |
+
import warnings
|
14 |
+
from tqdm import tqdm
|
15 |
+
from torch import Tensor
|
16 |
+
from aria.tokenizer import AbsTokenizer
|
17 |
+
import pickle
|
18 |
+
from torch.nn import Module, LayerNorm, Dropout, Linear
|
19 |
+
from torch.nn.modules.container import ModuleList
|
20 |
+
from torch.nn.modules.activation import MultiheadAttention
|
21 |
+
from torch.nn.init import xavier_uniform_
|
22 |
+
import torch.nn.functional as F
|
23 |
+
import torch.nn as nn
|
24 |
+
|
25 |
+
from st_moe_pytorch import MoE
|
26 |
+
from st_moe_pytorch import SparseMoEBlock
|
27 |
+
|
28 |
+
from einops import rearrange
|
29 |
+
|
30 |
+
from transformers import T5Tokenizer, T5EncoderModel
|
31 |
+
|
32 |
+
|
33 |
+
__all__ = ['Transformer', 'TransformerEncoder', 'TransformerDecoder', 'TransformerEncoderLayer', 'TransformerDecoderLayer']
|
34 |
+
|
35 |
+
def _generate_square_subsequent_mask(
|
36 |
+
sz: int,
|
37 |
+
device: Optional[torch.device] = None,
|
38 |
+
dtype: Optional[torch.dtype] = None,
|
39 |
+
) -> Tensor:
|
40 |
+
r"""Generate a square causal mask for the sequence.
|
41 |
+
|
42 |
+
The masked positions are filled with float('-inf'). Unmasked positions are filled with float(0.0).
|
43 |
+
"""
|
44 |
+
if device is None:
|
45 |
+
device = torch.device('cpu')
|
46 |
+
if dtype is None:
|
47 |
+
dtype = torch.float32
|
48 |
+
return torch.triu(
|
49 |
+
torch.full((sz, sz), float('-inf'), dtype=dtype, device=device),
|
50 |
+
diagonal=1,
|
51 |
+
)
|
52 |
+
|
53 |
+
|
54 |
+
def _get_seq_len(
|
55 |
+
src: Tensor,
|
56 |
+
batch_first: bool
|
57 |
+
) -> Optional[int]:
|
58 |
+
|
59 |
+
if src.is_nested:
|
60 |
+
return None
|
61 |
+
else:
|
62 |
+
src_size = src.size()
|
63 |
+
if len(src_size) == 2:
|
64 |
+
# unbatched: S, E
|
65 |
+
return src_size[0]
|
66 |
+
else:
|
67 |
+
# batched: B, S, E if batch_first else S, B, E
|
68 |
+
seq_len_pos = 1 if batch_first else 0
|
69 |
+
return src_size[seq_len_pos]
|
70 |
+
|
71 |
+
|
72 |
+
class PositionalEncoding(nn.Module):
|
73 |
+
r"""Inject some information about the relative or absolute position of the tokens in the sequence.
|
74 |
+
The positional encodings have the same dimension as the embeddings, so that the two can be summed.
|
75 |
+
Here, we use sine and cosine functions of different frequencies.
|
76 |
+
.. math:
|
77 |
+
\text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model))
|
78 |
+
\text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model))
|
79 |
+
\text{where pos is the word position and i is the embed idx)
|
80 |
+
Args:
|
81 |
+
d_model: the embed dim (required).
|
82 |
+
dropout: the dropout value (default=0.1).
|
83 |
+
max_len: the max. length of the incoming sequence (default=5000).
|
84 |
+
Examples:
|
85 |
+
>>> pos_encoder = PositionalEncoding(d_model)
|
86 |
+
"""
|
87 |
+
|
88 |
+
def __init__(self, d_model, dropout=0.1, max_len=5000):
|
89 |
+
super(PositionalEncoding, self).__init__()
|
90 |
+
self.dropout = nn.Dropout(p=dropout)
|
91 |
+
|
92 |
+
pe = torch.zeros(max_len, d_model)
|
93 |
+
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
|
94 |
+
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
95 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
96 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
97 |
+
pe = pe.unsqueeze(0).transpose(0, 1)
|
98 |
+
# self.register_buffer('pe', pe)
|
99 |
+
self.register_parameter('pe', nn.Parameter(pe, requires_grad=False))
|
100 |
+
|
101 |
+
def forward(self, x):
|
102 |
+
r"""Inputs of forward function
|
103 |
+
Args:
|
104 |
+
x: the sequence fed to the positional encoder model (required).
|
105 |
+
Shape:
|
106 |
+
x: [sequence length, batch size, embed dim]
|
107 |
+
output: [sequence length, batch size, embed dim]
|
108 |
+
Examples:
|
109 |
+
>>> output = pos_encoder(x)
|
110 |
+
"""
|
111 |
+
x = x + self.pe[:x.size(0), :]
|
112 |
+
return self.dropout(x)
|
113 |
+
|
114 |
+
|
115 |
+
def precompute_freqs_cis(
|
116 |
+
seq_len: int,
|
117 |
+
n_elem: int,
|
118 |
+
base: int = 10000,
|
119 |
+
dtype: torch.dtype = torch.bfloat16,
|
120 |
+
):
|
121 |
+
freqs = 1.0 / (
|
122 |
+
base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem)
|
123 |
+
)
|
124 |
+
t = torch.arange(seq_len, device=freqs.device)
|
125 |
+
freqs = torch.outer(t, freqs)
|
126 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
|
127 |
+
cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
|
128 |
+
|
129 |
+
return cache.to(dtype=dtype)
|
130 |
+
|
131 |
+
|
132 |
+
@torch.jit.script
|
133 |
+
def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
|
134 |
+
"""
|
135 |
+
In-place RoPE. Credits to Katherine Crowson:
|
136 |
+
x shape (b_sz, n_head, s_len, d_head).
|
137 |
+
cos, sin shape (s_len, d_head // 2).
|
138 |
+
"""
|
139 |
+
|
140 |
+
x = x.permute(0, 2, 1, 3)
|
141 |
+
d = x.shape[-1] // 2
|
142 |
+
cos = freqs_cis[..., 0][None, :, None]
|
143 |
+
sin = freqs_cis[..., 1][None, :, None]
|
144 |
+
x1, x2 = x[..., :d], x[..., d : d * 2]
|
145 |
+
tmp = x1.clone()
|
146 |
+
# x1.mul_(cos).addcmul_(x2, sin, value=-1)
|
147 |
+
# x2.mul_(cos).addcmul_(tmp, sin, value=1) ##was throwing some error: RuntimeError: Output 0 of SliceBackward0 is a view and is being modified inplace. This view is the output of a function that returns multiple views. Such functions do not allow the output views to be modified inplace. You should replace the inplace operation by an out-of-place one.
|
148 |
+
x1_new = x1.mul(cos) - x2.mul(sin)
|
149 |
+
x2_new = x2.mul(cos) + tmp.mul(sin)
|
150 |
+
x = torch.cat((x1_new, x2_new), dim=-1)
|
151 |
+
x = x.permute(0, 2, 1, 3)
|
152 |
+
|
153 |
+
return x
|
154 |
+
|
155 |
+
|
156 |
+
class MultiHeadSelfAttention(nn.Module):
|
157 |
+
r"""Multi-head self-attention module.
|
158 |
+
|
159 |
+
Args:
|
160 |
+
embed_dim (int): The input embedding dimension.
|
161 |
+
num_heads (int, optional): The number of attention heads (default: 4).
|
162 |
+
dropout (float, optional): The dropout probability (default: 0.1).
|
163 |
+
device (torch.device, optional): The device to use (default: None).
|
164 |
+
dtype (torch.dtype, optional): The data type to use (default: None).
|
165 |
+
|
166 |
+
Attributes:
|
167 |
+
dim_head (int): The dimension of each attention head.
|
168 |
+
scale (float): The scaling factor for attention scores.
|
169 |
+
heads (int): The number of attention heads.
|
170 |
+
to_qkv (nn.Linear): Linear layer for projecting input to query, key, and value.
|
171 |
+
to_out (nn.Linear): Linear layer for projecting attention output to the original embedding dimension.
|
172 |
+
dropout (nn.Dropout): Dropout layer.
|
173 |
+
|
174 |
+
"""
|
175 |
+
|
176 |
+
def __init__(
|
177 |
+
self,
|
178 |
+
embed_dim: int,
|
179 |
+
num_heads: int = 4,
|
180 |
+
dropout: float = 0.1,
|
181 |
+
batch_first: bool = True,
|
182 |
+
device: Optional[torch.device] = None,
|
183 |
+
dtype: Optional[torch.dtype] = None,
|
184 |
+
):
|
185 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
186 |
+
super().__init__()
|
187 |
+
self.embed_dim = embed_dim
|
188 |
+
self.batch_first = batch_first
|
189 |
+
self.dim_head = embed_dim // num_heads
|
190 |
+
self.scale = self.dim_head ** -0.5
|
191 |
+
self.heads = num_heads
|
192 |
+
hidden_dim = self.dim_head * num_heads
|
193 |
+
self.to_qkv = nn.Linear(embed_dim, hidden_dim * 3, bias=False, **factory_kwargs)
|
194 |
+
self.to_out = nn.Linear(hidden_dim, embed_dim, bias=False, **factory_kwargs)
|
195 |
+
self.dropout = nn.Dropout(dropout)
|
196 |
+
|
197 |
+
def forward(self, x: torch.Tensor, is_causal: bool = True) -> torch.Tensor:
|
198 |
+
|
199 |
+
r"""Forward pass of the multi-head self-attention module.
|
200 |
+
|
201 |
+
Args:
|
202 |
+
x (torch.Tensor): The input tensor of shape (batch_size, sequence_length, embed_dim).
|
203 |
+
|
204 |
+
Returns:
|
205 |
+
torch.Tensor: The output tensor of shape (batch_size, sequence_length, embed_dim).
|
206 |
+
|
207 |
+
"""
|
208 |
+
if not self.batch_first:
|
209 |
+
x = x.transpose(0, 1)
|
210 |
+
b, n, _ = x.size()
|
211 |
+
q, k, v = torch.chunk(self.to_qkv(x), chunks=3, dim=-1)
|
212 |
+
q, k, v = map(lambda t: t.contiguous().view(b, self.heads, n, -1), (q, k, v))
|
213 |
+
|
214 |
+
self.freqs_cis = precompute_freqs_cis(
|
215 |
+
seq_len=n,
|
216 |
+
n_elem=self.embed_dim // self.heads,
|
217 |
+
base=10000,
|
218 |
+
dtype=x.dtype,
|
219 |
+
).to(x.device)
|
220 |
+
freqs_cis = self.freqs_cis[: x.shape[1]]
|
221 |
+
# q = apply_rotary_emb(q, freqs_cis)
|
222 |
+
# k = apply_rotary_emb(k, freqs_cis)
|
223 |
+
out = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=is_causal)
|
224 |
+
out = out.contiguous().view(b, n, -1)
|
225 |
+
out = self.dropout(out)
|
226 |
+
return self.to_out(out)
|
227 |
+
|
228 |
+
|
229 |
+
class Transformer(Module):
|
230 |
+
r"""A transformer model.
|
231 |
+
|
232 |
+
User is able to modify the attributes as needed. The architecture
|
233 |
+
is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer,
|
234 |
+
Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and
|
235 |
+
Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information
|
236 |
+
Processing Systems, pages 6000-6010.
|
237 |
+
|
238 |
+
Args:
|
239 |
+
d_model: the number of expected features in the encoder/decoder inputs (default=512).
|
240 |
+
nhead: the number of heads in the multiheadattention models (default=8).
|
241 |
+
num_encoder_layers: the number of sub-encoder-layers in the encoder (default=6).
|
242 |
+
num_decoder_layers: the number of sub-decoder-layers in the decoder (default=6).
|
243 |
+
dim_feedforward: the dimension of the feedforward network model (default=2048).
|
244 |
+
use_moe: if True, use MoE instead of linear layer for feedforward network (default=False).
|
245 |
+
dropout: the dropout value (default=0.1).
|
246 |
+
activation: the activation function of encoder/decoder intermediate layer, can be a string
|
247 |
+
("relu" or "gelu") or a unary callable. Default: relu
|
248 |
+
custom_encoder: custom encoder (default=None).
|
249 |
+
custom_decoder: custom decoder (default=None).
|
250 |
+
layer_norm_eps: the eps value in layer normalization components (default=1e-5).
|
251 |
+
batch_first: If ``True``, then the input and output tensors are provided
|
252 |
+
as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
|
253 |
+
norm_first: if ``True``, encoder and decoder layers will perform LayerNorms before
|
254 |
+
other attention and feedforward operations, otherwise after. Default: ``False`` (after).
|
255 |
+
bias: If set to ``False``, ``Linear`` and ``LayerNorm`` layers will not learn an additive
|
256 |
+
bias. Default: ``True``.
|
257 |
+
|
258 |
+
Examples::
|
259 |
+
>>> transformer_model = nn.Transformer(nhead=16, num_encoder_layers=12)
|
260 |
+
>>> src = torch.rand((32, 512))
|
261 |
+
>>> tgt = torch.rand((32, 512, 30000))
|
262 |
+
>>> out = transformer_model(src, tgt)
|
263 |
+
|
264 |
+
Note: A full example to apply nn.Transformer module for the word language model is available in
|
265 |
+
https://github.com/pytorch/examples/tree/master/word_language_model
|
266 |
+
"""
|
267 |
+
|
268 |
+
def __init__(self, n_vocab: int = 30000, d_model: int = 512, nhead: int = 8, max_len: int = 5000,
|
269 |
+
num_decoder_layers: int = 6, dim_feedforward: int = 2048, use_moe: bool = False,
|
270 |
+
num_experts: int = 16, dropout: float = 0.1,
|
271 |
+
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
|
272 |
+
layer_norm_eps: float = 1e-5, batch_first: bool = True, norm_first: bool = False,
|
273 |
+
bias: bool = True, device=None, dtype=None) -> None:
|
274 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
275 |
+
super().__init__()
|
276 |
+
torch._C._log_api_usage_once(f"torch.nn.modules.{self.__class__.__name__}")
|
277 |
+
|
278 |
+
self.use_moe = use_moe
|
279 |
+
|
280 |
+
self.input_emb = nn.Embedding(n_vocab, d_model, **factory_kwargs)
|
281 |
+
self.pos_encoder = PositionalEncoding(d_model, dropout, max_len).to(device)
|
282 |
+
|
283 |
+
# Load the FLAN-T5 encoder
|
284 |
+
self.encoder = T5EncoderModel.from_pretrained("google/flan-t5-base").to(device)
|
285 |
+
# Freeze the encoder
|
286 |
+
for param in self.encoder.parameters():
|
287 |
+
param.requires_grad = False
|
288 |
+
|
289 |
+
decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, use_moe, num_experts, dropout,
|
290 |
+
activation, layer_norm_eps, batch_first, norm_first,
|
291 |
+
bias, **factory_kwargs)
|
292 |
+
decoder_norm = LayerNorm(d_model, eps=layer_norm_eps, bias=bias, **factory_kwargs)
|
293 |
+
self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, use_moe, decoder_norm)
|
294 |
+
|
295 |
+
self.projection = nn.Linear(d_model, n_vocab).to(device)
|
296 |
+
|
297 |
+
self._reset_parameters()
|
298 |
+
|
299 |
+
self.d_model = d_model
|
300 |
+
self.nhead = nhead
|
301 |
+
|
302 |
+
self.batch_first = batch_first
|
303 |
+
|
304 |
+
def forward(self, src: Tensor, src_mask: Tensor, tgt: Tensor, memory_mask: Optional[Tensor] = None,
|
305 |
+
memory_key_padding_mask: Optional[Tensor] = None, tgt_is_causal: bool = True,
|
306 |
+
memory_is_causal: bool = False) -> Tensor:
|
307 |
+
r"""Take in and process masked source/target sequences.
|
308 |
+
|
309 |
+
.. note::
|
310 |
+
|
311 |
+
If a boolean tensor is provided for any of the [src/tgt/memory]_mask arguments, positions with a ``True`` value are
|
312 |
+
not allowed to participate in the attention,
|
313 |
+
which is the opposite of the definition for :attr:`attn_mask`
|
314 |
+
in :func:`torch.nn.functional.scaled_dot_product_attention`.
|
315 |
+
|
316 |
+
Args:
|
317 |
+
src: the sequence to the encoder (required).
|
318 |
+
src_attn_mask: the attention mask for the src sequence (required).
|
319 |
+
tgt: the sequence to the decoder (required).
|
320 |
+
tgt_mask: the additive mask for the tgt sequence (optional).
|
321 |
+
memory_mask: the additive mask for the encoder output (optional).
|
322 |
+
tgt_key_padding_mask: the Tensor mask for tgt keys per batch (optional).
|
323 |
+
memory_key_padding_mask: the Tensor mask for memory keys per batch (optional).
|
324 |
+
tgt_is_causal: If specified, applies a causal mask as ``tgt_mask``.
|
325 |
+
Default: ``None``; try to detect a causal mask.
|
326 |
+
Warning:
|
327 |
+
``tgt_is_causal`` provides a hint that ``tgt_mask`` is
|
328 |
+
the causal mask. Providing incorrect hints can result in
|
329 |
+
incorrect execution, including forward and backward
|
330 |
+
compatibility.
|
331 |
+
memory_is_causal: If specified, applies a causal mask as
|
332 |
+
``memory_mask``.
|
333 |
+
Default: ``False``.
|
334 |
+
Warning:
|
335 |
+
``memory_is_causal`` provides a hint that
|
336 |
+
``memory_mask`` is the causal mask. Providing incorrect
|
337 |
+
hints can result in incorrect execution, including
|
338 |
+
forward and backward compatibility.
|
339 |
+
|
340 |
+
Shape:
|
341 |
+
- src: :math:`(S, S)` for unbatched input, :math:`(S, N)` if `batch_first=False` or
|
342 |
+
`(N, S)` if `batch_first=True`.
|
343 |
+
- src_mask: :math:`(S, S)` or :math:`(N\cdot\text{num\_heads}, S, S)`.
|
344 |
+
- tgt: :math:`(T, E)` for unbatched input, :math:`(T, N, E)` if `batch_first=False` or
|
345 |
+
`(N, T, E)` if `batch_first=True`.
|
346 |
+
- tgt_mask: :math:`(T, T)` or :math:`(N\cdot\text{num\_heads}, T, T)`.
|
347 |
+
- memory_mask: :math:`(T, S)`.
|
348 |
+
- src_key_padding_mask: :math:`(S)` for unbatched input otherwise :math:`(N, S)`.
|
349 |
+
- tgt_key_padding_mask: :math:`(T)` for unbatched input otherwise :math:`(N, T)`.
|
350 |
+
- memory_key_padding_mask: :math:`(S)` for unbatched input otherwise :math:`(N, S)`.
|
351 |
+
|
352 |
+
Note: [src/tgt/memory]_mask ensures that position :math:`i` is allowed to attend the unmasked
|
353 |
+
positions. If a BoolTensor is provided, positions with ``True``
|
354 |
+
are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
|
355 |
+
is provided, it will be added to the attention weight.
|
356 |
+
[src/tgt/memory]_key_padding_mask provides specified elements in the key to be ignored by
|
357 |
+
the attention. If a BoolTensor is provided, the positions with the
|
358 |
+
value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
|
359 |
+
|
360 |
+
- output: :math:`(T, E)` for unbatched input, :math:`(T, N, E)` if `batch_first=False` or
|
361 |
+
`(N, T, E)` if `batch_first=True`.
|
362 |
+
|
363 |
+
Note: Due to the multi-head attention architecture in the transformer model,
|
364 |
+
the output sequence length of a transformer is same as the input sequence
|
365 |
+
(i.e. target) length of the decoder.
|
366 |
+
|
367 |
+
where :math:`S` is the source sequence length, :math:`T` is the target sequence length, :math:`N` is the
|
368 |
+
batch size, :math:`E` is the feature number
|
369 |
+
|
370 |
+
Examples:
|
371 |
+
>>> # xdoctest: +SKIP
|
372 |
+
>>> output = transformer_model(src, tgt, src_mask=src_mask)
|
373 |
+
"""
|
374 |
+
if src.dim() != tgt.dim():
|
375 |
+
raise RuntimeError("the number of dimensions in src and tgt must be equal")
|
376 |
+
|
377 |
+
memory = self.encoder(src, attention_mask=src_mask).last_hidden_state
|
378 |
+
|
379 |
+
tgt = self.input_emb(tgt) * math.sqrt(self.d_model)
|
380 |
+
tgt = self.pos_encoder(tgt)
|
381 |
+
# tgt = tgt + tgt_pos
|
382 |
+
|
383 |
+
if self.use_moe:
|
384 |
+
with torch.cuda.amp.autocast(enabled =False):
|
385 |
+
output, sum_total_aux_loss = self.decoder(tgt, memory, memory_mask=memory_mask,
|
386 |
+
memory_key_padding_mask=memory_key_padding_mask,
|
387 |
+
tgt_is_causal=tgt_is_causal, memory_is_causal=memory_is_causal)
|
388 |
+
else:
|
389 |
+
output = self.decoder(tgt, memory, memory_mask=memory_mask,
|
390 |
+
memory_key_padding_mask=memory_key_padding_mask,
|
391 |
+
tgt_is_causal=tgt_is_causal, memory_is_causal=memory_is_causal)
|
392 |
+
|
393 |
+
output = self.projection(output)
|
394 |
+
# output = F.log_softmax(output, dim=-1)
|
395 |
+
|
396 |
+
if self.use_moe:
|
397 |
+
return output, sum_total_aux_loss
|
398 |
+
else:
|
399 |
+
return output
|
400 |
+
|
401 |
+
def generate(self, src: Tensor, src_mask: Tensor, max_len: int = 100, temperature: float = 1.0):
|
402 |
+
## ADD A START OF SEQUENCE TOKEN <SS> token to the src tensor
|
403 |
+
r"""Generate a sequence of tokens from the given inputs.
|
404 |
+
|
405 |
+
Args:
|
406 |
+
src: the sequence to the encoder (required).
|
407 |
+
src_mask: the attention mask for the src sequence (required).
|
408 |
+
max_len: the maximum length of the sequence to generate (default=100).
|
409 |
+
temperature: the temperature for the softmax (default=1.0).
|
410 |
+
|
411 |
+
Returns:
|
412 |
+
torch.Tensor: The generated sequence of tokens.
|
413 |
+
|
414 |
+
"""
|
415 |
+
if src.dim() != 2:
|
416 |
+
raise RuntimeError("The src tensor should be 2-dimensional")
|
417 |
+
tgt_fin = torch.full((src.size(0), 1), 1, dtype=torch.long, device=src.device)
|
418 |
+
# values = [21631, 8, 10, 9, 6, 7, 17, 21632, 11474, 20626, 21151, 9426, 20627, 21143, 11476, 20640, 21143, 11477, 20655, 21145, 11476, 20669, 21145, 11477, 20683, 21145, 13527, 20697, 21146, 13529, 20712, 21145, 7013, 20769, 21143, 7006, 20769, 21143, 7006, 20769, 21141, 7009, 20769, 21143, 9426, 20797, 21144, 11474, 20797, 21173, 11476, 20812, 21144, 11477, 20826, 21145, 11476, 20840, 21145, 11477, 20855, 21145, 13527, 20869, 21144, 13529, 20883, 21143, 7006, 20940, 21139, 7013, 20940, 21140, 7006, 20940, 21147, 7009, 20940, 21147, 11474, 20969, 21144, 11474, 20969, 21170, 11476, 20983, 21144, 11477, 20997, 21145, 11476, 21012, 21144, 11477, 21026, 21144, 11479, 21040]
|
419 |
+
# values_tensor = torch.tensor(values, dtype=torch.long, device=src.device)
|
420 |
+
# tgt_fin = values_tensor.unsqueeze(0).repeat(src.size(0), 1)
|
421 |
+
for i in tqdm(range(max_len)):
|
422 |
+
max_index = tgt_fin.max()
|
423 |
+
# assert max_index < 21634, "tgt_fin contains index out of range. Adjust n_vocab or fix tgt_fin indices."
|
424 |
+
tgt = tgt_fin
|
425 |
+
if self.use_moe:
|
426 |
+
output, _ = self.froward(src, src_mask, tgt, memory_mask=None,
|
427 |
+
memory_key_padding_mask=None,
|
428 |
+
tgt_is_causal=True, memory_is_causal=False)
|
429 |
+
else:
|
430 |
+
output = self.forward(src, src_mask, tgt, memory_mask=None,
|
431 |
+
memory_key_padding_mask=None,
|
432 |
+
tgt_is_causal=True, memory_is_causal=False)
|
433 |
+
# logits = self.projection(output)
|
434 |
+
logits = output
|
435 |
+
output = F.log_softmax(logits/temperature, dim=-1)
|
436 |
+
output = output.view(-1, output.size(-1))
|
437 |
+
next_tokens = torch.multinomial(torch.exp(output), 1)[-1] # taking the last logit and adding to the sequence
|
438 |
+
tgt_fin = torch.cat((tgt_fin, next_tokens.unsqueeze(-1)), dim=1)
|
439 |
+
return tgt_fin[:, 1:]
|
440 |
+
|
441 |
+
@staticmethod
|
442 |
+
def generate_square_subsequent_mask(
|
443 |
+
sz: int,
|
444 |
+
device: Optional[torch.device] = None,
|
445 |
+
dtype: Optional[torch.dtype] = None,
|
446 |
+
) -> Tensor:
|
447 |
+
r"""Generate a square causal mask for the sequence.
|
448 |
+
|
449 |
+
The masked positions are filled with float('-inf'). Unmasked positions are filled with float(0.0).
|
450 |
+
"""
|
451 |
+
return _generate_square_subsequent_mask(sz, dtype=dtype, device=device)
|
452 |
+
|
453 |
+
|
454 |
+
def _reset_parameters(self):
|
455 |
+
r"""Initiate parameters in the transformer model."""
|
456 |
+
for p in self.parameters():
|
457 |
+
if p.dim() > 1:
|
458 |
+
xavier_uniform_(p)
|
459 |
+
|
460 |
+
|
461 |
+
|
462 |
+
|
463 |
+
class TransformerEncoder(Module):
|
464 |
+
r"""TransformerEncoder is a stack of N encoder layers.
|
465 |
+
|
466 |
+
Users can build the BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
|
467 |
+
|
468 |
+
Args:
|
469 |
+
encoder_layer: an instance of the TransformerEncoderLayer() class (required).
|
470 |
+
num_layers: the number of sub-encoder-layers in the encoder (required).
|
471 |
+
norm: the layer normalization component (optional).
|
472 |
+
enable_nested_tensor: if True, input will automatically convert to nested tensor
|
473 |
+
(and convert back on output). This will improve the overall performance of
|
474 |
+
TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
|
475 |
+
|
476 |
+
Examples::
|
477 |
+
>>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8)
|
478 |
+
>>> transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=6)
|
479 |
+
>>> src = torch.rand(10, 32, 512)
|
480 |
+
>>> out = transformer_encoder(src)
|
481 |
+
"""
|
482 |
+
|
483 |
+
__constants__ = ['norm']
|
484 |
+
|
485 |
+
def __init__(
|
486 |
+
self,
|
487 |
+
encoder_layer: "TransformerEncoderLayer",
|
488 |
+
num_layers: int,
|
489 |
+
norm: Optional[Module] = None,
|
490 |
+
enable_nested_tensor: bool = True,
|
491 |
+
mask_check: bool = True
|
492 |
+
) -> None:
|
493 |
+
super().__init__()
|
494 |
+
torch._C._log_api_usage_once(f"torch.nn.modules.{self.__class__.__name__}")
|
495 |
+
self.layers = _get_clones(encoder_layer, num_layers)
|
496 |
+
self.num_layers = num_layers
|
497 |
+
self.norm = norm
|
498 |
+
# this attribute saves the value providedat object construction
|
499 |
+
self.enable_nested_tensor = enable_nested_tensor
|
500 |
+
# this attribute controls whether nested tensors are used
|
501 |
+
self.use_nested_tensor = enable_nested_tensor
|
502 |
+
self.mask_check = mask_check
|
503 |
+
|
504 |
+
enc_layer = "encoder_layer"
|
505 |
+
why_not_sparsity_fast_path = ''
|
506 |
+
if not isinstance(encoder_layer, torch.nn.TransformerEncoderLayer):
|
507 |
+
why_not_sparsity_fast_path = f"{enc_layer} was not TransformerEncoderLayer"
|
508 |
+
elif encoder_layer.norm_first :
|
509 |
+
why_not_sparsity_fast_path = f"{enc_layer}.norm_first was True"
|
510 |
+
elif not encoder_layer.self_attn.batch_first:
|
511 |
+
why_not_sparsity_fast_path = (f"{enc_layer}.self_attn.batch_first was not True" +
|
512 |
+
"(use batch_first for better inference performance)")
|
513 |
+
elif not encoder_layer.self_attn._qkv_same_embed_dim:
|
514 |
+
why_not_sparsity_fast_path = f"{enc_layer}.self_attn._qkv_same_embed_dim was not True"
|
515 |
+
elif encoder_layer.self_attn.in_proj_bias is None:
|
516 |
+
why_not_sparsity_fast_path = f"{enc_layer}.self_attn was passed bias=False"
|
517 |
+
elif not encoder_layer.activation_relu_or_gelu:
|
518 |
+
why_not_sparsity_fast_path = f"{enc_layer}.activation_relu_or_gelu was not True"
|
519 |
+
elif not (encoder_layer.norm1.eps == encoder_layer.norm2.eps) :
|
520 |
+
why_not_sparsity_fast_path = f"{enc_layer}.norm1.eps was not equal to {enc_layer}.norm2.eps"
|
521 |
+
elif encoder_layer.self_attn.num_heads % 2 == 1:
|
522 |
+
why_not_sparsity_fast_path = f"{enc_layer}.self_attn.num_heads is odd"
|
523 |
+
|
524 |
+
if enable_nested_tensor and why_not_sparsity_fast_path:
|
525 |
+
warnings.warn(f"enable_nested_tensor is True, but self.use_nested_tensor is False because {why_not_sparsity_fast_path}")
|
526 |
+
self.use_nested_tensor = False
|
527 |
+
|
528 |
+
|
529 |
+
|
530 |
+
def forward(
|
531 |
+
self,
|
532 |
+
src: Tensor,
|
533 |
+
mask: Optional[Tensor] = None,
|
534 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
535 |
+
is_causal: Optional[bool] = None) -> Tensor:
|
536 |
+
r"""Pass the input through the encoder layers in turn.
|
537 |
+
|
538 |
+
Args:
|
539 |
+
src: the sequence to the encoder (required).
|
540 |
+
mask: the mask for the src sequence (optional).
|
541 |
+
src_key_padding_mask: the mask for the src keys per batch (optional).
|
542 |
+
is_causal: If specified, applies a causal mask as ``mask``.
|
543 |
+
Default: ``None``; try to detect a causal mask.
|
544 |
+
Warning:
|
545 |
+
``is_causal`` provides a hint that ``mask`` is the
|
546 |
+
causal mask. Providing incorrect hints can result in
|
547 |
+
incorrect execution, including forward and backward
|
548 |
+
compatibility.
|
549 |
+
|
550 |
+
Shape:
|
551 |
+
see the docs in :class:`~torch.nn.Transformer`.
|
552 |
+
"""
|
553 |
+
src_key_padding_mask = F._canonical_mask(
|
554 |
+
mask=src_key_padding_mask,
|
555 |
+
mask_name="src_key_padding_mask",
|
556 |
+
other_type=F._none_or_dtype(mask),
|
557 |
+
other_name="mask",
|
558 |
+
target_type=src.dtype
|
559 |
+
)
|
560 |
+
|
561 |
+
mask = F._canonical_mask(
|
562 |
+
mask=mask,
|
563 |
+
mask_name="mask",
|
564 |
+
other_type=None,
|
565 |
+
other_name="",
|
566 |
+
target_type=src.dtype,
|
567 |
+
check_other=False,
|
568 |
+
)
|
569 |
+
|
570 |
+
output = src
|
571 |
+
convert_to_nested = False
|
572 |
+
first_layer = self.layers[0]
|
573 |
+
src_key_padding_mask_for_layers = src_key_padding_mask
|
574 |
+
why_not_sparsity_fast_path = ''
|
575 |
+
str_first_layer = "self.layers[0]"
|
576 |
+
batch_first = first_layer.self_attn.batch_first
|
577 |
+
# is_fastpath_enabled = torch.backends.mha.get_fastpath_enabled()
|
578 |
+
|
579 |
+
# if not is_fastpath_enabled:
|
580 |
+
# why_not_sparsity_fast_path = "torch.backends.mha.get_fastpath_enabled() was not True"
|
581 |
+
if not hasattr(self, "use_nested_tensor"):
|
582 |
+
why_not_sparsity_fast_path = "use_nested_tensor attribute not present"
|
583 |
+
elif not self.use_nested_tensor:
|
584 |
+
why_not_sparsity_fast_path = "self.use_nested_tensor (set in init) was not True"
|
585 |
+
elif first_layer.training:
|
586 |
+
why_not_sparsity_fast_path = f"{str_first_layer} was in training mode"
|
587 |
+
elif not src.dim() == 3:
|
588 |
+
why_not_sparsity_fast_path = f"input not batched; expected src.dim() of 3 but got {src.dim()}"
|
589 |
+
elif src_key_padding_mask is None:
|
590 |
+
why_not_sparsity_fast_path = "src_key_padding_mask was None"
|
591 |
+
elif (((not hasattr(self, "mask_check")) or self.mask_check)
|
592 |
+
and not torch._nested_tensor_from_mask_left_aligned(src, src_key_padding_mask.logical_not())):
|
593 |
+
why_not_sparsity_fast_path = "mask_check enabled, and src and src_key_padding_mask was not left aligned"
|
594 |
+
elif output.is_nested:
|
595 |
+
why_not_sparsity_fast_path = "NestedTensor input is not supported"
|
596 |
+
elif mask is not None:
|
597 |
+
why_not_sparsity_fast_path = "src_key_padding_mask and mask were both supplied"
|
598 |
+
elif torch.is_autocast_enabled():
|
599 |
+
why_not_sparsity_fast_path = "autocast is enabled"
|
600 |
+
|
601 |
+
if not why_not_sparsity_fast_path:
|
602 |
+
tensor_args = (
|
603 |
+
src,
|
604 |
+
first_layer.self_attn.in_proj_weight,
|
605 |
+
first_layer.self_attn.in_proj_bias,
|
606 |
+
first_layer.self_attn.out_proj.weight,
|
607 |
+
first_layer.self_attn.out_proj.bias,
|
608 |
+
first_layer.norm1.weight,
|
609 |
+
first_layer.norm1.bias,
|
610 |
+
first_layer.norm2.weight,
|
611 |
+
first_layer.norm2.bias,
|
612 |
+
first_layer.linear1.weight,
|
613 |
+
first_layer.linear1.bias,
|
614 |
+
first_layer.linear2.weight,
|
615 |
+
first_layer.linear2.bias,
|
616 |
+
)
|
617 |
+
_supported_device_type = ["cpu", "cuda", torch.utils.backend_registration._privateuse1_backend_name]
|
618 |
+
if torch.overrides.has_torch_function(tensor_args):
|
619 |
+
why_not_sparsity_fast_path = "some Tensor argument has_torch_function"
|
620 |
+
elif src.device.type not in _supported_device_type:
|
621 |
+
why_not_sparsity_fast_path = f"src device is neither one of {_supported_device_type}"
|
622 |
+
elif torch.is_grad_enabled() and any(x.requires_grad for x in tensor_args):
|
623 |
+
why_not_sparsity_fast_path = ("grad is enabled and at least one of query or the "
|
624 |
+
"input/output projection weights or biases requires_grad")
|
625 |
+
|
626 |
+
if (not why_not_sparsity_fast_path) and (src_key_padding_mask is not None):
|
627 |
+
convert_to_nested = True
|
628 |
+
output = torch._nested_tensor_from_mask(output, src_key_padding_mask.logical_not(), mask_check=False)
|
629 |
+
src_key_padding_mask_for_layers = None
|
630 |
+
|
631 |
+
seq_len = _get_seq_len(src, batch_first)
|
632 |
+
is_causal = _detect_is_causal_mask(mask, is_causal, seq_len)
|
633 |
+
|
634 |
+
for mod in self.layers:
|
635 |
+
output = mod(output, src_mask=mask, is_causal=is_causal, src_key_padding_mask=src_key_padding_mask_for_layers)
|
636 |
+
|
637 |
+
if convert_to_nested:
|
638 |
+
output = output.to_padded_tensor(0., src.size())
|
639 |
+
|
640 |
+
if self.norm is not None:
|
641 |
+
output = self.norm(output)
|
642 |
+
|
643 |
+
return output
|
644 |
+
|
645 |
+
|
646 |
+
|
647 |
+
|
648 |
+
class TransformerDecoder(Module):
|
649 |
+
r"""TransformerDecoder is a stack of N decoder layers.
|
650 |
+
|
651 |
+
Args:
|
652 |
+
decoder_layer: an instance of the TransformerDecoderLayer() class (required).
|
653 |
+
num_layers: the number of sub-decoder-layers in the decoder (required).
|
654 |
+
norm: the layer normalization component (optional).
|
655 |
+
|
656 |
+
Examples::
|
657 |
+
>>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8)
|
658 |
+
>>> transformer_decoder = nn.TransformerDecoder(decoder_layer, num_layers=6)
|
659 |
+
>>> memory = torch.rand(10, 32, 512)
|
660 |
+
>>> tgt = torch.rand(20, 32, 512)
|
661 |
+
>>> out = transformer_decoder(tgt, memory)
|
662 |
+
"""
|
663 |
+
|
664 |
+
__constants__ = ['norm']
|
665 |
+
|
666 |
+
def __init__(
|
667 |
+
self,
|
668 |
+
decoder_layer: "TransformerDecoderLayer",
|
669 |
+
num_layers: int,
|
670 |
+
use_moe: bool = False,
|
671 |
+
norm: Optional[Module] = None
|
672 |
+
) -> None:
|
673 |
+
super().__init__()
|
674 |
+
torch._C._log_api_usage_once(f"torch.nn.modules.{self.__class__.__name__}")
|
675 |
+
self.layers = _get_clones(decoder_layer, num_layers)
|
676 |
+
self.num_layers = num_layers
|
677 |
+
self.use_moe = use_moe
|
678 |
+
self.norm = norm
|
679 |
+
|
680 |
+
|
681 |
+
def forward(self, tgt: Tensor, memory: Tensor, tgt_mask: Optional[Tensor] = None,
|
682 |
+
memory_mask: Optional[Tensor] = None,
|
683 |
+
memory_key_padding_mask: Optional[Tensor] = None, tgt_is_causal: Optional[bool] = None,
|
684 |
+
memory_is_causal: bool = False) -> Tensor:
|
685 |
+
r"""Pass the inputs (and mask) through the decoder layer in turn.
|
686 |
+
|
687 |
+
Args:
|
688 |
+
tgt: the sequence to the decoder (required).
|
689 |
+
memory: the sequence from the last layer of the encoder (required).
|
690 |
+
tgt_mask: the mask for the tgt sequence (optional).
|
691 |
+
memory_mask: the mask for the memory sequence (optional).
|
692 |
+
memory_key_padding_mask: the mask for the memory keys per batch (optional).
|
693 |
+
tgt_is_causal: If specified, applies a causal mask as ``tgt mask``.
|
694 |
+
Default: ``None``; try to detect a causal mask.
|
695 |
+
Warning:
|
696 |
+
``tgt_is_causal`` provides a hint that ``tgt_mask`` is
|
697 |
+
the causal mask. Providing incorrect hints can result in
|
698 |
+
incorrect execution, including forward and backward
|
699 |
+
compatibility.
|
700 |
+
memory_is_causal: If specified, applies a causal mask as
|
701 |
+
``memory mask``.
|
702 |
+
Default: ``False``.
|
703 |
+
Warning:
|
704 |
+
``memory_is_causal`` provides a hint that
|
705 |
+
``memory_mask`` is the causal mask. Providing incorrect
|
706 |
+
hints can result in incorrect execution, including
|
707 |
+
forward and backward compatibility.
|
708 |
+
|
709 |
+
Shape:
|
710 |
+
see the docs in :class:`~torch.nn.Transformer`.
|
711 |
+
"""
|
712 |
+
output = tgt
|
713 |
+
|
714 |
+
seq_len = _get_seq_len(tgt, self.layers[0].self_attn.batch_first)
|
715 |
+
tgt_is_causal = _detect_is_causal_mask(tgt_mask, tgt_is_causal, seq_len)
|
716 |
+
# print(f'target is causal: {tgt_is_causal}')
|
717 |
+
|
718 |
+
if self.use_moe:
|
719 |
+
sum_total_aux_loss = 0
|
720 |
+
for mod in self.layers:
|
721 |
+
output, total_aux_loss, balance_loss, router_z_loss = mod(output, memory,
|
722 |
+
memory_mask=memory_mask,
|
723 |
+
memory_key_padding_mask=memory_key_padding_mask,
|
724 |
+
tgt_is_causal=tgt_is_causal,
|
725 |
+
memory_is_causal=memory_is_causal)
|
726 |
+
sum_total_aux_loss += total_aux_loss
|
727 |
+
else:
|
728 |
+
for mod in self.layers:
|
729 |
+
output = mod(output, memory,
|
730 |
+
memory_mask=memory_mask,
|
731 |
+
memory_key_padding_mask=memory_key_padding_mask,
|
732 |
+
tgt_is_causal=tgt_is_causal,
|
733 |
+
memory_is_causal=memory_is_causal)
|
734 |
+
|
735 |
+
if self.norm is not None:
|
736 |
+
output = self.norm(output)
|
737 |
+
|
738 |
+
if self.use_moe:
|
739 |
+
return output, sum_total_aux_loss
|
740 |
+
else:
|
741 |
+
return output
|
742 |
+
|
743 |
+
|
744 |
+
|
745 |
+
class TransformerEncoderLayer(Module):
|
746 |
+
r"""TransformerEncoderLayer is made up of self-attn and feedforward network.
|
747 |
+
|
748 |
+
This standard encoder layer is based on the paper "Attention Is All You Need".
|
749 |
+
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,
|
750 |
+
Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in
|
751 |
+
Neural Information Processing Systems, pages 6000-6010. Users may modify or implement
|
752 |
+
in a different way during application.
|
753 |
+
|
754 |
+
TransformerEncoderLayer can handle either traditional torch.tensor inputs,
|
755 |
+
or Nested Tensor inputs. Derived classes are expected to similarly accept
|
756 |
+
both input formats. (Not all combinations of inputs are currently
|
757 |
+
supported by TransformerEncoderLayer while Nested Tensor is in prototype
|
758 |
+
state.)
|
759 |
+
|
760 |
+
If you are implementing a custom layer, you may derive it either from
|
761 |
+
the Module or TransformerEncoderLayer class. If your custom layer
|
762 |
+
supports both torch.Tensors and Nested Tensors inputs, make its
|
763 |
+
implementation a derived class of TransformerEncoderLayer. If your custom
|
764 |
+
Layer supports only torch.Tensor inputs, derive its implementation from
|
765 |
+
Module.
|
766 |
+
|
767 |
+
Args:
|
768 |
+
d_model: the number of expected features in the input (required).
|
769 |
+
nhead: the number of heads in the multiheadattention models (required).
|
770 |
+
dim_feedforward: the dimension of the feedforward network model (default=2048).
|
771 |
+
dropout: the dropout value (default=0.1).
|
772 |
+
activation: the activation function of the intermediate layer, can be a string
|
773 |
+
("relu" or "gelu") or a unary callable. Default: relu
|
774 |
+
layer_norm_eps: the eps value in layer normalization components (default=1e-5).
|
775 |
+
batch_first: If ``True``, then the input and output tensors are provided
|
776 |
+
as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
|
777 |
+
norm_first: if ``True``, layer norm is done prior to attention and feedforward
|
778 |
+
operations, respectively. Otherwise it's done after. Default: ``False`` (after).
|
779 |
+
bias: If set to ``False``, ``Linear`` and ``LayerNorm`` layers will not learn an additive
|
780 |
+
bias. Default: ``True``.
|
781 |
+
|
782 |
+
Examples::
|
783 |
+
>>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8)
|
784 |
+
>>> src = torch.rand(10, 32, 512)
|
785 |
+
>>> out = encoder_layer(src)
|
786 |
+
|
787 |
+
Alternatively, when ``batch_first`` is ``True``:
|
788 |
+
>>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8, batch_first=True)
|
789 |
+
>>> src = torch.rand(32, 10, 512)
|
790 |
+
>>> out = encoder_layer(src)
|
791 |
+
|
792 |
+
Fast path:
|
793 |
+
forward() will use a special optimized implementation described in
|
794 |
+
`FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness`_ if all of the following
|
795 |
+
conditions are met:
|
796 |
+
|
797 |
+
- Either autograd is disabled (using ``torch.inference_mode`` or ``torch.no_grad``) or no tensor
|
798 |
+
argument ``requires_grad``
|
799 |
+
- training is disabled (using ``.eval()``)
|
800 |
+
- batch_first is ``True`` and the input is batched (i.e., ``src.dim() == 3``)
|
801 |
+
- activation is one of: ``"relu"``, ``"gelu"``, ``torch.functional.relu``, or ``torch.functional.gelu``
|
802 |
+
- at most one of ``src_mask`` and ``src_key_padding_mask`` is passed
|
803 |
+
- if src is a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_, neither ``src_mask``
|
804 |
+
nor ``src_key_padding_mask`` is passed
|
805 |
+
- the two ``LayerNorm`` instances have a consistent ``eps`` value (this will naturally be the case
|
806 |
+
unless the caller has manually modified one without modifying the other)
|
807 |
+
|
808 |
+
If the optimized implementation is in use, a
|
809 |
+
`NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ can be
|
810 |
+
passed for ``src`` to represent padding more efficiently than using a padding
|
811 |
+
mask. In this case, a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ will be
|
812 |
+
returned, and an additional speedup proportional to the fraction of the input that
|
813 |
+
is padding can be expected.
|
814 |
+
|
815 |
+
.. _`FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness`:
|
816 |
+
https://arxiv.org/abs/2205.14135
|
817 |
+
|
818 |
+
"""
|
819 |
+
|
820 |
+
__constants__ = ['norm_first']
|
821 |
+
|
822 |
+
def __init__(self, d_model: int, nhead: int, dim_feedforward: int = 2048, dropout: float = 0.1,
|
823 |
+
activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
|
824 |
+
layer_norm_eps: float = 1e-5, batch_first: bool = False, norm_first: bool = False,
|
825 |
+
bias: bool = True, device=None, dtype=None) -> None:
|
826 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
827 |
+
super().__init__()
|
828 |
+
self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout,
|
829 |
+
bias=bias, batch_first=batch_first,
|
830 |
+
**factory_kwargs)
|
831 |
+
# Implementation of Feedforward model
|
832 |
+
self.linear1 = Linear(d_model, dim_feedforward, bias=bias, **factory_kwargs)
|
833 |
+
self.dropout = Dropout(dropout)
|
834 |
+
self.linear2 = Linear(dim_feedforward, d_model, bias=bias, **factory_kwargs)
|
835 |
+
|
836 |
+
self.norm_first = norm_first
|
837 |
+
self.norm1 = LayerNorm(d_model, eps=layer_norm_eps, bias=bias, **factory_kwargs)
|
838 |
+
self.norm2 = LayerNorm(d_model, eps=layer_norm_eps, bias=bias, **factory_kwargs)
|
839 |
+
self.dropout1 = Dropout(dropout)
|
840 |
+
self.dropout2 = Dropout(dropout)
|
841 |
+
|
842 |
+
# Legacy string support for activation function.
|
843 |
+
if isinstance(activation, str):
|
844 |
+
activation = _get_activation_fn(activation)
|
845 |
+
|
846 |
+
# We can't test self.activation in forward() in TorchScript,
|
847 |
+
# so stash some information about it instead.
|
848 |
+
if activation is F.relu or isinstance(activation, torch.nn.ReLU):
|
849 |
+
self.activation_relu_or_gelu = 1
|
850 |
+
elif activation is F.gelu or isinstance(activation, torch.nn.GELU):
|
851 |
+
self.activation_relu_or_gelu = 2
|
852 |
+
else:
|
853 |
+
self.activation_relu_or_gelu = 0
|
854 |
+
self.activation = activation
|
855 |
+
|
856 |
+
def __setstate__(self, state):
|
857 |
+
super().__setstate__(state)
|
858 |
+
if not hasattr(self, 'activation'):
|
859 |
+
self.activation = F.relu
|
860 |
+
|
861 |
+
|
862 |
+
|
863 |
+
def forward(
|
864 |
+
self,
|
865 |
+
src: Tensor,
|
866 |
+
src_mask: Optional[Tensor] = None,
|
867 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
868 |
+
is_causal: bool = False) -> Tensor:
|
869 |
+
r"""Pass the input through the encoder layer.
|
870 |
+
|
871 |
+
Args:
|
872 |
+
src: the sequence to the encoder layer (required).
|
873 |
+
src_mask: the mask for the src sequence (optional).
|
874 |
+
src_key_padding_mask: the mask for the src keys per batch (optional).
|
875 |
+
is_causal: If specified, applies a causal mask as ``src mask``.
|
876 |
+
Default: ``False``.
|
877 |
+
Warning:
|
878 |
+
``is_causal`` provides a hint that ``src_mask`` is the
|
879 |
+
causal mask. Providing incorrect hints can result in
|
880 |
+
incorrect execution, including forward and backward
|
881 |
+
compatibility.
|
882 |
+
|
883 |
+
Shape:
|
884 |
+
see the docs in :class:`~torch.nn.Transformer`.
|
885 |
+
"""
|
886 |
+
src_key_padding_mask = F._canonical_mask(
|
887 |
+
mask=src_key_padding_mask,
|
888 |
+
mask_name="src_key_padding_mask",
|
889 |
+
other_type=F._none_or_dtype(src_mask),
|
890 |
+
other_name="src_mask",
|
891 |
+
target_type=src.dtype
|
892 |
+
)
|
893 |
+
|
894 |
+
src_mask = F._canonical_mask(
|
895 |
+
mask=src_mask,
|
896 |
+
mask_name="src_mask",
|
897 |
+
other_type=None,
|
898 |
+
other_name="",
|
899 |
+
target_type=src.dtype,
|
900 |
+
check_other=False,
|
901 |
+
)
|
902 |
+
|
903 |
+
# is_fastpath_enabled = torch.backends.mha.get_fastpath_enabled()
|
904 |
+
|
905 |
+
# see Fig. 1 of https://arxiv.org/pdf/2002.04745v1.pdf
|
906 |
+
why_not_sparsity_fast_path = ''
|
907 |
+
# if not is_fastpath_enabled:
|
908 |
+
# why_not_sparsity_fast_path = "torch.backends.mha.get_fastpath_enabled() was not True"
|
909 |
+
if not src.dim() == 3:
|
910 |
+
why_not_sparsity_fast_path = f"input not batched; expected src.dim() of 3 but got {src.dim()}"
|
911 |
+
elif self.training:
|
912 |
+
why_not_sparsity_fast_path = "training is enabled"
|
913 |
+
elif not self.self_attn.batch_first:
|
914 |
+
why_not_sparsity_fast_path = "self_attn.batch_first was not True"
|
915 |
+
elif self.self_attn.in_proj_bias is None:
|
916 |
+
why_not_sparsity_fast_path = "self_attn was passed bias=False"
|
917 |
+
elif not self.self_attn._qkv_same_embed_dim:
|
918 |
+
why_not_sparsity_fast_path = "self_attn._qkv_same_embed_dim was not True"
|
919 |
+
elif not self.activation_relu_or_gelu:
|
920 |
+
why_not_sparsity_fast_path = "activation_relu_or_gelu was not True"
|
921 |
+
elif not (self.norm1.eps == self.norm2.eps):
|
922 |
+
why_not_sparsity_fast_path = "norm1.eps is not equal to norm2.eps"
|
923 |
+
elif src.is_nested and (src_key_padding_mask is not None or src_mask is not None):
|
924 |
+
why_not_sparsity_fast_path = "neither src_key_padding_mask nor src_mask are not supported with NestedTensor input"
|
925 |
+
elif self.self_attn.num_heads % 2 == 1:
|
926 |
+
why_not_sparsity_fast_path = "num_head is odd"
|
927 |
+
elif torch.is_autocast_enabled():
|
928 |
+
why_not_sparsity_fast_path = "autocast is enabled"
|
929 |
+
if not why_not_sparsity_fast_path:
|
930 |
+
tensor_args = (
|
931 |
+
src,
|
932 |
+
self.self_attn.in_proj_weight,
|
933 |
+
self.self_attn.in_proj_bias,
|
934 |
+
self.self_attn.out_proj.weight,
|
935 |
+
self.self_attn.out_proj.bias,
|
936 |
+
self.norm1.weight,
|
937 |
+
self.norm1.bias,
|
938 |
+
self.norm2.weight,
|
939 |
+
self.norm2.bias,
|
940 |
+
self.linear1.weight,
|
941 |
+
self.linear1.bias,
|
942 |
+
self.linear2.weight,
|
943 |
+
self.linear2.bias,
|
944 |
+
)
|
945 |
+
|
946 |
+
# We have to use list comprehensions below because TorchScript does not support
|
947 |
+
# generator expressions.
|
948 |
+
_supported_device_type = ["cpu", "cuda", torch.utils.backend_registration._privateuse1_backend_name]
|
949 |
+
if torch.overrides.has_torch_function(tensor_args):
|
950 |
+
why_not_sparsity_fast_path = "some Tensor argument has_torch_function"
|
951 |
+
elif not all((x.device.type in _supported_device_type) for x in tensor_args):
|
952 |
+
why_not_sparsity_fast_path = ("some Tensor argument's device is neither one of "
|
953 |
+
f"{_supported_device_type}")
|
954 |
+
elif torch.is_grad_enabled() and any(x.requires_grad for x in tensor_args):
|
955 |
+
why_not_sparsity_fast_path = ("grad is enabled and at least one of query or the "
|
956 |
+
"input/output projection weights or biases requires_grad")
|
957 |
+
|
958 |
+
if not why_not_sparsity_fast_path:
|
959 |
+
merged_mask, mask_type = self.self_attn.merge_masks(src_mask, src_key_padding_mask, src)
|
960 |
+
return torch._transformer_encoder_layer_fwd(
|
961 |
+
src,
|
962 |
+
self.self_attn.embed_dim,
|
963 |
+
self.self_attn.num_heads,
|
964 |
+
self.self_attn.in_proj_weight,
|
965 |
+
self.self_attn.in_proj_bias,
|
966 |
+
self.self_attn.out_proj.weight,
|
967 |
+
self.self_attn.out_proj.bias,
|
968 |
+
self.activation_relu_or_gelu == 2,
|
969 |
+
self.norm_first,
|
970 |
+
self.norm1.eps,
|
971 |
+
self.norm1.weight,
|
972 |
+
self.norm1.bias,
|
973 |
+
self.norm2.weight,
|
974 |
+
self.norm2.bias,
|
975 |
+
self.linear1.weight,
|
976 |
+
self.linear1.bias,
|
977 |
+
self.linear2.weight,
|
978 |
+
self.linear2.bias,
|
979 |
+
merged_mask,
|
980 |
+
mask_type,
|
981 |
+
)
|
982 |
+
|
983 |
+
|
984 |
+
x = src
|
985 |
+
if self.norm_first:
|
986 |
+
x = x + self._sa_block(self.norm1(x), src_mask, src_key_padding_mask, is_causal=is_causal)
|
987 |
+
x = x + self._ff_block(self.norm2(x))
|
988 |
+
else:
|
989 |
+
x = self.norm1(x + self._sa_block(x, src_mask, src_key_padding_mask, is_causal=is_causal))
|
990 |
+
x = self.norm2(x + self._ff_block(x))
|
991 |
+
|
992 |
+
return x
|
993 |
+
|
994 |
+
|
995 |
+
# self-attention block
|
996 |
+
def _sa_block(self, x: Tensor,
|
997 |
+
attn_mask: Optional[Tensor], key_padding_mask: Optional[Tensor], is_causal: bool = False) -> Tensor:
|
998 |
+
x = self.self_attn(x, x, x,
|
999 |
+
attn_mask=attn_mask,
|
1000 |
+
key_padding_mask=key_padding_mask,
|
1001 |
+
need_weights=False, is_causal=is_causal)[0]
|
1002 |
+
return self.dropout1(x)
|
1003 |
+
|
1004 |
+
# feed forward block
|
1005 |
+
def _ff_block(self, x: Tensor) -> Tensor:
|
1006 |
+
x = self.linear2(self.dropout(self.activation(self.linear1(x))))
|
1007 |
+
return self.dropout2(x)
|
1008 |
+
|
1009 |
+
|
1010 |
+
|
1011 |
+
|
1012 |
+
class TransformerDecoderLayer(Module):
|
1013 |
+
r"""TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network.
|
1014 |
+
|
1015 |
+
This standard decoder layer is based on the paper "Attention Is All You Need".
|
1016 |
+
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez,
|
1017 |
+
Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in
|
1018 |
+
Neural Information Processing Systems, pages 6000-6010. Users may modify or implement
|
1019 |
+
in a different way during application.
|
1020 |
+
|
1021 |
+
Args:
|
1022 |
+
d_model: the number of expected features in the input (required).
|
1023 |
+
nhead: the number of heads in the multiheadattention models (required).
|
1024 |
+
dim_feedforward: the dimension of the feedforward network model (default=2048).
|
1025 |
+
dropout: the dropout value (default=0.1).
|
1026 |
+
activation: the activation function of the intermediate layer, can be a string
|
1027 |
+
("relu" or "gelu") or a unary callable. Default: relu
|
1028 |
+
layer_norm_eps: the eps value in layer normalization components (default=1e-5).
|
1029 |
+
batch_first: If ``True``, then the input and output tensors are provided
|
1030 |
+
as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
|
1031 |
+
norm_first: if ``True``, layer norm is done prior to self attention, multihead
|
1032 |
+
attention and feedforward operations, respectively. Otherwise it's done after.
|
1033 |
+
Default: ``False`` (after).
|
1034 |
+
bias: If set to ``False``, ``Linear`` and ``LayerNorm`` layers will not learn an additive
|
1035 |
+
bias. Default: ``True``.
|
1036 |
+
|
1037 |
+
Examples::
|
1038 |
+
>>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8)
|
1039 |
+
>>> memory = torch.rand(10, 32, 512)
|
1040 |
+
>>> tgt = torch.rand(20, 32, 512)
|
1041 |
+
>>> out = decoder_layer(tgt, memory)
|
1042 |
+
|
1043 |
+
Alternatively, when ``batch_first`` is ``True``:
|
1044 |
+
>>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8, batch_first=True)
|
1045 |
+
>>> memory = torch.rand(32, 10, 512)
|
1046 |
+
>>> tgt = torch.rand(32, 20, 512)
|
1047 |
+
>>> out = decoder_layer(tgt, memory)
|
1048 |
+
"""
|
1049 |
+
|
1050 |
+
__constants__ = ['norm_first']
|
1051 |
+
|
1052 |
+
def __init__(self, d_model: int, nhead: int, dim_feedforward: int = 2048, use_moe: bool = False, num_experts: int = 16,
|
1053 |
+
dropout: float = 0.1, activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
|
1054 |
+
layer_norm_eps: float = 1e-5, batch_first: bool = False, norm_first: bool = False,
|
1055 |
+
bias: bool = True, device=None, dtype=None) -> None:
|
1056 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
1057 |
+
super().__init__()
|
1058 |
+
|
1059 |
+
self.self_attn = MultiHeadSelfAttention(d_model, nhead, dropout=dropout, batch_first=batch_first, **factory_kwargs)
|
1060 |
+
self.multihead_attn = MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=batch_first,
|
1061 |
+
bias=bias, **factory_kwargs)
|
1062 |
+
self.use_moe = use_moe
|
1063 |
+
|
1064 |
+
if use_moe:
|
1065 |
+
self.moe = MoE(
|
1066 |
+
dim = d_model,
|
1067 |
+
num_experts = num_experts, # increase the experts (# parameters) of your model without increasing computation
|
1068 |
+
gating_top_n = 2, # default to top 2 gating, but can also be more (3 was tested in the paper with a lower threshold)
|
1069 |
+
threshold_train = 0.2, # at what threshold to accept a token to be routed to second expert and beyond - 0.2 was optimal for 2 expert routing, and apparently should be lower for 3
|
1070 |
+
threshold_eval = 0.2,
|
1071 |
+
capacity_factor_train = 1.25, # experts have fixed capacity per batch. we need some extra capacity in case gating is not perfectly balanced.
|
1072 |
+
capacity_factor_eval = 2., # capacity_factor_* should be set to a value >=1
|
1073 |
+
balance_loss_coef = 1e-2, # multiplier on the auxiliary expert balancing auxiliary loss
|
1074 |
+
router_z_loss_coef = 1e-3, # loss weight for router z-loss
|
1075 |
+
).to(device)
|
1076 |
+
self.moe_block = SparseMoEBlock(
|
1077 |
+
self.moe,
|
1078 |
+
add_ff_before = True,
|
1079 |
+
add_ff_after = True
|
1080 |
+
).to(device)
|
1081 |
+
else:
|
1082 |
+
# Implementation of Feedforward model
|
1083 |
+
self.linear1 = Linear(d_model, dim_feedforward, bias=bias, **factory_kwargs)
|
1084 |
+
self.dropout = Dropout(dropout)
|
1085 |
+
self.linear2 = Linear(dim_feedforward, d_model, bias=bias, **factory_kwargs)
|
1086 |
+
|
1087 |
+
self.norm_first = norm_first
|
1088 |
+
self.norm1 = LayerNorm(d_model, eps=layer_norm_eps, bias=bias, **factory_kwargs)
|
1089 |
+
self.norm2 = LayerNorm(d_model, eps=layer_norm_eps, bias=bias, **factory_kwargs)
|
1090 |
+
self.norm3 = LayerNorm(d_model, eps=layer_norm_eps, bias=bias, **factory_kwargs)
|
1091 |
+
self.dropout1 = Dropout(dropout)
|
1092 |
+
self.dropout2 = Dropout(dropout)
|
1093 |
+
self.dropout3 = Dropout(dropout)
|
1094 |
+
|
1095 |
+
# Legacy string support for activation function.
|
1096 |
+
if isinstance(activation, str):
|
1097 |
+
self.activation = _get_activation_fn(activation)
|
1098 |
+
else:
|
1099 |
+
self.activation = activation
|
1100 |
+
|
1101 |
+
def __setstate__(self, state):
|
1102 |
+
if 'activation' not in state:
|
1103 |
+
state['activation'] = F.relu
|
1104 |
+
super().__setstate__(state)
|
1105 |
+
|
1106 |
+
|
1107 |
+
def forward(
|
1108 |
+
self,
|
1109 |
+
tgt: Tensor,
|
1110 |
+
memory: Tensor,
|
1111 |
+
memory_mask: Optional[Tensor] = None,
|
1112 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
1113 |
+
tgt_is_causal: bool = False,
|
1114 |
+
memory_is_causal: bool = False,
|
1115 |
+
) -> Tensor:
|
1116 |
+
r"""Pass the inputs (and mask) through the decoder layer.
|
1117 |
+
|
1118 |
+
Args:
|
1119 |
+
tgt: the sequence to the decoder layer (required).
|
1120 |
+
memory: the sequence from the last layer of the encoder (required).
|
1121 |
+
memory_mask: the mask for the memory sequence (optional).
|
1122 |
+
memory_key_padding_mask: the mask for the memory keys per batch (optional).
|
1123 |
+
tgt_is_causal: If specified, applies a causal mask as ``tgt mask``.
|
1124 |
+
Default: ``False``.
|
1125 |
+
Warning:
|
1126 |
+
``tgt_is_causal`` provides a hint that ``tgt_mask`` is
|
1127 |
+
the causal mask. Providing incorrect hints can result in
|
1128 |
+
incorrect execution, including forward and backward
|
1129 |
+
compatibility.
|
1130 |
+
memory_is_causal: If specified, applies a causal mask as
|
1131 |
+
``memory mask``.
|
1132 |
+
Default: ``False``.
|
1133 |
+
Warning:
|
1134 |
+
``memory_is_causal`` provides a hint that
|
1135 |
+
``memory_mask`` is the causal mask. Providing incorrect
|
1136 |
+
hints can result in incorrect execution, including
|
1137 |
+
forward and backward compatibility.
|
1138 |
+
|
1139 |
+
Shape:
|
1140 |
+
see the docs in :class:`~torch.nn.Transformer`.
|
1141 |
+
"""
|
1142 |
+
# see Fig. 1 of https://arxiv.org/pdf/2002.04745v1.pdf
|
1143 |
+
|
1144 |
+
x = tgt
|
1145 |
+
# print(f'target is causal: {tgt_is_causal}')
|
1146 |
+
if self.norm_first:
|
1147 |
+
x = x + self._sa_block(self.norm1(x), tgt_is_causal)
|
1148 |
+
x = x + self._mha_block(self.norm2(x), memory, memory_mask, memory_key_padding_mask, memory_is_causal)
|
1149 |
+
if self.use_moe:
|
1150 |
+
m, total_aux_loss, balance_loss, router_z_loss = self.moe_block(x)
|
1151 |
+
x = x + m
|
1152 |
+
else:
|
1153 |
+
x = x + self._ff_block(self.norm3(x))
|
1154 |
+
else:
|
1155 |
+
x = self.norm1(x + self._sa_block(x, tgt_is_causal))
|
1156 |
+
x = self.norm2(x + self._mha_block(x, memory, memory_mask, memory_key_padding_mask, memory_is_causal))
|
1157 |
+
if self.use_moe:
|
1158 |
+
m, total_aux_loss, balance_loss, router_z_loss = self.moe_block(x)
|
1159 |
+
x = x + m
|
1160 |
+
else:
|
1161 |
+
x = self.norm3(x + self._ff_block(x))
|
1162 |
+
|
1163 |
+
if self.use_moe:
|
1164 |
+
return x, total_aux_loss, balance_loss, router_z_loss
|
1165 |
+
else:
|
1166 |
+
return x
|
1167 |
+
|
1168 |
+
|
1169 |
+
# self-attention block
|
1170 |
+
def _sa_block(self, x: Tensor,
|
1171 |
+
is_causal: bool = False) -> Tensor:
|
1172 |
+
x = self.self_attn(x, is_causal=is_causal)
|
1173 |
+
return self.dropout1(x)
|
1174 |
+
|
1175 |
+
# multihead attention block
|
1176 |
+
def _mha_block(self, x: Tensor, mem: Tensor,
|
1177 |
+
attn_mask: Optional[Tensor], key_padding_mask: Optional[Tensor], is_causal: bool = False) -> Tensor:
|
1178 |
+
x = self.multihead_attn(x, mem, mem,
|
1179 |
+
attn_mask=attn_mask,
|
1180 |
+
key_padding_mask=key_padding_mask,
|
1181 |
+
is_causal=is_causal,
|
1182 |
+
need_weights=False)[0]
|
1183 |
+
return self.dropout2(x)
|
1184 |
+
|
1185 |
+
# feed forward block
|
1186 |
+
def _ff_block(self, x: Tensor) -> Tensor:
|
1187 |
+
x = self.linear2(self.dropout(self.activation(self.linear1(x))))
|
1188 |
+
return self.dropout3(x)
|
1189 |
+
|
1190 |
+
|
1191 |
+
|
1192 |
+
def _get_clones(module, N):
|
1193 |
+
# FIXME: copy.deepcopy() is not defined on nn.module
|
1194 |
+
return ModuleList([copy.deepcopy(module) for i in range(N)])
|
1195 |
+
|
1196 |
+
|
1197 |
+
def _get_activation_fn(activation: str) -> Callable[[Tensor], Tensor]:
|
1198 |
+
if activation == "relu":
|
1199 |
+
return F.relu
|
1200 |
+
elif activation == "gelu":
|
1201 |
+
return F.gelu
|
1202 |
+
|
1203 |
+
raise RuntimeError(f"activation should be relu/gelu, not {activation}")
|
1204 |
+
|
1205 |
+
|
1206 |
+
def _detect_is_causal_mask(
|
1207 |
+
mask: Optional[Tensor],
|
1208 |
+
is_causal: Optional[bool] = None,
|
1209 |
+
size: Optional[int] = None,
|
1210 |
+
) -> bool:
|
1211 |
+
"""Return whether the given attention mask is causal.
|
1212 |
+
|
1213 |
+
Warning:
|
1214 |
+
If ``is_causal`` is not ``None``, its value will be returned as is. If a
|
1215 |
+
user supplies an incorrect ``is_causal`` hint,
|
1216 |
+
|
1217 |
+
``is_causal=False`` when the mask is in fact a causal attention.mask
|
1218 |
+
may lead to reduced performance relative to what would be achievable
|
1219 |
+
with ``is_causal=True``;
|
1220 |
+
``is_causal=True`` when the mask is in fact not a causal attention.mask
|
1221 |
+
may lead to incorrect and unpredictable execution - in some scenarios,
|
1222 |
+
a causal mask may be applied based on the hint, in other execution
|
1223 |
+
scenarios the specified mask may be used. The choice may not appear
|
1224 |
+
to be deterministic, in that a number of factors like alignment,
|
1225 |
+
hardware SKU, etc influence the decision whether to use a mask or
|
1226 |
+
rely on the hint.
|
1227 |
+
``size`` if not None, check whether the mask is a causal mask of the provided size
|
1228 |
+
Otherwise, checks for any causal mask.
|
1229 |
+
"""
|
1230 |
+
# Prevent type refinement
|
1231 |
+
make_causal = (is_causal is True)
|
1232 |
+
|
1233 |
+
if is_causal is None and mask is not None:
|
1234 |
+
sz = size if size is not None else mask.size(-2)
|
1235 |
+
causal_comparison = _generate_square_subsequent_mask(
|
1236 |
+
sz, device=mask.device, dtype=mask.dtype)
|
1237 |
+
|
1238 |
+
# Do not use `torch.equal` so we handle batched masks by
|
1239 |
+
# broadcasting the comparison.
|
1240 |
+
if mask.size() == causal_comparison.size():
|
1241 |
+
make_causal = bool((mask == causal_comparison).all())
|
1242 |
+
else:
|
1243 |
+
make_causal = False
|
1244 |
+
|
1245 |
+
return make_causal
|
1246 |
+
|
1247 |
+
def check_instruments(genereated_seq):
|
1248 |
+
ins_present = []
|
1249 |
+
ins_count = 0
|
1250 |
+
instrument_list = ["piano", "chromatic", "organ", "guitar", "bass", "strings", "ensemble", "brass", "reed", "drum", "pipe", "synth_lead", "synth_pad", "synth_effect", "ethnic", "percussive", "sfx"]
|
1251 |
+
for token in genereated_seq:
|
1252 |
+
try:
|
1253 |
+
ins, pitch, vel = token
|
1254 |
+
# print(str(ins))
|
1255 |
+
except ValueError:
|
1256 |
+
try:
|
1257 |
+
ins, pitch = token
|
1258 |
+
except ValueError:
|
1259 |
+
ins = token
|
1260 |
+
if str(ins) in instrument_list:
|
1261 |
+
# print('coming here')
|
1262 |
+
|
1263 |
+
if ('prefix', 'instrument', str(ins)) not in ins_present and ins_count < 15:
|
1264 |
+
ins_count += 1
|
1265 |
+
print(f'adding instrument {ins}')
|
1266 |
+
ins_present.append(('prefix', 'instrument', str(ins)))
|
1267 |
+
if ins_present != []:
|
1268 |
+
genereated_seq = ins_present + ['<S>']+ genereated_seq +['<E>']
|
1269 |
+
else:
|
1270 |
+
genereated_seq = genereated_seq +['<E>']
|
1271 |
+
print(genereated_seq)
|
1272 |
+
return genereated_seq
|
1273 |
+
|
1274 |
+
def process_caption(gpu_id, captions, model, tokenizer, r_tokenizer):
|
1275 |
+
device = gpu_id
|
1276 |
+
torch.cuda.set_device(gpu_id)
|
1277 |
+
model.to(gpu_id)
|
1278 |
+
model.eval()
|
1279 |
+
for caption in captions:
|
1280 |
+
src = caption['caption']
|
1281 |
+
location = caption['location']
|
1282 |
+
#src = "A cinematic electronic soundtrack that evokes an epic and dark atmosphere, featuring cello, contrabass, and drums. The song is set in A minor with a moderate tempo and a 4/4 time signature, creating an emotional and action-packed ambiance suitable for film."
|
1283 |
+
'''
|
1284 |
+
example 1: "A cheerful and melodic pop Christmas song featuring piano, acoustic guitar, vibraphone, bass, and drums, set in the key of Eb minor with a fast tempo of 123 bpm and a 4/4 time signature, creating a joyful and relaxing atmosphere."lmd_full/1/1b9f5f325c2080d345d877f590aa3dbe.mid
|
1285 |
+
example 2: "A melodic electronic song with ambient elements, featuring piano, acoustic guitar, alto saxophone, string ensemble, and electric bass. Set in G minor with a 4/4 time signature, it moves at a lively Presto tempo. The composition evokes a blend of relaxation and darkness, with hints of happiness and a meditative quality."lmd_full/1/152891ac63017b234c33e75e4a4a28c5.mid
|
1286 |
+
example 3: "This motivational electronic and pop song features a clean electric guitar, rock organ, synth voice, acoustic guitar, and vibraphone, creating a melodic and uplifting atmosphere. Set in the key of G# minor with a 4/4 time signature, the track moves at an energetic Allegro tempo of 120 beats per minute. The chord progression of Bbm7 and F# adds to the song's inspiring and corporate feel." lmd_full/1/14347e50e9e8149a9da09f49b188180b.mid
|
1287 |
+
example 4: "This short electronic song in C minor features a brass section, string ensemble, tenor saxophone, clean electric guitar, and slap bass, creating a melodic and slightly dark atmosphere. With a tempo of 124 BPM (Allegro) and a 4/4 time signature, the track incorporates a chord progression of C7/E, Eb6, and Bbm6, adding a touch of corporate and motivational vibes to the overall composition." lmd_full/1/1dc4cd50a5509d8042d27d80bc7e668e.mid
|
1288 |
+
example 5: "An energetic and melodic electronic trance track with a space and retro vibe, featuring drums, distortion guitar, flute, synth bass, and slap bass. Set in A minor with a fast tempo of 138 BPM, the song maintains a 4/4 time signature throughout its duration." lmd_full/3/3328b854ebe7a2fc9a746ede74c410ae.mid
|
1289 |
+
example 6: "A short but energetic rock fragment in C minor, featuring overdriven guitars, electric bass, and drums, with a vivacious tempo of 155 BPM and a 4/4 time signature, evoking a blend of dark and melodic tones." lmd_full/4/4c2232688c5f869b8470a408d197f5e3.mid
|
1290 |
+
example 7: "A classical piece with a cinematic flair, this composition is characterized by its fast tempo and 4/4 time signature. The soprano saxophone and flute take turns leading the melody, supported by the lush tones of the string ensemble, acoustic bass, and pan flute. Set in the key of F minor, the harmonic landscape is painted with the chords Gm7b5, Cm7b5, Fm7, Eaug, and Ab/Eb. The overall mood evokes images of film, with hints of Christmas, drama, documentary, and adventure." lmd_full/9/95bce1b489a11829b4fef39200291f60.mid
|
1291 |
+
exmaple 8: "A slow, dark, and emotional classical piece featuring cello, violin, and viola, likely to be used in a dramatic film soundtrack. The composition is in the key of C minor with a 4/4 time signature, and the main chord progression consists of Cm, G, Cm, and Fm." lmd_full/a/a22aad98ecfe4b3d8a353c2a72132834.mid
|
1292 |
+
example 9: "A slow and emotional classical piece, likely used in a film soundtrack, featuring a church organ as the sole instrument. Written in the key of Eb major with a 3/4 time signature, it evokes a sense of drama and romance. The chord progression of Bb7, Eb, and Ab contributes to the relaxing atmosphere throughout the song." lmd_full/a/af4302a036c9df71e0435df9b08f8c4b.mid
|
1293 |
+
example 10: "A cinematic electronic soundtrack that evokes an epic and dark atmosphere, featuring cello, contrabass, and drums. The song is set in A minor with a moderate tempo and a 4/4 time signature, creating an emotional and action-packed ambiance suitable for film." lmd_full/d/d920b6f451d7a72ae06f154e7c06c4c1.mid
|
1294 |
+
'''
|
1295 |
+
inputs = tokenizer(src, return_tensors='pt', padding=True, truncation=True)
|
1296 |
+
input_ids = nn.utils.rnn.pad_sequence(inputs.input_ids, batch_first=True, padding_value=0)
|
1297 |
+
input_ids = input_ids.to(device)
|
1298 |
+
attention_mask =nn.utils.rnn.pad_sequence(inputs.attention_mask, batch_first=True, padding_value=0)
|
1299 |
+
attention_mask = attention_mask.to(device)
|
1300 |
+
output = model.generate(input_ids, attention_mask,max_len=1000,temperature = 0.9)
|
1301 |
+
output_list = output[0].tolist()
|
1302 |
+
print(type(output_list))
|
1303 |
+
# generated_sequences = [dict_tokenizer[token] for token in output_list[0]]
|
1304 |
+
# generated_sequences = check_instruments(generated_sequences)
|
1305 |
+
# # generated_sequences = [('prefix', 'instrument', 'bass'), ('prefix', 'instrument', 'guitar'), ('prefix', 'instrument', 'piano'), ('prefix', 'instrument', 'guitar'), '<S>' ]+ generated_sequences +['<E>']
|
1306 |
+
# generated_sequences = [token for token in generated_sequences]# if token not in ["<SS>", "<S>", "<E>", "<SEP>"]]
|
1307 |
+
# # print("Generated sequences:", generated_sequences)
|
1308 |
+
# with open('../../generated_seq.pkl', 'wb') as f:
|
1309 |
+
# pickle.dump(generated_sequences, f)
|
1310 |
+
# mid_dict = aria_tokenizer.detokenize(generated_sequences)
|
1311 |
+
# mid = mid_dict.to_midi()
|
1312 |
+
generated_midi = r_tokenizer.decode(output_list)
|
1313 |
+
# print(type(generated_midi))
|
1314 |
+
generated_midi.dump_midi(f"../res/{location}")
|
1315 |
+
|
1316 |
+
def test_generate():
|
1317 |
+
device = 'cuda'
|
1318 |
+
artifact_folder = '../artifacts'
|
1319 |
+
tokenizer_filepath = os.path.join(artifact_folder, "vocab_remi.pkl")
|
1320 |
+
caption_dataset_path = '/root/text2midi/captions/train.json'
|
1321 |
+
print(f'caption_dataset_path: {caption_dataset_path}')
|
1322 |
+
# Load the tokenizer dictionary
|
1323 |
+
with open(tokenizer_filepath, "rb") as f:
|
1324 |
+
r_tokenizer = pickle.load(f)
|
1325 |
+
# print(tokenizer['<SS>'])
|
1326 |
+
# dict_tokenizer = {v: k for k, v in tokenizer.items()}
|
1327 |
+
# data_str = json.dumps(dict_tokenizer, indent=4)
|
1328 |
+
# with open('dict_output.txt', 'w') as file:
|
1329 |
+
# file.write(data_str)
|
1330 |
+
# Get the vocab size
|
1331 |
+
with jsonlines.open(caption_dataset_path) as reader:
|
1332 |
+
# captions = list(reader)
|
1333 |
+
captions = [line for line in reader if line.get('test_set') is True]
|
1334 |
+
print(f'Number of test set captions: {len(captions)}')
|
1335 |
+
with jsonlines.open(caption_dataset_path) as reader:
|
1336 |
+
captions = [line for line in reader if line.get('test_set') is True and not os.path.isfile('/root/test/text2midi/res/' + line.get('location'))]
|
1337 |
+
print(f'Number of test set captions not done: {len(captions)}')
|
1338 |
+
vocab_size = len(r_tokenizer)#+1
|
1339 |
+
print("Vocab size: ", vocab_size)
|
1340 |
+
# print(tokenizer[2171])
|
1341 |
+
# d_model =
|
1342 |
+
# model = Transformer(vocab_size, 768, 8, 8000, 8, 1024, False, 8, device=device)
|
1343 |
+
model = Transformer(vocab_size, 768, 8, 5000, 18, 1024, False, 8, device=device)
|
1344 |
+
# model = DataParallel(model)
|
1345 |
+
model.load_state_dict(torch.load('/root/test/text2midi/output_test_lr_symph/epoch_65/pytorch_model.bin', map_location=device))
|
1346 |
+
model.eval()
|
1347 |
+
tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-base")
|
1348 |
+
num_gpus = torch.cuda.device_count()
|
1349 |
+
captions_per_gpu = len(captions) // num_gpus
|
1350 |
+
processes = []
|
1351 |
+
for i in range(num_gpus):
|
1352 |
+
start_idx = i * captions_per_gpu
|
1353 |
+
end_idx = (i + 1) * captions_per_gpu if i != num_gpus - 1 else len(captions)
|
1354 |
+
p = mp.Process(target=process_caption, args=(i, captions[start_idx:end_idx], model, tokenizer, r_tokenizer))
|
1355 |
+
p.start()
|
1356 |
+
processes.append(p)
|
1357 |
+
|
1358 |
+
for p in processes:
|
1359 |
+
p.join()
|
1360 |
+
|
1361 |
+
# src = "Played at 149 beats per minute in 2/4 time signature and the key of G major, classical piece with instruments: bassoon, clarinet, flute, horn, oboe, and trumpet."
|
1362 |
+
# src= 'Played at 114 beats per minute in 1/4 time signature and the key of g# minor, classical piece with the following instruments: clarinet, english horn, flute, horn, piccolo, trombone, and trumpet.'
|
1363 |
+
|
1364 |
+
# mid.save('../../output_1000_epoch_9_pos.mid')
|
1365 |
+
# print(output.shape)
|
1366 |
+
|
1367 |
+
if __name__ == "__main__":
|
1368 |
+
mp.set_start_method('spawn')
|
1369 |
+
test_generate()
|
1370 |
+
print("Done")
|
1371 |
+
|
1372 |
+
# if __name__ == "__main__":
|
1373 |
+
# device = torch.device("cuda:2" if torch.cuda.is_available() else "cpu")
|
1374 |
+
# print(device)
|
1375 |
+
|
1376 |
+
# # Initialize the model
|
1377 |
+
# batch_size = 4
|
1378 |
+
# d_model = 768 # Model dimension (same as FLAN-T5 encoder output dimension)
|
1379 |
+
# nhead = 8 # Number of heads in the multiheadattention models
|
1380 |
+
# num_layers = 4 # Number of decoder layers
|
1381 |
+
# n_vocab = 22000 # Number of tokens in the vocabulary
|
1382 |
+
# max_len = 4000 # Maximum length of the input sequence
|
1383 |
+
# use_moe = True # Use mixture of experts
|
1384 |
+
# num_experts = 16 # Number of experts in the mixture of experts
|
1385 |
+
# t5_tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-base")
|
1386 |
+
|
1387 |
+
|
1388 |
+
# model = Transformer(n_vocab, d_model, nhead, max_len, num_decoder_layers=num_layers, dim_feedforward=1024, use_moe=use_moe, num_experts=num_experts, batch_first=True).to(device)
|
1389 |
+
# src = ["Hello, how are you?"] * batch_size
|
1390 |
+
# inputs = t5_tokenizer(src, return_tensors='pt', padding=True, truncation=True)
|
1391 |
+
# input_ids = inputs.input_ids.to(device)
|
1392 |
+
# attention_mask = inputs.attention_mask.to(device)
|
1393 |
+
# tgt = torch.randint(0, n_vocab, (batch_size, max_len)).to(device) # Shape: (batch_size, max_len)
|
1394 |
+
# print(input_ids.shape, tgt.shape)
|
1395 |
+
|
1396 |
+
# # Forward pass
|
1397 |
+
# time_start = time.time()
|
1398 |
+
# if use_moe:
|
1399 |
+
# out, aux_loss = model(input_ids, attention_mask, tgt, tgt_is_causal=True)
|
1400 |
+
# time_end = time.time()
|
1401 |
+
# print(aux_loss)
|
1402 |
+
# else:
|
1403 |
+
# out = model(input_ids, attention_mask, tgt)
|
1404 |
+
# time_end = time.time()
|
1405 |
+
# print(out.shape)
|
1406 |
+
# print(f"Time taken for forward pass: {time_end - time_start} seconds")
|
1407 |
+
|
1408 |
+
# # Print number of parameters
|
1409 |
+
# num_params = sum(p.numel() for p in model.parameters())
|
1410 |
+
# print(f"Number of parameters: {num_params}")
|
1411 |
+
|
1412 |
+
# # Print number of trainable parameters
|
1413 |
+
# num_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
1414 |
+
# print(f"Number of trainable parameters: {num_trainable_params}")
|
1415 |
+
|
1416 |
+
# # Print memory usage in GB
|
1417 |
+
# print(f"Memory allocated: {torch.cuda.memory_allocated(device) / 1e9} GB")
|