Spaces:
Runtime error
Runtime error
abhishekrajpurohit
commited on
Upload 39 files
Browse files- app.py +202 -0
- audio_utils.py +31 -0
- input_validation.py +7 -0
- language_mapping.py +154 -0
- parler-tts/.gitignore +173 -0
- parler-tts/INFERENCE.md +264 -0
- parler-tts/LICENSE +201 -0
- parler-tts/Makefile +9 -0
- parler-tts/README.md +201 -0
- parler-tts/helpers/gradio_demo/app.py +105 -0
- parler-tts/helpers/model_init_scripts/init_dummy_model.py +69 -0
- parler-tts/helpers/model_init_scripts/init_dummy_model_with_encodec.py +67 -0
- parler-tts/helpers/model_init_scripts/init_large_model.py +68 -0
- parler-tts/helpers/model_init_scripts/init_model_600M.py +68 -0
- parler-tts/helpers/push_to_hub_scripts/push_dac_to_hub.py +26 -0
- parler-tts/helpers/push_to_hub_scripts/push_trained_parler_tts_to_hub.py +13 -0
- parler-tts/helpers/training_configs/librispeech_tts_r_300M_dummy.json +72 -0
- parler-tts/helpers/training_configs/starting_point_0.01.json +74 -0
- parler-tts/helpers/training_configs/starting_point_v1.json +76 -0
- parler-tts/helpers/training_configs/starting_point_v1_large.json +77 -0
- parler-tts/parler_tts/__init__.py +25 -0
- parler-tts/parler_tts/configuration_parler_tts.py +291 -0
- parler-tts/parler_tts/dac_wrapper/__init__.py +2 -0
- parler-tts/parler_tts/dac_wrapper/configuration_dac.py +27 -0
- parler-tts/parler_tts/dac_wrapper/modeling_dac.py +164 -0
- parler-tts/parler_tts/logits_processors.py +54 -0
- parler-tts/parler_tts/modeling_parler_tts.py +0 -0
- parler-tts/parler_tts/streamer.py +147 -0
- parler-tts/pyproject.toml +17 -0
- parler-tts/setup.py +69 -0
- parler-tts/training/README.md +212 -0
- parler-tts/training/__init__.py +0 -0
- parler-tts/training/arguments.py +375 -0
- parler-tts/training/data.py +311 -0
- parler-tts/training/eval.py +142 -0
- parler-tts/training/run_parler_tts_training.py +1249 -0
- parler-tts/training/utils.py +203 -0
- requirements.txt +5 -0
- tts.py +50 -0
app.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from models.tts import TTSModel
|
3 |
+
from utils.audio_utils import save_audio, get_cached_audio, get_audio_filename
|
4 |
+
from utils.input_validation import validate_input
|
5 |
+
from config.language_mapping import (
|
6 |
+
LANGUAGE_VOICE_MAPPING,
|
7 |
+
construct_description,
|
8 |
+
EMOTION_DESC,
|
9 |
+
SPEED_DESC,
|
10 |
+
PITCH_DESC,
|
11 |
+
BACKGROUND_NOISE_DESC,
|
12 |
+
REVERBERATION_DESC,
|
13 |
+
QUALITY_DESC,
|
14 |
+
get_speakers_for_language
|
15 |
+
)
|
16 |
+
|
17 |
+
def generate_speech(
|
18 |
+
text,
|
19 |
+
language,
|
20 |
+
speaker,
|
21 |
+
emotion="Neutral",
|
22 |
+
speed="Normal",
|
23 |
+
pitch="Medium",
|
24 |
+
background_noise="Minimal",
|
25 |
+
reverberation="Close",
|
26 |
+
quality="High"
|
27 |
+
):
|
28 |
+
try:
|
29 |
+
# Validate inputs
|
30 |
+
validate_input(text, language)
|
31 |
+
|
32 |
+
# Check if audio is already cached
|
33 |
+
cached_audio = get_cached_audio(
|
34 |
+
text, language, speaker, emotion, speed,
|
35 |
+
pitch, background_noise, reverberation, quality
|
36 |
+
)
|
37 |
+
|
38 |
+
if cached_audio:
|
39 |
+
return cached_audio
|
40 |
+
|
41 |
+
# Get the description using the imported constructor
|
42 |
+
description = construct_description(
|
43 |
+
speaker,
|
44 |
+
language,
|
45 |
+
emotion,
|
46 |
+
speed,
|
47 |
+
pitch,
|
48 |
+
background_noise,
|
49 |
+
reverberation,
|
50 |
+
quality
|
51 |
+
)
|
52 |
+
|
53 |
+
# Generate audio
|
54 |
+
tts_model = TTSModel()
|
55 |
+
audio_array = tts_model.generate_audio(text, description)
|
56 |
+
|
57 |
+
# Save the generated audio
|
58 |
+
filename = get_audio_filename(
|
59 |
+
text, language, speaker, emotion, speed,
|
60 |
+
pitch, background_noise, reverberation, quality
|
61 |
+
)
|
62 |
+
filepath = save_audio(audio_array, filename)
|
63 |
+
|
64 |
+
return filepath
|
65 |
+
|
66 |
+
except Exception as e:
|
67 |
+
raise gr.Error(str(e))
|
68 |
+
|
69 |
+
# Create Gradio interface
|
70 |
+
with gr.Blocks(title="Indic Text-to-Speech") as demo:
|
71 |
+
gr.Markdown("# Indian Local Text-to-Speech Synthesizer")
|
72 |
+
gr.Markdown("Generate natural speech in multiple Indian languages using AI4Bharat's model")
|
73 |
+
|
74 |
+
with gr.Row():
|
75 |
+
with gr.Column():
|
76 |
+
text_input = gr.Textbox(
|
77 |
+
label="Text to speak",
|
78 |
+
placeholder="Enter the text you want to convert to speech...",
|
79 |
+
lines=3
|
80 |
+
)
|
81 |
+
|
82 |
+
with gr.Row():
|
83 |
+
language_input = gr.Dropdown(
|
84 |
+
choices=sorted(list(LANGUAGE_VOICE_MAPPING.keys())),
|
85 |
+
label="Language",
|
86 |
+
value="English"
|
87 |
+
)
|
88 |
+
speaker_input = gr.Dropdown(
|
89 |
+
choices=LANGUAGE_VOICE_MAPPING["English"], # Default choices
|
90 |
+
label="Speaker",
|
91 |
+
value=LANGUAGE_VOICE_MAPPING["English"][0] # Default value
|
92 |
+
)
|
93 |
+
|
94 |
+
with gr.Row():
|
95 |
+
emotion_input = gr.Dropdown(
|
96 |
+
choices=list(EMOTION_DESC.keys()),
|
97 |
+
label="Expressivity",
|
98 |
+
value="Neutral"
|
99 |
+
)
|
100 |
+
speed_input = gr.Dropdown(
|
101 |
+
choices=list(SPEED_DESC.keys()),
|
102 |
+
label="Speaking Speed",
|
103 |
+
value="Normal"
|
104 |
+
)
|
105 |
+
|
106 |
+
with gr.Row():
|
107 |
+
pitch_input = gr.Dropdown(
|
108 |
+
choices=list(PITCH_DESC.keys()),
|
109 |
+
label="Pitch",
|
110 |
+
value="Medium"
|
111 |
+
)
|
112 |
+
background_input = gr.Dropdown(
|
113 |
+
choices=list(BACKGROUND_NOISE_DESC.keys()),
|
114 |
+
label="Background Noise",
|
115 |
+
value="Minimal"
|
116 |
+
)
|
117 |
+
|
118 |
+
with gr.Row():
|
119 |
+
reverb_input = gr.Dropdown(
|
120 |
+
choices=list(REVERBERATION_DESC.keys()),
|
121 |
+
label="Reverberation",
|
122 |
+
value="Close"
|
123 |
+
)
|
124 |
+
quality_input = gr.Dropdown(
|
125 |
+
choices=list(QUALITY_DESC.keys()),
|
126 |
+
label="Audio Quality",
|
127 |
+
value="High"
|
128 |
+
)
|
129 |
+
|
130 |
+
generate_btn = gr.Button("Generate Speech", variant="primary")
|
131 |
+
|
132 |
+
with gr.Column():
|
133 |
+
audio_output = gr.Audio(
|
134 |
+
label="Generated Speech",
|
135 |
+
type="numpy"
|
136 |
+
)
|
137 |
+
|
138 |
+
# Update speaker choices when language changes
|
139 |
+
def update_speakers(language):
|
140 |
+
speakers = get_speakers_for_language(language)
|
141 |
+
return gr.Dropdown(choices=speakers, value=speakers[0])
|
142 |
+
|
143 |
+
language_input.change(
|
144 |
+
fn=update_speakers,
|
145 |
+
inputs=[language_input],
|
146 |
+
outputs=[speaker_input]
|
147 |
+
)
|
148 |
+
|
149 |
+
# Connect the components
|
150 |
+
generate_btn.click(
|
151 |
+
fn=generate_speech,
|
152 |
+
inputs=[
|
153 |
+
text_input,
|
154 |
+
language_input,
|
155 |
+
speaker_input,
|
156 |
+
emotion_input,
|
157 |
+
speed_input,
|
158 |
+
pitch_input,
|
159 |
+
background_input,
|
160 |
+
reverb_input,
|
161 |
+
quality_input
|
162 |
+
],
|
163 |
+
outputs=audio_output
|
164 |
+
)
|
165 |
+
|
166 |
+
# Pre-generate and cache example outputs
|
167 |
+
example_outputs = []
|
168 |
+
examples = [
|
169 |
+
["Hello, how are you?", "English", "Thoma", "Happy", "Normal", "Medium", "Minimal", "Close", "High"],
|
170 |
+
["नमस्ते, आप कैसे हैं?", "Hindi", "Rohit", "Neutral", "Normal", "Medium", "None", "Very Close", "Studio"],
|
171 |
+
["ನಮಸ್ಕಾರ, ಹೇಗಿದ್ದೀರಾ?", "Kannada", "Suresh", "Highly Expressive", "Fast", "High", "Minimal", "Moderate", "High"],
|
172 |
+
["How are you doing today?", "English", "Mary", "Monotone", "Slow", "Low", "Moderate", "Distant", "Good"],
|
173 |
+
]
|
174 |
+
|
175 |
+
# Generate and cache example outputs at startup
|
176 |
+
for example in examples:
|
177 |
+
output = generate_speech(*example)
|
178 |
+
example_outputs.append(output)
|
179 |
+
|
180 |
+
# Add examples with cached outputs
|
181 |
+
gr.Examples(
|
182 |
+
examples=examples,
|
183 |
+
inputs=[
|
184 |
+
text_input,
|
185 |
+
language_input,
|
186 |
+
speaker_input,
|
187 |
+
emotion_input,
|
188 |
+
speed_input,
|
189 |
+
pitch_input,
|
190 |
+
background_input,
|
191 |
+
reverb_input,
|
192 |
+
quality_input
|
193 |
+
],
|
194 |
+
outputs=audio_output,
|
195 |
+
fn=generate_speech,
|
196 |
+
cache_examples=True,
|
197 |
+
preprocess=False, # Don't preprocess inputs
|
198 |
+
postprocess=False # Don't postprocess outputs
|
199 |
+
)
|
200 |
+
|
201 |
+
if __name__ == "__main__":
|
202 |
+
demo.launch()
|
audio_utils.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import soundfile as sf
|
3 |
+
import hashlib
|
4 |
+
|
5 |
+
def ensure_dir(directory):
|
6 |
+
"""Ensure that a directory exists"""
|
7 |
+
if not os.path.exists(directory):
|
8 |
+
os.makedirs(directory)
|
9 |
+
|
10 |
+
def get_audio_filename(text, language, speaker, emotion, speed, pitch, background_noise, reverberation, quality):
|
11 |
+
"""Generate a unique filename based on input parameters"""
|
12 |
+
# Create a string containing all parameters
|
13 |
+
params = f"{text}{language}{speaker}{emotion}{speed}{pitch}{background_noise}{reverberation}{quality}"
|
14 |
+
# Create a hash of the parameters
|
15 |
+
filename = hashlib.md5(params.encode()).hexdigest()
|
16 |
+
return filename
|
17 |
+
|
18 |
+
def save_audio(audio_array, filename, sampling_rate=22050):
|
19 |
+
"""Save audio array to a file"""
|
20 |
+
ensure_dir("static/audio")
|
21 |
+
filepath = f"static/audio/{filename}.wav"
|
22 |
+
sf.write(filepath, audio_array, sampling_rate)
|
23 |
+
return filepath
|
24 |
+
|
25 |
+
def get_cached_audio(text, language, speaker, emotion, speed, pitch, background_noise, reverberation, quality):
|
26 |
+
"""Get cached audio if it exists"""
|
27 |
+
filename = get_audio_filename(text, language, speaker, emotion, speed, pitch, background_noise, reverberation, quality)
|
28 |
+
filepath = f"static/audio/{filename}.wav"
|
29 |
+
if os.path.exists(filepath):
|
30 |
+
return filepath
|
31 |
+
return None
|
input_validation.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from config.language_mapping import LANGUAGE_VOICE_MAPPING
|
2 |
+
|
3 |
+
def validate_input(text, language):
|
4 |
+
if not text.strip():
|
5 |
+
raise ValueError("Input text cannot be empty.")
|
6 |
+
if language not in LANGUAGE_VOICE_MAPPING:
|
7 |
+
raise ValueError(f"Language {language} is not supported.")
|
language_mapping.py
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
LANGUAGE_VOICE_MAPPING = {
|
2 |
+
"Assamese": ["Amit", "Sita"],
|
3 |
+
"Bengali": ["Arjun", "Aditi"],
|
4 |
+
"Bodo": ["Bikram", "Maya"],
|
5 |
+
"Chhattisgarhi": ["Bhanu", "Champa"],
|
6 |
+
"Dogri": ["Karan"],
|
7 |
+
"English": ["Thoma", "Mary"],
|
8 |
+
"Gujarati": ["Yash", "Neha"],
|
9 |
+
"Hindi": ["Rohit", "Divya"],
|
10 |
+
"Kannada": ["Suresh", "Anu"],
|
11 |
+
"Malayalam": ["Anjali", "Harish"],
|
12 |
+
"Manipuri": ["Laishram", "Ranjit"],
|
13 |
+
"Marathi": ["Sanjay", "Sunita"],
|
14 |
+
"Nepali": ["Amrita"],
|
15 |
+
"Odia": ["Manas", "Debjani"],
|
16 |
+
"Punjabi": ["Divjot", "Gurpreet"],
|
17 |
+
"Sanskrit": ["Aryan"],
|
18 |
+
"Tamil": ["Jaya", "Kavitha"],
|
19 |
+
"Telugu": ["Prakash", "Lalitha"]
|
20 |
+
}
|
21 |
+
|
22 |
+
# Voice characteristics for each speaker
|
23 |
+
VOICE_CHARACTERISTICS = {
|
24 |
+
"Amit": "slightly deep and resonant",
|
25 |
+
"Sita": "clear and well-paced",
|
26 |
+
"Arjun": "moderate and clear",
|
27 |
+
"Aditi": "high-pitched and expressive",
|
28 |
+
"Bikram": "higher-pitched and energetic",
|
29 |
+
"Maya": "balanced and pleasant",
|
30 |
+
"Bhanu": "warm and measured",
|
31 |
+
"Champa": "clear and gentle",
|
32 |
+
"Karan": "high-pitched and engaging",
|
33 |
+
"Thoma": "clear and well-articulated",
|
34 |
+
"Mary": "pleasant and measured",
|
35 |
+
"Yash": "warm and balanced",
|
36 |
+
"Neha": "clear and dynamic",
|
37 |
+
"Rohit": "moderate and expressive",
|
38 |
+
"Divya": "pleasant and well-paced",
|
39 |
+
"Suresh": "clear and precise",
|
40 |
+
"Anu": "warm and melodious",
|
41 |
+
"Anjali": "high-pitched and pleasant",
|
42 |
+
"Harish": "deep and measured",
|
43 |
+
"Laishram": "balanced and smooth",
|
44 |
+
"Ranjit": "clear and authoritative",
|
45 |
+
"Sanjay": "deep and authoritative",
|
46 |
+
"Sunita": "high-pitched and pleasant",
|
47 |
+
"Amrita": "high-pitched and gentle",
|
48 |
+
"Manas": "moderate and measured",
|
49 |
+
"Debjani": "clear and pleasant",
|
50 |
+
"Divjot": "clear and dynamic",
|
51 |
+
"Gurpreet": "warm and balanced",
|
52 |
+
"Aryan": "resonant and measured",
|
53 |
+
"Jaya": "high-pitched and melodious",
|
54 |
+
"Kavitha": "clear and expressive",
|
55 |
+
"Prakash": "clear and well-paced",
|
56 |
+
"Lalitha": "pleasant and melodious"
|
57 |
+
}
|
58 |
+
|
59 |
+
# Emotion descriptions
|
60 |
+
EMOTION_DESC = {
|
61 |
+
"Neutral": "maintaining a balanced and natural tone",
|
62 |
+
"Happy": "with a warm and positive energy",
|
63 |
+
"Sad": "with a gentle and somber tone",
|
64 |
+
"Angry": "with intense and strong delivery",
|
65 |
+
"Highly Expressive": "with dynamic and vibrant emotional delivery",
|
66 |
+
"Monotone": "with minimal tonal variation"
|
67 |
+
}
|
68 |
+
|
69 |
+
# Speed descriptions
|
70 |
+
SPEED_DESC = {
|
71 |
+
"Very Slow": "at an extremely measured pace",
|
72 |
+
"Slow": "at a measured, deliberate pace",
|
73 |
+
"Normal": "at a natural, comfortable pace",
|
74 |
+
"Fast": "at a swift, dynamic pace",
|
75 |
+
"Very Fast": "at a rapid, accelerated pace"
|
76 |
+
}
|
77 |
+
|
78 |
+
# Pitch modifiers
|
79 |
+
PITCH_DESC = {
|
80 |
+
"Very Low": "in an extremely deep register",
|
81 |
+
"Low": "in a deeper register",
|
82 |
+
"Medium": "in a natural pitch range",
|
83 |
+
"High": "in a higher register",
|
84 |
+
"Very High": "in an extremely high register"
|
85 |
+
}
|
86 |
+
|
87 |
+
BACKGROUND_NOISE_DESC = {
|
88 |
+
"None": "with absolutely no background noise",
|
89 |
+
"Minimal": "with minimal background noise",
|
90 |
+
"Moderate": "with moderate ambient noise",
|
91 |
+
"Noticeable": "with noticeable background sounds"
|
92 |
+
}
|
93 |
+
|
94 |
+
REVERBERATION_DESC = {
|
95 |
+
"Very Close": "in an extremely intimate setting",
|
96 |
+
"Close": "in a close-sounding environment",
|
97 |
+
"Moderate": "in a moderately spacious environment",
|
98 |
+
"Distant": "in a spacious, reverberant setting",
|
99 |
+
"Very Distant": "in a very large, echoing space"
|
100 |
+
}
|
101 |
+
|
102 |
+
QUALITY_DESC = {
|
103 |
+
"Basic": "in basic audio quality",
|
104 |
+
"Good": "in good audio quality",
|
105 |
+
"High": "in high audio quality",
|
106 |
+
"Studio": "in professional studio quality"
|
107 |
+
}
|
108 |
+
|
109 |
+
def construct_description(
|
110 |
+
speaker,
|
111 |
+
language,
|
112 |
+
emotion="Neutral",
|
113 |
+
speed="Normal",
|
114 |
+
pitch="Medium",
|
115 |
+
background_noise="Minimal",
|
116 |
+
reverberation="Close",
|
117 |
+
quality="High"
|
118 |
+
):
|
119 |
+
"""
|
120 |
+
Constructs a comprehensive description for the TTS model based on all available parameters.
|
121 |
+
|
122 |
+
Args:
|
123 |
+
speaker (str): The name of the speaker
|
124 |
+
language (str): The language being spoken
|
125 |
+
emotion (str): The emotional tone
|
126 |
+
speed (str): The speaking speed
|
127 |
+
pitch (str): The pitch level
|
128 |
+
background_noise (str): Level of background noise
|
129 |
+
reverberation (str): Distance/space effect
|
130 |
+
quality (str): Audio quality level
|
131 |
+
|
132 |
+
Returns:
|
133 |
+
str: A detailed description for the TTS model
|
134 |
+
"""
|
135 |
+
description = (
|
136 |
+
f"{speaker} speaks in {language} {VOICE_CHARACTERISTICS.get(speaker, 'with clear articulation')} "
|
137 |
+
f"{PITCH_DESC[pitch]}, {EMOTION_DESC[emotion]} {SPEED_DESC[speed]}. "
|
138 |
+
f"The recording is {REVERBERATION_DESC[reverberation]}, {BACKGROUND_NOISE_DESC[background_noise]}, "
|
139 |
+
f"captured {QUALITY_DESC[quality]}."
|
140 |
+
)
|
141 |
+
|
142 |
+
return description
|
143 |
+
|
144 |
+
def get_speakers_for_language(language):
|
145 |
+
"""
|
146 |
+
Get the list of recommended speakers for a given language.
|
147 |
+
|
148 |
+
Args:
|
149 |
+
language (str): The language to get speakers for
|
150 |
+
|
151 |
+
Returns:
|
152 |
+
list: List of recommended speakers for the language
|
153 |
+
"""
|
154 |
+
return LANGUAGE_VOICE_MAPPING.get(language, [])
|
parler-tts/.gitignore
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/.gitignore
|
2 |
+
|
3 |
+
# Byte-compiled / optimized / DLL files
|
4 |
+
__pycache__/
|
5 |
+
*.py[cod]
|
6 |
+
*$py.class
|
7 |
+
|
8 |
+
# C extensions
|
9 |
+
*.so
|
10 |
+
|
11 |
+
# logs
|
12 |
+
logs/
|
13 |
+
|
14 |
+
# Distribution / packaging
|
15 |
+
.Python
|
16 |
+
build/
|
17 |
+
develop-eggs/
|
18 |
+
dist/
|
19 |
+
downloads/
|
20 |
+
eggs/
|
21 |
+
.eggs/
|
22 |
+
lib/
|
23 |
+
lib64/
|
24 |
+
parts/
|
25 |
+
sdist/
|
26 |
+
var/
|
27 |
+
wheels/
|
28 |
+
*.egg-info/
|
29 |
+
.installed.cfg
|
30 |
+
*.egg
|
31 |
+
MANIFEST
|
32 |
+
|
33 |
+
# PyInstaller
|
34 |
+
# Usually these files are written by a python script from a template
|
35 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
36 |
+
*.manifest
|
37 |
+
*.spec
|
38 |
+
|
39 |
+
# Installer logs
|
40 |
+
pip-log.txt
|
41 |
+
pip-delete-this-directory.txt
|
42 |
+
|
43 |
+
# Unit test / coverage reports
|
44 |
+
htmlcov/
|
45 |
+
.tox/
|
46 |
+
.nox/
|
47 |
+
.coverage
|
48 |
+
.coverage.*
|
49 |
+
.cache
|
50 |
+
nosetests.xml
|
51 |
+
coverage.xml
|
52 |
+
*.cover
|
53 |
+
.hypothesis/
|
54 |
+
.pytest_cache/
|
55 |
+
|
56 |
+
# Translations
|
57 |
+
*.mo
|
58 |
+
*.pot
|
59 |
+
|
60 |
+
# Django stuff:
|
61 |
+
*.log
|
62 |
+
local_settings.py
|
63 |
+
db.sqlite3
|
64 |
+
|
65 |
+
# Flask stuff:
|
66 |
+
instance/
|
67 |
+
.webassets-cache
|
68 |
+
|
69 |
+
# Scrapy stuff:
|
70 |
+
.scrapy
|
71 |
+
|
72 |
+
# Sphinx documentation
|
73 |
+
docs/_build/
|
74 |
+
|
75 |
+
# PyBuilder
|
76 |
+
target/
|
77 |
+
|
78 |
+
# Jupyter Notebook
|
79 |
+
.ipynb_checkpoints
|
80 |
+
|
81 |
+
# IPython
|
82 |
+
profile_default/
|
83 |
+
ipython_config.py
|
84 |
+
|
85 |
+
# pyenv
|
86 |
+
.python-version
|
87 |
+
|
88 |
+
# celery beat schedule file
|
89 |
+
celerybeat-schedule
|
90 |
+
|
91 |
+
# SageMath parsed files
|
92 |
+
*.sage.py
|
93 |
+
|
94 |
+
# Environments
|
95 |
+
.env
|
96 |
+
.venv
|
97 |
+
env/
|
98 |
+
venv/
|
99 |
+
ENV/
|
100 |
+
env.bak/
|
101 |
+
venv.bak/
|
102 |
+
|
103 |
+
# Spyder project settings
|
104 |
+
.spyderproject
|
105 |
+
.spyproject
|
106 |
+
|
107 |
+
# Rope project settings
|
108 |
+
.ropeproject
|
109 |
+
|
110 |
+
# mkdocs documentation
|
111 |
+
/site
|
112 |
+
|
113 |
+
# mypy
|
114 |
+
.mypy_cache/
|
115 |
+
.dmypy.json
|
116 |
+
dmypy.json
|
117 |
+
|
118 |
+
# Pyre type checker
|
119 |
+
.pyre/
|
120 |
+
|
121 |
+
# vscode
|
122 |
+
.vs
|
123 |
+
.vscode
|
124 |
+
|
125 |
+
# Pycharm
|
126 |
+
.idea
|
127 |
+
|
128 |
+
# TF code
|
129 |
+
tensorflow_code
|
130 |
+
|
131 |
+
# Models
|
132 |
+
proc_data
|
133 |
+
|
134 |
+
# examples
|
135 |
+
runs
|
136 |
+
/runs_old
|
137 |
+
/wandb
|
138 |
+
/examples/runs
|
139 |
+
/examples/**/*.args
|
140 |
+
/examples/rag/sweep
|
141 |
+
|
142 |
+
# data
|
143 |
+
/data
|
144 |
+
serialization_dir
|
145 |
+
|
146 |
+
# emacs
|
147 |
+
*.*~
|
148 |
+
debug.env
|
149 |
+
|
150 |
+
# vim
|
151 |
+
.*.swp
|
152 |
+
|
153 |
+
#ctags
|
154 |
+
tags
|
155 |
+
|
156 |
+
# pre-commit
|
157 |
+
.pre-commit*
|
158 |
+
|
159 |
+
# .lock
|
160 |
+
*.lock
|
161 |
+
|
162 |
+
# DS_Store (MacOS)
|
163 |
+
.DS_Store
|
164 |
+
# RL pipelines may produce mp4 outputs
|
165 |
+
*.mp4
|
166 |
+
|
167 |
+
# dependencies
|
168 |
+
/transformers
|
169 |
+
|
170 |
+
# ruff
|
171 |
+
.ruff_cache
|
172 |
+
|
173 |
+
wandb
|
parler-tts/INFERENCE.md
ADDED
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Inference tips
|
2 |
+
|
3 |
+
Parler-TTS benefits from a number of optimizations that can make the model up to 4x faster. Add to this the ability to stream audio as it's being generated, and you can achieve time-to-first audio in under 500ms on a modern GPU.
|
4 |
+
|
5 |
+
## 📖 Quick Index
|
6 |
+
* [Efficient Attention Implementation](#efficient-attention-implementations)
|
7 |
+
* [Compilation](#compilation)
|
8 |
+
* [Streaming](#streaming)
|
9 |
+
* [Batch generation](#batch-generation)
|
10 |
+
* [Speaker Consistency](#speaker-consistency)
|
11 |
+
|
12 |
+
## Efficient Attention implementations
|
13 |
+
|
14 |
+
Parler-TTS supports [SDPA](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html) and [Flash Attention 2](https://github.com/Dao-AILab/flash-attention).
|
15 |
+
|
16 |
+
SDPA is used by default and speeds up generation time by up to 1.4x compared with eager attention.
|
17 |
+
|
18 |
+
To switch between attention implementations, simply specify `attn_implementation=attn_implementation` when loading the checkpoints:
|
19 |
+
|
20 |
+
```py
|
21 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
22 |
+
|
23 |
+
torch_device = "cuda:0" # use "mps" for Mac
|
24 |
+
torch_dtype = torch.bfloat16
|
25 |
+
model_name = "parler-tts/parler-tts-mini-v1"
|
26 |
+
|
27 |
+
attn_implementation = "eager" # "sdpa" or "flash_attention_2"
|
28 |
+
|
29 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained(
|
30 |
+
model_name,
|
31 |
+
attn_implementation=attn_implementation
|
32 |
+
).to(torch_device, dtype=torch_dtype)
|
33 |
+
```
|
34 |
+
|
35 |
+
## Compilation
|
36 |
+
|
37 |
+
[Compiling](https://pytorch.org/docs/stable/generated/torch.compile.html) the forward method of Parler can speed up generation time by up to 4.5x.
|
38 |
+
|
39 |
+
As an indication, `mode=default` brings a speed-up of 1.4 times compared to no compilation, while `mode="reduce-overhead"` brings much faster generation, at the cost of a longer compilation time and the need to generate twice to see the benefits of compilation.
|
40 |
+
|
41 |
+
```py
|
42 |
+
import torch
|
43 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
44 |
+
from transformers import AutoTokenizer
|
45 |
+
|
46 |
+
torch_device = "cuda:0"
|
47 |
+
torch_dtype = torch.bfloat16
|
48 |
+
model_name = "parler-tts/parler-tts-mini-v1"
|
49 |
+
|
50 |
+
# need to set padding max length
|
51 |
+
max_length = 50
|
52 |
+
|
53 |
+
# load model and tokenizer
|
54 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
55 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained(
|
56 |
+
model_name,
|
57 |
+
attn_implementation="eager"
|
58 |
+
).to(torch_device, dtype=torch_dtype)
|
59 |
+
|
60 |
+
# compile the forward pass
|
61 |
+
compile_mode = "default" # chose "reduce-overhead" for 3 to 4x speed-up
|
62 |
+
model.generation_config.cache_implementation = "static"
|
63 |
+
model.forward = torch.compile(model.forward, mode=compile_mode)
|
64 |
+
|
65 |
+
# warmup
|
66 |
+
inputs = tokenizer("This is for compilation", return_tensors="pt", padding="max_length", max_length=max_length).to(torch_device)
|
67 |
+
|
68 |
+
model_kwargs = {**inputs, "prompt_input_ids": inputs.input_ids, "prompt_attention_mask": inputs.attention_mask, }
|
69 |
+
|
70 |
+
n_steps = 1 if compile_mode == "default" else 2
|
71 |
+
for _ in range(n_steps):
|
72 |
+
_ = model.generate(**model_kwargs)
|
73 |
+
|
74 |
+
|
75 |
+
# now you can benefit from compilation speed-ups
|
76 |
+
...
|
77 |
+
|
78 |
+
```
|
79 |
+
|
80 |
+
|
81 |
+
## Streaming
|
82 |
+
|
83 |
+
### How Does It Work?
|
84 |
+
|
85 |
+
Parler-TTS is an auto-regressive transformer-based model, meaning generates audio codes (tokens) in a causal fashion.
|
86 |
+
|
87 |
+
At each decoding step, the model generates a new set of audio codes, conditional on the text input and all previous audio codes. From the
|
88 |
+
frame rate of the [DAC model](https://huggingface.co/parler-tts/dac_44khZ_8kbps) used to decode the generated codes to audio waveform, each set of generated audio codes corresponds to 0.011 seconds. This means we require a total of 1720 decoding steps to generate 20 seconds of audio.
|
89 |
+
|
90 |
+
Rather than waiting for the entire audio sequence to be generated, which would require the full 1720 decoding steps, we can start playing the audio after a specified number of decoding steps have been reached, a techinque known as [*streaming*](https://huggingface.co/docs/transformers/main/en/generation_strategies#streaming).
|
91 |
+
For example, after 86 steps we have the first second of audio ready, and so can play this without waiting for the remaining decoding steps to be complete. As we continue to generate with the Parler-TTS model, we append new chunks of generated audio to our output waveform on-the-fly. After the full 1720 decoding steps, the generated audio is complete, and is composed of 20 chunks of audio, each corresponding to 86 tokens.
|
92 |
+
This method of playing incremental generations reduces the latency of the Parler-TTS model from the total time to generate 1720 tokens, to the time taken to play the first chunk of audio (86 tokens). This can result in significant improvements to perceived latency, particularly when the chunk size is chosen to be small. In practice, the chunk size should be tuned to your device: using a smaller chunk size will mean that the first chunk is ready faster, but should not be chosen so small that the model generates slower than the time it takes to play the audio.
|
93 |
+
|
94 |
+
|
95 |
+
### How Can I Use It?
|
96 |
+
|
97 |
+
We've added [ParlerTTSStreamer](https://github.com/huggingface/parler-tts/blob/main/parler_tts/streamer.py) to the library. Don't hesitate to adapt it to your use-case.
|
98 |
+
|
99 |
+
Here's how to create a generator out of the streamer.
|
100 |
+
|
101 |
+
```py
|
102 |
+
import torch
|
103 |
+
from parler_tts import ParlerTTSForConditionalGeneration, ParlerTTSStreamer
|
104 |
+
from transformers import AutoTokenizer
|
105 |
+
from threading import Thread
|
106 |
+
|
107 |
+
torch_device = "cuda:0" # Use "mps" for Mac
|
108 |
+
torch_dtype = torch.bfloat16
|
109 |
+
model_name = "parler-tts/parler-tts-mini-v1"
|
110 |
+
|
111 |
+
# need to set padding max length
|
112 |
+
max_length = 50
|
113 |
+
|
114 |
+
# load model and tokenizer
|
115 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
116 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained(
|
117 |
+
model_name,
|
118 |
+
).to(torch_device, dtype=torch_dtype)
|
119 |
+
|
120 |
+
sampling_rate = model.audio_encoder.config.sampling_rate
|
121 |
+
frame_rate = model.audio_encoder.config.frame_rate
|
122 |
+
|
123 |
+
def generate(text, description, play_steps_in_s=0.5):
|
124 |
+
play_steps = int(frame_rate * play_steps_in_s)
|
125 |
+
streamer = ParlerTTSStreamer(model, device=torch_device, play_steps=play_steps)
|
126 |
+
# tokenization
|
127 |
+
inputs = tokenizer(description, return_tensors="pt").to(torch_device)
|
128 |
+
prompt = tokenizer(text, return_tensors="pt").to(torch_device)
|
129 |
+
# create generation kwargs
|
130 |
+
generation_kwargs = dict(
|
131 |
+
input_ids=inputs.input_ids,
|
132 |
+
prompt_input_ids=prompt.input_ids,
|
133 |
+
attention_mask=inputs.attention_mask,
|
134 |
+
prompt_attention_mask=prompt.attention_mask,
|
135 |
+
streamer=streamer,
|
136 |
+
do_sample=True,
|
137 |
+
temperature=1.0,
|
138 |
+
min_new_tokens=10,
|
139 |
+
)
|
140 |
+
# initialize Thread
|
141 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
142 |
+
thread.start()
|
143 |
+
# iterate over chunks of audio
|
144 |
+
for new_audio in streamer:
|
145 |
+
if new_audio.shape[0] == 0:
|
146 |
+
break
|
147 |
+
print(f"Sample of length: {round(new_audio.shape[0] / sampling_rate, 4)} seconds")
|
148 |
+
yield sampling_rate, new_audio
|
149 |
+
|
150 |
+
|
151 |
+
# now you can do
|
152 |
+
text = "This is a test of the streamer class"
|
153 |
+
description = "Jon's talking really fast."
|
154 |
+
|
155 |
+
chunk_size_in_s = 0.5
|
156 |
+
|
157 |
+
for (sampling_rate, audio_chunk) in generate(text, description, chunk_size_in_s):
|
158 |
+
# You can do everything that you need with the chunk now
|
159 |
+
# For example: stream it, save it, play it.
|
160 |
+
print(audio_chunk.shape)
|
161 |
+
```
|
162 |
+
|
163 |
+
## Batch generation
|
164 |
+
|
165 |
+
Batching means combining operations for multiple samples to bring the overall time spent generating the samples lower than generating sample per sample.
|
166 |
+
|
167 |
+
Here is a quick example of how you can use it:
|
168 |
+
|
169 |
+
```py
|
170 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
171 |
+
from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
|
172 |
+
import scipy
|
173 |
+
|
174 |
+
|
175 |
+
repo_id = "parler-tts/parler-tts-mini-v1"
|
176 |
+
|
177 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to("cuda")
|
178 |
+
tokenizer = AutoTokenizer.from_pretrained(repo_id, padding_side="left")
|
179 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
|
180 |
+
|
181 |
+
input_text = ["Hey, how are you doing?", "I'm not sure how to feel about it."]
|
182 |
+
description = 2 * ["A male speaker with a monotone and high-pitched voice is delivering his speech at a really low speed in a confined environment."]
|
183 |
+
|
184 |
+
inputs = tokenizer(description, return_tensors="pt", padding=True).to("cuda")
|
185 |
+
prompt = tokenizer(input_text, return_tensors="pt", padding=True).to("cuda")
|
186 |
+
|
187 |
+
set_seed(0)
|
188 |
+
generation = model.generate(
|
189 |
+
input_ids=inputs.input_ids,
|
190 |
+
attention_mask=inputs.attention_mask,
|
191 |
+
prompt_input_ids=prompt.input_ids,
|
192 |
+
prompt_attention_mask=prompt.attention_mask,
|
193 |
+
do_sample=True,
|
194 |
+
return_dict_in_generate=True,
|
195 |
+
)
|
196 |
+
|
197 |
+
audio_1 = generation.sequences[0, :generation.audios_length[0]]
|
198 |
+
audio_2 = generation.sequences[1, :generation.audios_length[1]]
|
199 |
+
|
200 |
+
print(audio_1.shape, audio_2.shape)
|
201 |
+
scipy.io.wavfile.write("sample_out.wav", rate=feature_extractor.sampling_rate, data=audio_1.cpu().numpy().squeeze())
|
202 |
+
scipy.io.wavfile.write("sample_out_2.wav", rate=feature_extractor.sampling_rate, data=audio_2.cpu().numpy().squeeze())
|
203 |
+
```
|
204 |
+
|
205 |
+
## Speaker Consistency
|
206 |
+
|
207 |
+
The checkpoint was trained on 34 speakers. The full list of available speakers includes:
|
208 |
+
Laura, Gary, Jon, Lea, Karen, Rick, Brenda, David, Eileen, Jordan, Mike, Yann, Joy, James, Eric, Lauren, Rose, Will, Jason, Aaron, Naomie, Alisa, Patrick, Jerry, Tina, Jenna, Bill, Tom, Carol, Barbara, Rebecca, Anna, Bruce, and Emily.
|
209 |
+
|
210 |
+
However, the models performed better with certain speakers. Below are the top 20 speakers for each model variant, ranked by their average speaker similarity scores:
|
211 |
+
|
212 |
+
### Large Model - Top 20 Speakers
|
213 |
+
|
214 |
+
| Speaker | Similarity Score |
|
215 |
+
|---------|------------------|
|
216 |
+
| Will | 0.906055 |
|
217 |
+
| Eric | 0.887598 |
|
218 |
+
| Laura | 0.877930 |
|
219 |
+
| Alisa | 0.877393 |
|
220 |
+
| Patrick | 0.873682 |
|
221 |
+
| Rose | 0.873047 |
|
222 |
+
| Jerry | 0.871582 |
|
223 |
+
| Jordan | 0.870703 |
|
224 |
+
| Lauren | 0.867432 |
|
225 |
+
| Jenna | 0.866455 |
|
226 |
+
| Karen | 0.866309 |
|
227 |
+
| Rick | 0.863135 |
|
228 |
+
| Bill | 0.862207 |
|
229 |
+
| James | 0.856934 |
|
230 |
+
| Yann | 0.856787 |
|
231 |
+
| Emily | 0.856543 |
|
232 |
+
| Anna | 0.848877 |
|
233 |
+
| Jon | 0.848828 |
|
234 |
+
| Brenda | 0.848291 |
|
235 |
+
| Barbara | 0.847998 |
|
236 |
+
|
237 |
+
### Mini Model - Top 20 Speakers
|
238 |
+
|
239 |
+
| Speaker | Similarity Score |
|
240 |
+
|---------|------------------|
|
241 |
+
| Jon | 0.908301 |
|
242 |
+
| Lea | 0.904785 |
|
243 |
+
| Gary | 0.903516 |
|
244 |
+
| Jenna | 0.901807 |
|
245 |
+
| Mike | 0.885742 |
|
246 |
+
| Laura | 0.882666 |
|
247 |
+
| Lauren | 0.878320 |
|
248 |
+
| Eileen | 0.875635 |
|
249 |
+
| Alisa | 0.874219 |
|
250 |
+
| Karen | 0.872363 |
|
251 |
+
| Barbara | 0.871509 |
|
252 |
+
| Carol | 0.863623 |
|
253 |
+
| Emily | 0.854932 |
|
254 |
+
| Rose | 0.852246 |
|
255 |
+
| Will | 0.851074 |
|
256 |
+
| Patrick | 0.850977 |
|
257 |
+
| Eric | 0.845459 |
|
258 |
+
| Rick | 0.845020 |
|
259 |
+
| Anna | 0.844922 |
|
260 |
+
| Tina | 0.839160 |
|
261 |
+
|
262 |
+
The numbers represent the average speaker similarity between a random snippet of the person speaking and a randomly Parler-generated snippet. Higher scores indicate better model performance in maintaining voice consistency.
|
263 |
+
|
264 |
+
These scores are derived from [dataset for Mini](https://huggingface.co/datasets/ylacombe/parler-tts-mini-v1_speaker_similarity) and [dataset for Large](https://huggingface.co/datasets/ylacombe/parler-large-v1-og_speaker_similarity).
|
parler-tts/LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright [2024] [The HuggingFace Inc. team]
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
parler-tts/Makefile
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
check_dirs := .
|
2 |
+
|
3 |
+
quality:
|
4 |
+
black --check $(check_dirs)
|
5 |
+
ruff $(check_dirs)
|
6 |
+
|
7 |
+
style:
|
8 |
+
black $(check_dirs)
|
9 |
+
ruff $(check_dirs) --fix
|
parler-tts/README.md
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Parler-TTS
|
2 |
+
|
3 |
+
Parler-TTS is a lightweight text-to-speech (TTS) model that can generate high-quality, natural sounding speech in the style of a given speaker (gender, pitch, speaking style, etc). It is a reproduction of work from the paper [Natural language guidance of high-fidelity text-to-speech with synthetic annotations](https://www.text-description-to-speech.com) by Dan Lyth and Simon King, from Stability AI and Edinburgh University respectively.
|
4 |
+
|
5 |
+
Contrarily to other TTS models, Parler-TTS is a **fully open-source** release. All of the datasets, pre-processing, training code and weights are released publicly under permissive license, enabling the community to build on our work and develop their own powerful TTS models.
|
6 |
+
|
7 |
+
This repository contains the inference and training code for Parler-TTS. It is designed to accompany the [Data-Speech](https://github.com/huggingface/dataspeech) repository for dataset annotation.
|
8 |
+
|
9 |
+
> [!IMPORTANT]
|
10 |
+
> **08/08/2024:** We are proud to release two new Parler-TTS checkpoints:
|
11 |
+
> 1. [Parler-TTS Mini](https://huggingface.co/parler-tts/parler-tts-mini-v1), an 880M parameter model.
|
12 |
+
> 2. [Parler-TTS Large](https://huggingface.co/parler-tts/parler-tts-large-v1), a 2.3B parameter model.
|
13 |
+
>
|
14 |
+
> These checkpoints have been trained on 45k hours of audiobook data.
|
15 |
+
>
|
16 |
+
> In addition, the code is optimized for much faster generation: we've added SDPA and Flash Attention 2 compatibility, as well as the ability to compile the model.
|
17 |
+
|
18 |
+
## 📖 Quick Index
|
19 |
+
* [Installation](#installation)
|
20 |
+
* [Usage](#usage)
|
21 |
+
- [🎲 Using a random voice](#-random-voice)
|
22 |
+
- [🎯 Using a specific speaker](#-using-a-specific-speaker)
|
23 |
+
* [Training](#training)
|
24 |
+
* [Demo](https://huggingface.co/spaces/parler-tts/parler_tts)
|
25 |
+
* [Model weights and datasets](https://huggingface.co/parler-tts)
|
26 |
+
* [Optimizing inference](#-optimizing-inference-speed)
|
27 |
+
|
28 |
+
## Installation
|
29 |
+
|
30 |
+
Parler-TTS has light-weight dependencies and can be installed in one line:
|
31 |
+
|
32 |
+
```sh
|
33 |
+
pip install git+https://github.com/huggingface/parler-tts.git
|
34 |
+
```
|
35 |
+
|
36 |
+
Apple Silicon users will need to run a follow-up command to make use the nightly PyTorch (2.4) build for bfloat16 support:
|
37 |
+
|
38 |
+
```sh
|
39 |
+
pip3 install --pre torch torchaudio --index-url https://download.pytorch.org/whl/nightly/cpu
|
40 |
+
```
|
41 |
+
|
42 |
+
## Usage
|
43 |
+
|
44 |
+
> [!TIP]
|
45 |
+
> You can directly try it out in an interactive demo [here](https://huggingface.co/spaces/parler-tts/parler_tts)!
|
46 |
+
|
47 |
+
Using Parler-TTS is as simple as "bonjour". Simply install the library once:
|
48 |
+
|
49 |
+
```sh
|
50 |
+
pip install git+https://github.com/huggingface/parler-tts.git
|
51 |
+
```
|
52 |
+
|
53 |
+
### 🎲 Random voice
|
54 |
+
|
55 |
+
|
56 |
+
**Parler-TTS** has been trained to generate speech with features that can be controlled with a simple text prompt, for example:
|
57 |
+
|
58 |
+
```py
|
59 |
+
import torch
|
60 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
61 |
+
from transformers import AutoTokenizer
|
62 |
+
import soundfile as sf
|
63 |
+
|
64 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
65 |
+
|
66 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained("parler-tts/parler-tts-mini-v1").to(device)
|
67 |
+
tokenizer = AutoTokenizer.from_pretrained("parler-tts/parler-tts-mini-v1")
|
68 |
+
|
69 |
+
prompt = "Hey, how are you doing today?"
|
70 |
+
description = "A female speaker delivers a slightly expressive and animated speech with a moderate speed and pitch. The recording is of very high quality, with the speaker's voice sounding clear and very close up."
|
71 |
+
|
72 |
+
input_ids = tokenizer(description, return_tensors="pt").input_ids.to(device)
|
73 |
+
prompt_input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
|
74 |
+
|
75 |
+
generation = model.generate(input_ids=input_ids, prompt_input_ids=prompt_input_ids)
|
76 |
+
audio_arr = generation.cpu().numpy().squeeze()
|
77 |
+
sf.write("parler_tts_out.wav", audio_arr, model.config.sampling_rate)
|
78 |
+
```
|
79 |
+
|
80 |
+
### 🎯 Using a specific speaker
|
81 |
+
|
82 |
+
To ensure speaker consistency across generations, this checkpoint was also trained on 34 speakers, characterized by name. The full list of available speakers includes:
|
83 |
+
Laura, Gary, Jon, Lea, Karen, Rick, Brenda, David, Eileen, Jordan, Mike, Yann, Joy, James, Eric, Lauren, Rose, Will, Jason, Aaron, Naomie, Alisa, Patrick, Jerry, Tina, Jenna, Bill, Tom, Carol, Barbara, Rebecca, Anna, Bruce, Emily.
|
84 |
+
|
85 |
+
To take advantage of this, simply adapt your text description to specify which speaker to use: `Jon's voice is monotone yet slightly fast in delivery, with a very close recording that almost has no background noise.`
|
86 |
+
|
87 |
+
You can replace "Jon" with any of the names from the list above to utilize different speaker characteristics. Each speaker has unique vocal qualities that can be leveraged to suit your specific needs. For more detailed information on speaker performance with voice consistency, please refer [inference guide](INFERENCE.md#speaker-consistency).
|
88 |
+
|
89 |
+
```py
|
90 |
+
import torch
|
91 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
92 |
+
from transformers import AutoTokenizer
|
93 |
+
import soundfile as sf
|
94 |
+
|
95 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
96 |
+
|
97 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained("parler-tts/parler-tts-mini-v1").to(device)
|
98 |
+
tokenizer = AutoTokenizer.from_pretrained("parler-tts/parler-tts-mini-v1")
|
99 |
+
|
100 |
+
prompt = "Hey, how are you doing today?"
|
101 |
+
description = "Jon's voice is monotone yet slightly fast in delivery, with a very close recording that almost has no background noise."
|
102 |
+
|
103 |
+
input_ids = tokenizer(description, return_tensors="pt").input_ids.to(device)
|
104 |
+
prompt_input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
|
105 |
+
|
106 |
+
generation = model.generate(input_ids=input_ids, prompt_input_ids=prompt_input_ids)
|
107 |
+
audio_arr = generation.cpu().numpy().squeeze()
|
108 |
+
sf.write("parler_tts_out.wav", audio_arr, model.config.sampling_rate)
|
109 |
+
```
|
110 |
+
|
111 |
+
**Tips**:
|
112 |
+
* Include the term "very clear audio" to generate the highest quality audio, and "very noisy audio" for high levels of background noise
|
113 |
+
* Punctuation can be used to control the prosody of the generations, e.g. use commas to add small breaks in speech
|
114 |
+
* The remaining speech features (gender, speaking rate, pitch and reverberation) can be controlled directly through the prompt
|
115 |
+
|
116 |
+
### ✨ Optimizing Inference Speed
|
117 |
+
|
118 |
+
We've set up an [inference guide](INFERENCE.md) to make generation faster. Think SDPA, torch.compile and streaming!
|
119 |
+
|
120 |
+
|
121 |
+
https://github.com/huggingface/parler-tts/assets/52246514/251e2488-fe6e-42c1-81cd-814c5b7795b0
|
122 |
+
|
123 |
+
## Training
|
124 |
+
|
125 |
+
<a target="_blank" href="https://github.com/ylacombe/scripts_and_notebooks/blob/main/Finetuning_Parler_TTS_v1_on_a_single_speaker_dataset.ipynb">
|
126 |
+
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
|
127 |
+
</a>
|
128 |
+
|
129 |
+
The [training folder](/training/) contains all the information to train or fine-tune your own Parler-TTS model. It consists of:
|
130 |
+
- [1. An introduction to the Parler-TTS architecture](/training/README.md#1-architecture)
|
131 |
+
- [2. The first steps to get started](/training/README.md#2-getting-started)
|
132 |
+
- [3. A training guide](/training/README.md#3-training)
|
133 |
+
|
134 |
+
> [!IMPORTANT]
|
135 |
+
> **TL;DR:** After having followed the [installation steps](/training/README.md#requirements), you can reproduce the Parler-TTS Mini v1 training recipe with the following command line:
|
136 |
+
|
137 |
+
```sh
|
138 |
+
accelerate launch ./training/run_parler_tts_training.py ./helpers/training_configs/starting_point_v1.json
|
139 |
+
```
|
140 |
+
|
141 |
+
> [!IMPORTANT]
|
142 |
+
> You can also follow [this fine-tuning guide](https://github.com/ylacombe/scripts_and_notebooks/blob/main/Finetuning_Parler_TTS_v1_on_a_single_speaker_dataset.ipynb) on a mono-speaker dataset example.
|
143 |
+
|
144 |
+
## Acknowledgements
|
145 |
+
|
146 |
+
This library builds on top of a number of open-source giants, to whom we'd like to extend our warmest thanks for providing these tools!
|
147 |
+
|
148 |
+
Special thanks to:
|
149 |
+
- Dan Lyth and Simon King, from Stability AI and Edinburgh University respectively, for publishing such a promising and clear research paper: [Natural language guidance of high-fidelity text-to-speech with synthetic annotations](https://arxiv.org/abs/2402.01912).
|
150 |
+
- the many libraries used, namely [🤗 datasets](https://huggingface.co/docs/datasets/v2.17.0/en/index), [🤗 accelerate](https://huggingface.co/docs/accelerate/en/index), [jiwer](https://github.com/jitsi/jiwer), [wandb](https://wandb.ai/), and [🤗 transformers](https://huggingface.co/docs/transformers/index).
|
151 |
+
- Descript for the [DAC codec model](https://github.com/descriptinc/descript-audio-codec)
|
152 |
+
- Hugging Face 🤗 for providing compute resources and time to explore!
|
153 |
+
|
154 |
+
|
155 |
+
## Citation
|
156 |
+
|
157 |
+
If you found this repository useful, please consider citing this work and also the original Stability AI paper:
|
158 |
+
|
159 |
+
```
|
160 |
+
@misc{lacombe-etal-2024-parler-tts,
|
161 |
+
author = {Yoach Lacombe and Vaibhav Srivastav and Sanchit Gandhi},
|
162 |
+
title = {Parler-TTS},
|
163 |
+
year = {2024},
|
164 |
+
publisher = {GitHub},
|
165 |
+
journal = {GitHub repository},
|
166 |
+
howpublished = {\url{https://github.com/huggingface/parler-tts}}
|
167 |
+
}
|
168 |
+
```
|
169 |
+
|
170 |
+
```
|
171 |
+
@misc{lyth2024natural,
|
172 |
+
title={Natural language guidance of high-fidelity text-to-speech with synthetic annotations},
|
173 |
+
author={Dan Lyth and Simon King},
|
174 |
+
year={2024},
|
175 |
+
eprint={2402.01912},
|
176 |
+
archivePrefix={arXiv},
|
177 |
+
primaryClass={cs.SD}
|
178 |
+
}
|
179 |
+
```
|
180 |
+
|
181 |
+
## Contribution
|
182 |
+
|
183 |
+
Contributions are welcome, as the project offers many possibilities for improvement and exploration.
|
184 |
+
|
185 |
+
Namely, we're looking at ways to improve both quality and speed:
|
186 |
+
- Datasets:
|
187 |
+
- Train on more data
|
188 |
+
- Add more features such as accents
|
189 |
+
- Training:
|
190 |
+
- Add PEFT compatibility to do Lora fine-tuning.
|
191 |
+
- Add possibility to train without description column.
|
192 |
+
- Add notebook training.
|
193 |
+
- Explore multilingual training.
|
194 |
+
- Explore mono-speaker finetuning.
|
195 |
+
- Explore more architectures.
|
196 |
+
- Optimization:
|
197 |
+
- Compilation and static cache
|
198 |
+
- Support to FA2 and SDPA
|
199 |
+
- Evaluation:
|
200 |
+
- Add more evaluation metrics
|
201 |
+
|
parler-tts/helpers/gradio_demo/app.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from transformers import AutoFeatureExtractor, AutoTokenizer, set_seed
|
4 |
+
|
5 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
6 |
+
|
7 |
+
|
8 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
9 |
+
|
10 |
+
repo_id = "parler-tts/parler_tts_mini_v0.1"
|
11 |
+
|
12 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
|
13 |
+
tokenizer = AutoTokenizer.from_pretrained(repo_id)
|
14 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
|
15 |
+
|
16 |
+
|
17 |
+
SAMPLE_RATE = feature_extractor.sampling_rate
|
18 |
+
SEED = 41
|
19 |
+
|
20 |
+
default_text = "Please surprise me and speak in whatever voice you enjoy."
|
21 |
+
|
22 |
+
title = "# Parler-TTS </div>"
|
23 |
+
|
24 |
+
examples = [
|
25 |
+
[
|
26 |
+
"'This is the best time of my life, Bartley,' she said happily.",
|
27 |
+
"A female speaker with a slightly low-pitched, quite monotone voice delivers her words at a slightly faster-than-average pace in a confined space with very clear audio.",
|
28 |
+
],
|
29 |
+
[
|
30 |
+
"Montrose also, after having experienced still more variety of good and bad fortune, threw down his arms, and retired out of the kingdom. ",
|
31 |
+
"A male speaker with a slightly high-pitched voice delivering his words at a slightly slow pace in a small, confined space with a touch of background noise and a quite monotone tone.",
|
32 |
+
],
|
33 |
+
[
|
34 |
+
"montrose also after having experienced still more variety of good and bad fortune threw down his arms and retired out of the kingdom",
|
35 |
+
"A male speaker with a low-pitched voice delivering his words at a fast pace in a small, confined space with a lot of background noise and an animated tone.",
|
36 |
+
],
|
37 |
+
]
|
38 |
+
|
39 |
+
|
40 |
+
def gen_tts(text, description):
|
41 |
+
inputs = tokenizer(description, return_tensors="pt").to(device)
|
42 |
+
prompt = tokenizer(text, return_tensors="pt").to(device)
|
43 |
+
|
44 |
+
set_seed(SEED)
|
45 |
+
generation = model.generate(
|
46 |
+
input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids, do_sample=True, temperature=1.0
|
47 |
+
)
|
48 |
+
audio_arr = generation.cpu().numpy().squeeze()
|
49 |
+
|
50 |
+
return (SAMPLE_RATE, audio_arr)
|
51 |
+
|
52 |
+
|
53 |
+
css = """
|
54 |
+
#share-btn-container {
|
55 |
+
display: flex;
|
56 |
+
padding-left: 0.5rem !important;
|
57 |
+
padding-right: 0.5rem !important;
|
58 |
+
background-color: #000000;
|
59 |
+
justify-content: center;
|
60 |
+
align-items: center;
|
61 |
+
border-radius: 9999px !important;
|
62 |
+
width: 13rem;
|
63 |
+
margin-top: 10px;
|
64 |
+
margin-left: auto;
|
65 |
+
flex: unset !important;
|
66 |
+
}
|
67 |
+
#share-btn {
|
68 |
+
all: initial;
|
69 |
+
color: #ffffff;
|
70 |
+
font-weight: 600;
|
71 |
+
cursor: pointer;
|
72 |
+
font-family: 'IBM Plex Sans', sans-serif;
|
73 |
+
margin-left: 0.5rem !important;
|
74 |
+
padding-top: 0.25rem !important;
|
75 |
+
padding-bottom: 0.25rem !important;
|
76 |
+
right:0;
|
77 |
+
}
|
78 |
+
#share-btn * {
|
79 |
+
all: unset !important;
|
80 |
+
}
|
81 |
+
#share-btn-container div:nth-child(-n+2){
|
82 |
+
width: auto !important;
|
83 |
+
min-height: 0px !important;
|
84 |
+
}
|
85 |
+
#share-btn-container .wrap {
|
86 |
+
display: none !important;
|
87 |
+
}
|
88 |
+
"""
|
89 |
+
with gr.Blocks(css=css) as block:
|
90 |
+
gr.Markdown(title)
|
91 |
+
with gr.Row():
|
92 |
+
with gr.Column():
|
93 |
+
input_text = gr.Textbox(label="Input Text", lines=2, value=default_text, elem_id="input_text")
|
94 |
+
description = gr.Textbox(label="Description", lines=2, value="", elem_id="input_description")
|
95 |
+
run_button = gr.Button("Generate Audio", variant="primary")
|
96 |
+
with gr.Column():
|
97 |
+
audio_out = gr.Audio(label="Parler-TTS generation", type="numpy", elem_id="audio_out")
|
98 |
+
|
99 |
+
inputs = [input_text, description]
|
100 |
+
outputs = [audio_out]
|
101 |
+
gr.Examples(examples=examples, fn=gen_tts, inputs=inputs, outputs=outputs, cache_examples=True)
|
102 |
+
run_button.click(fn=gen_tts, inputs=inputs, outputs=outputs, queue=True)
|
103 |
+
|
104 |
+
block.queue()
|
105 |
+
block.launch(share=True)
|
parler-tts/helpers/model_init_scripts/init_dummy_model.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
|
4 |
+
from transformers import AutoConfig
|
5 |
+
|
6 |
+
from parler_tts import ParlerTTSDecoderConfig, ParlerTTSForCausalLM, ParlerTTSForConditionalGeneration
|
7 |
+
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument("save_directory", type=str, help="Directory where to save the model and the decoder.")
|
12 |
+
parser.add_argument("--text_model", type=str, help="Repository id or path to the text encoder.")
|
13 |
+
parser.add_argument("--audio_model", type=str, help="Repository id or path to the audio encoder.")
|
14 |
+
|
15 |
+
args = parser.parse_args()
|
16 |
+
|
17 |
+
text_model = args.text_model
|
18 |
+
encodec_version = args.audio_model
|
19 |
+
|
20 |
+
t5 = AutoConfig.from_pretrained(text_model)
|
21 |
+
encodec = AutoConfig.from_pretrained(encodec_version)
|
22 |
+
|
23 |
+
encodec_vocab_size = encodec.codebook_size
|
24 |
+
num_codebooks = encodec.num_codebooks
|
25 |
+
print("num_codebooks", num_codebooks)
|
26 |
+
|
27 |
+
decoder_config = ParlerTTSDecoderConfig(
|
28 |
+
vocab_size=encodec_vocab_size + 1,
|
29 |
+
max_position_embeddings=2048,
|
30 |
+
num_hidden_layers=4,
|
31 |
+
ffn_dim=512,
|
32 |
+
num_attention_heads=8,
|
33 |
+
layerdrop=0.0,
|
34 |
+
use_cache=True,
|
35 |
+
activation_function="gelu",
|
36 |
+
hidden_size=512,
|
37 |
+
dropout=0.0,
|
38 |
+
attention_dropout=0.0,
|
39 |
+
activation_dropout=0.0,
|
40 |
+
pad_token_id=encodec_vocab_size,
|
41 |
+
eos_token_id=encodec_vocab_size,
|
42 |
+
bos_token_id=encodec_vocab_size + 1,
|
43 |
+
num_codebooks=num_codebooks,
|
44 |
+
)
|
45 |
+
|
46 |
+
decoder = ParlerTTSForCausalLM(decoder_config)
|
47 |
+
decoder.save_pretrained(os.path.join(args.save_directory, "decoder"))
|
48 |
+
|
49 |
+
model = ParlerTTSForConditionalGeneration.from_sub_models_pretrained(
|
50 |
+
text_encoder_pretrained_model_name_or_path=text_model,
|
51 |
+
audio_encoder_pretrained_model_name_or_path=encodec_version,
|
52 |
+
decoder_pretrained_model_name_or_path=os.path.join(args.save_directory, "decoder"),
|
53 |
+
vocab_size=t5.vocab_size,
|
54 |
+
)
|
55 |
+
|
56 |
+
# set the appropriate bos/pad token ids
|
57 |
+
model.generation_config.decoder_start_token_id = encodec_vocab_size + 1
|
58 |
+
model.generation_config.pad_token_id = encodec_vocab_size
|
59 |
+
model.generation_config.eos_token_id = encodec_vocab_size
|
60 |
+
|
61 |
+
# set other default generation config params
|
62 |
+
model.generation_config.max_length = int(30 * model.audio_encoder.config.frame_rate)
|
63 |
+
model.generation_config.do_sample = True # True
|
64 |
+
|
65 |
+
|
66 |
+
model.config.pad_token_id = encodec_vocab_size
|
67 |
+
model.config.decoder_start_token_id = encodec_vocab_size + 1
|
68 |
+
|
69 |
+
model.save_pretrained(os.path.join(args.save_directory, "tiny-model"))
|
parler-tts/helpers/model_init_scripts/init_dummy_model_with_encodec.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
|
4 |
+
from transformers import AutoConfig
|
5 |
+
|
6 |
+
from parler_tts import ParlerTTSDecoderConfig, ParlerTTSForCausalLM, ParlerTTSForConditionalGeneration
|
7 |
+
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument("save_directory", type=str, help="Directory where to save the model and the decoder.")
|
12 |
+
args = parser.parse_args()
|
13 |
+
|
14 |
+
text_model = "google-t5/t5-small"
|
15 |
+
encodec_version = "facebook/encodec_24khz"
|
16 |
+
|
17 |
+
t5 = AutoConfig.from_pretrained(text_model)
|
18 |
+
encodec = AutoConfig.from_pretrained(encodec_version)
|
19 |
+
|
20 |
+
encodec_vocab_size = encodec.codebook_size
|
21 |
+
num_codebooks = 8
|
22 |
+
print("num_codebooks", num_codebooks)
|
23 |
+
|
24 |
+
decoder_config = ParlerTTSDecoderConfig(
|
25 |
+
vocab_size=encodec_vocab_size + 1,
|
26 |
+
max_position_embeddings=2048,
|
27 |
+
num_hidden_layers=4,
|
28 |
+
ffn_dim=512,
|
29 |
+
num_attention_heads=8,
|
30 |
+
layerdrop=0.0,
|
31 |
+
use_cache=True,
|
32 |
+
activation_function="gelu",
|
33 |
+
hidden_size=512,
|
34 |
+
dropout=0.0,
|
35 |
+
attention_dropout=0.0,
|
36 |
+
activation_dropout=0.0,
|
37 |
+
pad_token_id=encodec_vocab_size,
|
38 |
+
eos_token_id=encodec_vocab_size,
|
39 |
+
bos_token_id=encodec_vocab_size + 1,
|
40 |
+
num_codebooks=num_codebooks,
|
41 |
+
)
|
42 |
+
|
43 |
+
decoder = ParlerTTSForCausalLM(decoder_config)
|
44 |
+
|
45 |
+
decoder.save_pretrained(os.path.join(args.save_directory, "decoder"))
|
46 |
+
|
47 |
+
model = ParlerTTSForConditionalGeneration.from_sub_models_pretrained(
|
48 |
+
text_encoder_pretrained_model_name_or_path=text_model,
|
49 |
+
audio_encoder_pretrained_model_name_or_path=encodec_version,
|
50 |
+
decoder_pretrained_model_name_or_path=os.path.join(args.save_directory, "decoder"),
|
51 |
+
vocab_size=t5.vocab_size,
|
52 |
+
)
|
53 |
+
|
54 |
+
# set the appropriate bos/pad token ids
|
55 |
+
model.generation_config.decoder_start_token_id = encodec_vocab_size + 1
|
56 |
+
model.generation_config.pad_token_id = encodec_vocab_size
|
57 |
+
model.generation_config.eos_token_id = encodec_vocab_size
|
58 |
+
|
59 |
+
# set other default generation config params
|
60 |
+
model.generation_config.max_length = int(30 * model.audio_encoder.config.frame_rate)
|
61 |
+
model.generation_config.do_sample = True # True
|
62 |
+
|
63 |
+
|
64 |
+
model.config.pad_token_id = encodec_vocab_size
|
65 |
+
model.config.decoder_start_token_id = encodec_vocab_size + 1
|
66 |
+
|
67 |
+
model.save_pretrained(os.path.join(args.save_directory, "tiny-model"))
|
parler-tts/helpers/model_init_scripts/init_large_model.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from parler_tts import ParlerTTSForCausalLM, ParlerTTSForConditionalGeneration, ParlerTTSDecoderConfig
|
2 |
+
from transformers import AutoConfig
|
3 |
+
import os
|
4 |
+
import argparse
|
5 |
+
|
6 |
+
|
7 |
+
if __name__ == "__main__":
|
8 |
+
parser = argparse.ArgumentParser()
|
9 |
+
parser.add_argument("save_directory", type=str, help="Directory where to save the model and the decoder.")
|
10 |
+
parser.add_argument("--text_model", type=str, help="Repository id or path to the text encoder.")
|
11 |
+
parser.add_argument("--audio_model", type=str, help="Repository id or path to the audio encoder.")
|
12 |
+
|
13 |
+
args = parser.parse_args()
|
14 |
+
|
15 |
+
text_model = args.text_model
|
16 |
+
encodec_version = args.audio_model
|
17 |
+
|
18 |
+
t5 = AutoConfig.from_pretrained(text_model)
|
19 |
+
encodec = AutoConfig.from_pretrained(encodec_version)
|
20 |
+
|
21 |
+
encodec_vocab_size = encodec.codebook_size
|
22 |
+
num_codebooks = encodec.num_codebooks
|
23 |
+
print("num_codebooks", num_codebooks)
|
24 |
+
|
25 |
+
decoder_config = ParlerTTSDecoderConfig(
|
26 |
+
vocab_size=encodec_vocab_size + 64, # + 64 instead of +1 to have a multiple of 64
|
27 |
+
max_position_embeddings=4096, # 30 s = 2580
|
28 |
+
num_hidden_layers=30,
|
29 |
+
ffn_dim=6144,
|
30 |
+
num_attention_heads=24,
|
31 |
+
num_key_value_heads=24,
|
32 |
+
layerdrop=0.0,
|
33 |
+
use_cache=True,
|
34 |
+
activation_function="gelu",
|
35 |
+
hidden_size=1536,
|
36 |
+
dropout=0.1,
|
37 |
+
attention_dropout=0.0,
|
38 |
+
activation_dropout=0.0,
|
39 |
+
pad_token_id=encodec_vocab_size,
|
40 |
+
eos_token_id=encodec_vocab_size,
|
41 |
+
bos_token_id=encodec_vocab_size + 1,
|
42 |
+
num_codebooks=num_codebooks,
|
43 |
+
)
|
44 |
+
|
45 |
+
decoder = ParlerTTSForCausalLM(decoder_config)
|
46 |
+
decoder.save_pretrained(os.path.join(args.save_directory, "decoder"))
|
47 |
+
|
48 |
+
model = ParlerTTSForConditionalGeneration.from_sub_models_pretrained(
|
49 |
+
text_encoder_pretrained_model_name_or_path=text_model,
|
50 |
+
audio_encoder_pretrained_model_name_or_path=encodec_version,
|
51 |
+
decoder_pretrained_model_name_or_path=os.path.join(args.save_directory, "decoder"),
|
52 |
+
vocab_size=t5.vocab_size,
|
53 |
+
)
|
54 |
+
|
55 |
+
# set the appropriate bos/pad token ids
|
56 |
+
model.generation_config.decoder_start_token_id = encodec_vocab_size + 1
|
57 |
+
model.generation_config.pad_token_id = encodec_vocab_size
|
58 |
+
model.generation_config.eos_token_id = encodec_vocab_size
|
59 |
+
|
60 |
+
# set other default generation config params
|
61 |
+
model.generation_config.max_length = int(30 * model.audio_encoder.config.frame_rate)
|
62 |
+
model.generation_config.do_sample = True # True
|
63 |
+
|
64 |
+
|
65 |
+
model.config.pad_token_id = encodec_vocab_size
|
66 |
+
model.config.decoder_start_token_id = encodec_vocab_size + 1
|
67 |
+
|
68 |
+
model.save_pretrained(os.path.join(args.save_directory, "parler-tts-untrained-larger/"))
|
parler-tts/helpers/model_init_scripts/init_model_600M.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
|
4 |
+
from transformers import AutoConfig
|
5 |
+
|
6 |
+
from parler_tts import ParlerTTSDecoderConfig, ParlerTTSForCausalLM, ParlerTTSForConditionalGeneration
|
7 |
+
|
8 |
+
|
9 |
+
if __name__ == "__main__":
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument("save_directory", type=str, help="Directory where to save the model and the decoder.")
|
12 |
+
parser.add_argument("--text_model", type=str, help="Repository id or path to the text encoder.")
|
13 |
+
parser.add_argument("--audio_model", type=str, help="Repository id or path to the audio encoder.")
|
14 |
+
|
15 |
+
args = parser.parse_args()
|
16 |
+
|
17 |
+
text_model = args.text_model
|
18 |
+
encodec_version = args.audio_model
|
19 |
+
|
20 |
+
t5 = AutoConfig.from_pretrained(text_model)
|
21 |
+
encodec = AutoConfig.from_pretrained(encodec_version)
|
22 |
+
|
23 |
+
encodec_vocab_size = encodec.codebook_size
|
24 |
+
num_codebooks = encodec.num_codebooks
|
25 |
+
print("num_codebooks", num_codebooks)
|
26 |
+
|
27 |
+
decoder_config = ParlerTTSDecoderConfig(
|
28 |
+
vocab_size=encodec_vocab_size + 64, # + 64 instead of +1 to have a multiple of 64
|
29 |
+
max_position_embeddings=4096, # 30 s = 2580
|
30 |
+
num_hidden_layers=24,
|
31 |
+
ffn_dim=4096,
|
32 |
+
num_attention_heads=16,
|
33 |
+
layerdrop=0.0,
|
34 |
+
use_cache=True,
|
35 |
+
activation_function="gelu",
|
36 |
+
hidden_size=1024,
|
37 |
+
dropout=0.1,
|
38 |
+
attention_dropout=0.0,
|
39 |
+
activation_dropout=0.0,
|
40 |
+
pad_token_id=encodec_vocab_size,
|
41 |
+
eos_token_id=encodec_vocab_size,
|
42 |
+
bos_token_id=encodec_vocab_size + 1,
|
43 |
+
num_codebooks=num_codebooks,
|
44 |
+
)
|
45 |
+
|
46 |
+
decoder = ParlerTTSForCausalLM(decoder_config)
|
47 |
+
decoder.save_pretrained(os.path.join(args.save_directory, "decoder"))
|
48 |
+
|
49 |
+
model = ParlerTTSForConditionalGeneration.from_sub_models_pretrained(
|
50 |
+
text_encoder_pretrained_model_name_or_path=text_model,
|
51 |
+
audio_encoder_pretrained_model_name_or_path=encodec_version,
|
52 |
+
decoder_pretrained_model_name_or_path=os.path.join(args.save_directory, "decoder"),
|
53 |
+
vocab_size=t5.vocab_size,
|
54 |
+
)
|
55 |
+
|
56 |
+
# set the appropriate bos/pad token ids
|
57 |
+
model.generation_config.decoder_start_token_id = encodec_vocab_size + 1
|
58 |
+
model.generation_config.pad_token_id = encodec_vocab_size
|
59 |
+
model.generation_config.eos_token_id = encodec_vocab_size
|
60 |
+
|
61 |
+
# set other default generation config params
|
62 |
+
model.generation_config.max_length = int(30 * model.audio_encoder.config.frame_rate)
|
63 |
+
model.generation_config.do_sample = True # True
|
64 |
+
|
65 |
+
model.config.pad_token_id = encodec_vocab_size
|
66 |
+
model.config.decoder_start_token_id = encodec_vocab_size + 1
|
67 |
+
|
68 |
+
model.save_pretrained(os.path.join(args.save_directory, "parler-tts-untrained-600M/"))
|
parler-tts/helpers/push_to_hub_scripts/push_dac_to_hub.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dac
|
2 |
+
from transformers import AutoConfig, AutoModel, EncodecFeatureExtractor
|
3 |
+
|
4 |
+
from parler_tts import DACConfig, DACModel
|
5 |
+
from transformers import AutoConfig, AutoModel
|
6 |
+
from transformers import EncodecFeatureExtractor
|
7 |
+
|
8 |
+
from importlib.metadata import version
|
9 |
+
from packaging.version import Version
|
10 |
+
|
11 |
+
if Version(version("transformers"))<= Version("4.44.2dev"):
|
12 |
+
AutoConfig.register("dac", DACConfig)
|
13 |
+
else:
|
14 |
+
AutoConfig.register("dac_on_the_hub", DACConfig)
|
15 |
+
|
16 |
+
AutoModel.register(DACConfig, DACModel)
|
17 |
+
|
18 |
+
# Download a model
|
19 |
+
model_path = dac.utils.download(model_type="44khz")
|
20 |
+
model = dac.DAC.load(model_path)
|
21 |
+
|
22 |
+
hf_dac = DACModel(DACConfig())
|
23 |
+
hf_dac.model.load_state_dict(model.state_dict())
|
24 |
+
|
25 |
+
hf_dac.push_to_hub("parler-tts/dac_44khZ_8kbps")
|
26 |
+
EncodecFeatureExtractor(sampling_rate=44100).push_to_hub("parler-tts/dac_44khZ_8kbps")
|
parler-tts/helpers/push_to_hub_scripts/push_trained_parler_tts_to_hub.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoFeatureExtractor, AutoTokenizer
|
2 |
+
|
3 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
4 |
+
|
5 |
+
|
6 |
+
path = "TODO"
|
7 |
+
repo_id = "parler_tts_600M"
|
8 |
+
|
9 |
+
|
10 |
+
AutoFeatureExtractor.from_pretrained("ylacombe/dac_44khZ_8kbps").push_to_hub(repo_id)
|
11 |
+
AutoTokenizer.from_pretrained("google/t5-v1_1-base").push_to_hub(repo_id)
|
12 |
+
|
13 |
+
ParlerTTSForConditionalGeneration.from_pretrained(path).push_to_hub(repo_id)
|
parler-tts/helpers/training_configs/librispeech_tts_r_300M_dummy.json
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"model_name_or_path": "./parler-tts-untrained-600M/parler-tts-untrained-600M/",
|
3 |
+
"save_to_disk": "./tmp_dataset_audio/",
|
4 |
+
"temporary_save_to_disk": "./audio_code_tmp/",
|
5 |
+
|
6 |
+
|
7 |
+
"feature_extractor_name":"ylacombe/dac_44khZ_8kbps",
|
8 |
+
"description_tokenizer_name":"google/flan-t5-base",
|
9 |
+
"prompt_tokenizer_name":"google/flan-t5-base",
|
10 |
+
|
11 |
+
"report_to": ["wandb"],
|
12 |
+
"overwrite_output_dir": true,
|
13 |
+
"output_dir": "./output_dir_training",
|
14 |
+
|
15 |
+
"train_dataset_name": "blabble-io/libritts_r",
|
16 |
+
"train_metadata_dataset_name": "parler-tts/libritts_r_tags_tagged_10k_generated",
|
17 |
+
"train_dataset_config_name": "clean",
|
18 |
+
"train_split_name": "test.clean",
|
19 |
+
|
20 |
+
"eval_dataset_name": "blabble-io/libritts_r",
|
21 |
+
"eval_metadata_dataset_name": "parler-tts/libritts_r_tags_tagged_10k_generated",
|
22 |
+
"eval_dataset_config_name": "clean",
|
23 |
+
"eval_split_name": "test.clean",
|
24 |
+
|
25 |
+
"target_audio_column_name": "audio",
|
26 |
+
"description_column_name": "text_description",
|
27 |
+
"prompt_column_name": "text",
|
28 |
+
|
29 |
+
"max_eval_samples": 48,
|
30 |
+
"max_train_samples": 96,
|
31 |
+
|
32 |
+
"max_duration_in_seconds": 20,
|
33 |
+
"min_duration_in_seconds": 2.0,
|
34 |
+
|
35 |
+
"add_audio_samples_to_wandb": true,
|
36 |
+
"id_column_name": "id",
|
37 |
+
|
38 |
+
"preprocessing_num_workers": 8,
|
39 |
+
|
40 |
+
"do_train": true,
|
41 |
+
"num_train_epochs": 50,
|
42 |
+
"gradient_accumulation_steps": 1,
|
43 |
+
"gradient_checkpointing": false,
|
44 |
+
"per_device_train_batch_size": 4,
|
45 |
+
"learning_rate": 1e-3,
|
46 |
+
"adam_beta1": 0.9,
|
47 |
+
"adam_beta2": 0.99,
|
48 |
+
"weight_decay": 0.01,
|
49 |
+
|
50 |
+
"lr_scheduler_type": "cosine",
|
51 |
+
"warmup_steps": 40,
|
52 |
+
|
53 |
+
|
54 |
+
"logging_steps": 2,
|
55 |
+
"freeze_text_encoder": true,
|
56 |
+
|
57 |
+
|
58 |
+
"do_eval": true,
|
59 |
+
"predict_with_generate": true,
|
60 |
+
"include_inputs_for_metrics": true,
|
61 |
+
"evaluation_strategy": "steps",
|
62 |
+
"eval_steps": 500,
|
63 |
+
"save_steps": 5000,
|
64 |
+
|
65 |
+
"per_device_eval_batch_size": 12,
|
66 |
+
|
67 |
+
"audio_encoder_per_device_batch_size":24,
|
68 |
+
"dtype": "bfloat16",
|
69 |
+
"seed": 456,
|
70 |
+
|
71 |
+
"dataloader_num_workers":8
|
72 |
+
}
|
parler-tts/helpers/training_configs/starting_point_0.01.json
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"model_name_or_path": "./parler-tts-untrained-600M/parler-tts-untrained-600M/",
|
3 |
+
"save_to_disk": "./tmp_dataset_audio/",
|
4 |
+
"temporary_save_to_disk": "./audio_code_tmp/",
|
5 |
+
|
6 |
+
|
7 |
+
"feature_extractor_name":"ylacombe/dac_44khZ_8kbps",
|
8 |
+
"description_tokenizer_name":"google/flan-t5-base",
|
9 |
+
"prompt_tokenizer_name":"google/flan-t5-base",
|
10 |
+
|
11 |
+
"report_to": ["wandb"],
|
12 |
+
"overwrite_output_dir": true,
|
13 |
+
"output_dir": "./output_dir_training",
|
14 |
+
|
15 |
+
"train_dataset_name": "blabble-io/libritts_r+blabble-io/libritts_r+blabble-io/libritts_r+parler-tts/mls_eng_10k",
|
16 |
+
"train_metadata_dataset_name": "parler-tts/libritts_r_tags_tagged_10k_generated+parler-tts/libritts_r_tags_tagged_10k_generated+parler-tts/libritts_r_tags_tagged_10k_generated+parler-tts/mls-eng-10k-tags_tagged_10k_generated",
|
17 |
+
"train_dataset_config_name": "clean+clean+other+default",
|
18 |
+
"train_split_name": "train.clean.360+train.clean.100+train.other.500+train",
|
19 |
+
|
20 |
+
"eval_dataset_name": "blabble-io/libritts_r+parler-tts/mls_eng_10k",
|
21 |
+
"eval_metadata_dataset_name": "parler-tts/libritts_r_tags_tagged_10k_generated+parler-tts/mls-eng-10k-tags_tagged_10k_generated",
|
22 |
+
"eval_dataset_config_name": "other+default",
|
23 |
+
"eval_split_name": "test.other+test",
|
24 |
+
|
25 |
+
"target_audio_column_name": "audio",
|
26 |
+
"description_column_name": "text_description",
|
27 |
+
"prompt_column_name": "text",
|
28 |
+
|
29 |
+
"max_eval_samples": 96,
|
30 |
+
|
31 |
+
"max_duration_in_seconds": 30,
|
32 |
+
"min_duration_in_seconds": 2.0,
|
33 |
+
"max_text_length": 400,
|
34 |
+
|
35 |
+
"group_by_length": true,
|
36 |
+
|
37 |
+
"add_audio_samples_to_wandb": true,
|
38 |
+
"id_column_name": "id",
|
39 |
+
|
40 |
+
"preprocessing_num_workers": 8,
|
41 |
+
|
42 |
+
"do_train": true,
|
43 |
+
"num_train_epochs": 40,
|
44 |
+
"gradient_accumulation_steps": 8,
|
45 |
+
"gradient_checkpointing": false,
|
46 |
+
"per_device_train_batch_size": 3,
|
47 |
+
"learning_rate": 0.00095,
|
48 |
+
"adam_beta1": 0.9,
|
49 |
+
"adam_beta2": 0.99,
|
50 |
+
"weight_decay": 0.01,
|
51 |
+
|
52 |
+
"lr_scheduler_type": "constant_with_warmup",
|
53 |
+
"warmup_steps": 20000,
|
54 |
+
|
55 |
+
|
56 |
+
"logging_steps": 1000,
|
57 |
+
"freeze_text_encoder": true,
|
58 |
+
|
59 |
+
|
60 |
+
"do_eval": true,
|
61 |
+
"predict_with_generate": true,
|
62 |
+
"include_inputs_for_metrics": true,
|
63 |
+
"evaluation_strategy": "steps",
|
64 |
+
"eval_steps": 10000,
|
65 |
+
"save_steps": 10000,
|
66 |
+
|
67 |
+
"per_device_eval_batch_size": 12,
|
68 |
+
|
69 |
+
"audio_encoder_per_device_batch_size":20,
|
70 |
+
"dtype": "bfloat16",
|
71 |
+
"seed": 456,
|
72 |
+
|
73 |
+
"dataloader_num_workers":8
|
74 |
+
}
|
parler-tts/helpers/training_configs/starting_point_v1.json
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"model_name_or_path": "./parler-tts-untrained-600M/parler-tts-untrained-600M/",
|
3 |
+
"save_to_disk": "./tmp_dataset_audio/",
|
4 |
+
"temporary_save_to_disk": "./audio_code_tmp/",
|
5 |
+
"wandb_project": "parler-tts-50k-hours",
|
6 |
+
"wandb_run_name": "Mini",
|
7 |
+
|
8 |
+
"feature_extractor_name":"ylacombe/dac_44khZ_8kbps",
|
9 |
+
"description_tokenizer_name":"google/flan-t5-large",
|
10 |
+
"prompt_tokenizer_name":"google/flan-t5-large",
|
11 |
+
|
12 |
+
"report_to": ["wandb"],
|
13 |
+
"overwrite_output_dir": true,
|
14 |
+
"output_dir": "./output_dir_training",
|
15 |
+
|
16 |
+
"train_dataset_name": "ylacombe/libritts_r_filtered+ylacombe/libritts_r_filtered+ylacombe/libritts_r_filtered+parler-tts/mls_eng",
|
17 |
+
"train_metadata_dataset_name": "ylacombe/libritts-r-filtered-descriptions-10k-v5-without-accents+ylacombe/libritts-r-filtered-descriptions-10k-v5-without-accents+ylacombe/libritts-r-filtered-descriptions-10k-v5-without-accents+ylacombe/mls-eng-descriptions-v4",
|
18 |
+
"train_dataset_config_name": "clean+clean+other+default",
|
19 |
+
"train_split_name": "train.clean.360+train.clean.100+train.other.500+train",
|
20 |
+
|
21 |
+
"eval_dataset_name": "ylacombe/libritts_r_filtered+parler-tts/mls_eng",
|
22 |
+
"eval_metadata_dataset_name": "ylacombe/libritts-r-filtered-descriptions-10k-v5-without-accents+ylacombe/mls-eng-descriptions-v4",
|
23 |
+
"eval_dataset_config_name": "other+default",
|
24 |
+
"eval_split_name": "test.other+test",
|
25 |
+
|
26 |
+
"target_audio_column_name": "audio",
|
27 |
+
"description_column_name": "text_description",
|
28 |
+
"prompt_column_name": "text",
|
29 |
+
|
30 |
+
"max_eval_samples": 96,
|
31 |
+
|
32 |
+
"max_duration_in_seconds": 30,
|
33 |
+
"min_duration_in_seconds": 2.0,
|
34 |
+
"max_text_length": 600,
|
35 |
+
|
36 |
+
"group_by_length": true,
|
37 |
+
|
38 |
+
"add_audio_samples_to_wandb": true,
|
39 |
+
"id_column_name": "id",
|
40 |
+
|
41 |
+
"preprocessing_num_workers": 8,
|
42 |
+
|
43 |
+
"do_train": true,
|
44 |
+
"num_train_epochs": 4,
|
45 |
+
"gradient_accumulation_steps": 4,
|
46 |
+
"gradient_checkpointing": false,
|
47 |
+
"per_device_train_batch_size": 6,
|
48 |
+
"learning_rate": 0.00095,
|
49 |
+
"adam_beta1": 0.9,
|
50 |
+
"adam_beta2": 0.99,
|
51 |
+
"weight_decay": 0.01,
|
52 |
+
|
53 |
+
"lr_scheduler_type": "constant_with_warmup",
|
54 |
+
"warmup_steps": 20000,
|
55 |
+
|
56 |
+
|
57 |
+
"logging_steps": 1000,
|
58 |
+
"freeze_text_encoder": true,
|
59 |
+
|
60 |
+
|
61 |
+
"do_eval": true,
|
62 |
+
"predict_with_generate": true,
|
63 |
+
"include_inputs_for_metrics": true,
|
64 |
+
"evaluation_strategy": "steps",
|
65 |
+
"eval_steps": 10000,
|
66 |
+
"save_steps": 10000,
|
67 |
+
|
68 |
+
"per_device_eval_batch_size": 4,
|
69 |
+
|
70 |
+
"audio_encoder_per_device_batch_size":24,
|
71 |
+
"dtype": "bfloat16",
|
72 |
+
"seed": 456,
|
73 |
+
|
74 |
+
"dataloader_num_workers":8,
|
75 |
+
"attn_implementation": "sdpa"
|
76 |
+
}
|
parler-tts/helpers/training_configs/starting_point_v1_large.json
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"model_name_or_path": "./parler-tts-untrained-large/parler-tts-untrained-large",
|
3 |
+
"save_to_disk": "./tmp_dataset_audio/",
|
4 |
+
"temporary_save_to_disk": "./audio_code_tmp/",
|
5 |
+
"wandb_project": "parler-tts-50k-hours",
|
6 |
+
"wandb_run_name": "Large",
|
7 |
+
|
8 |
+
"feature_extractor_name":"ylacombe/dac_44khZ_8kbps",
|
9 |
+
"description_tokenizer_name":"google/flan-t5-large",
|
10 |
+
"prompt_tokenizer_name":"google/flan-t5-large",
|
11 |
+
|
12 |
+
"report_to": ["wandb"],
|
13 |
+
"overwrite_output_dir": true,
|
14 |
+
"output_dir": "./output_dir_training",
|
15 |
+
|
16 |
+
"train_dataset_name": "ylacombe/libritts_r_filtered+ylacombe/libritts_r_filtered+ylacombe/libritts_r_filtered+parler-tts/mls_eng",
|
17 |
+
"train_metadata_dataset_name": "ylacombe/libritts-r-filtered-descriptions-10k-v5-without-accents+ylacombe/libritts-r-filtered-descriptions-10k-v5-without-accents+ylacombe/libritts-r-filtered-descriptions-10k-v5-without-accents+ylacombe/mls-eng-descriptions-v4",
|
18 |
+
"train_dataset_config_name": "clean+clean+other+default",
|
19 |
+
"train_split_name": "train.clean.360+train.clean.100+train.other.500+train",
|
20 |
+
|
21 |
+
"eval_dataset_name": "ylacombe/libritts_r_filtered+parler-tts/mls_eng",
|
22 |
+
"eval_metadata_dataset_name": "ylacombe/libritts-r-filtered-descriptions-10k-v5-without-accents+ylacombe/mls-eng-descriptions-v4",
|
23 |
+
"eval_dataset_config_name": "other+default",
|
24 |
+
"eval_split_name": "test.other+test",
|
25 |
+
|
26 |
+
"target_audio_column_name": "audio",
|
27 |
+
"description_column_name": "text_description",
|
28 |
+
"prompt_column_name": "text",
|
29 |
+
|
30 |
+
"max_eval_samples": 96,
|
31 |
+
|
32 |
+
"max_duration_in_seconds": 30,
|
33 |
+
"min_duration_in_seconds": 2.0,
|
34 |
+
"max_text_length": 600,
|
35 |
+
|
36 |
+
"group_by_length": true,
|
37 |
+
|
38 |
+
"add_audio_samples_to_wandb": true,
|
39 |
+
"id_column_name": "id",
|
40 |
+
|
41 |
+
"preprocessing_num_workers": 8,
|
42 |
+
|
43 |
+
"do_train": true,
|
44 |
+
"num_train_epochs": 4,
|
45 |
+
"gradient_accumulation_steps": 4,
|
46 |
+
"gradient_checkpointing": false,
|
47 |
+
"per_device_train_batch_size": 3,
|
48 |
+
"learning_rate": 0.0015,
|
49 |
+
"adam_beta1": 0.9,
|
50 |
+
"adam_beta2": 0.99,
|
51 |
+
"weight_decay": 0.01,
|
52 |
+
|
53 |
+
"lr_scheduler_type": "constant_with_warmup",
|
54 |
+
"warmup_steps": 10000,
|
55 |
+
|
56 |
+
|
57 |
+
"logging_steps": 1000,
|
58 |
+
"freeze_text_encoder": true,
|
59 |
+
|
60 |
+
|
61 |
+
"do_eval": true,
|
62 |
+
"predict_with_generate": true,
|
63 |
+
"include_inputs_for_metrics": true,
|
64 |
+
"evaluation_strategy": "steps",
|
65 |
+
"eval_steps": 10000,
|
66 |
+
"save_steps": 10000,
|
67 |
+
"save_total_limit": 10,
|
68 |
+
|
69 |
+
"per_device_eval_batch_size": 6,
|
70 |
+
|
71 |
+
"audio_encoder_per_device_batch_size":24,
|
72 |
+
"dtype": "bfloat16",
|
73 |
+
"seed": 738,
|
74 |
+
|
75 |
+
"dataloader_num_workers":8,
|
76 |
+
"attn_implementation": "sdpa"
|
77 |
+
}
|
parler-tts/parler_tts/__init__.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__version__ = "0.2.2"
|
2 |
+
|
3 |
+
|
4 |
+
from transformers import AutoConfig, AutoModel
|
5 |
+
|
6 |
+
from .configuration_parler_tts import ParlerTTSConfig, ParlerTTSDecoderConfig
|
7 |
+
from .dac_wrapper import DACConfig, DACModel
|
8 |
+
from .modeling_parler_tts import (
|
9 |
+
ParlerTTSForCausalLM,
|
10 |
+
ParlerTTSForConditionalGeneration,
|
11 |
+
apply_delay_pattern_mask,
|
12 |
+
build_delay_pattern_mask,
|
13 |
+
)
|
14 |
+
|
15 |
+
from .streamer import ParlerTTSStreamer
|
16 |
+
|
17 |
+
from importlib.metadata import version
|
18 |
+
from packaging.version import Version
|
19 |
+
|
20 |
+
if Version(version("transformers"))<= Version("4.44.2dev"):
|
21 |
+
AutoConfig.register("dac", DACConfig)
|
22 |
+
else:
|
23 |
+
AutoConfig.register("dac_on_the_hub", DACConfig)
|
24 |
+
|
25 |
+
AutoModel.register(DACConfig, DACModel)
|
parler-tts/parler_tts/configuration_parler_tts.py
ADDED
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
""" Parler-TTS model configuration"""
|
16 |
+
|
17 |
+
from transformers import AutoConfig, logging
|
18 |
+
from transformers.configuration_utils import PretrainedConfig
|
19 |
+
|
20 |
+
from importlib.metadata import version
|
21 |
+
from packaging.version import Version
|
22 |
+
|
23 |
+
use_dac_on_the_hub = Version(version("transformers")) > Version("4.44.2dev")
|
24 |
+
|
25 |
+
logger = logging.get_logger(__name__)
|
26 |
+
|
27 |
+
PARLER_TTS_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
28 |
+
"parler-tts/parler-tts-mini-v1": "https://huggingface.co/parler-tts/parler-tts-mini-v1/resolve/main/config.json",
|
29 |
+
# See all ParlerTTS models at https://huggingface.co/models?filter=parler_tts
|
30 |
+
}
|
31 |
+
|
32 |
+
|
33 |
+
class ParlerTTSDecoderConfig(PretrainedConfig):
|
34 |
+
r"""
|
35 |
+
This is the configuration class to store the configuration of an [`ParlerTTSDecoder`]. It is used to instantiate a
|
36 |
+
Parler-TTS decoder according to the specified arguments, defining the model architecture. Instantiating a
|
37 |
+
configuration with the defaults will yield a similar configuration to that of the Parler-TTS
|
38 |
+
[parler-tts/parler-tts-mini-v1](https://huggingface.co/parler-tts/parler-tts-mini-v1) architecture.
|
39 |
+
|
40 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
41 |
+
documentation from [`PretrainedConfig`] for more information.
|
42 |
+
|
43 |
+
|
44 |
+
Args:
|
45 |
+
vocab_size (`int`, *optional*, defaults to 2049):
|
46 |
+
Vocabulary size of the ParlerTTSDecoder model. Defines the number of different tokens that can be
|
47 |
+
represented by the `inputs_ids` passed when calling [`ParlerTTSDecoder`].
|
48 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
49 |
+
Dimensionality of the layers and the pooler layer.
|
50 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
51 |
+
Number of decoder layers.
|
52 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
53 |
+
Number of attention heads for each attention layer in the Transformer block.
|
54 |
+
num_key_value_heads (`int`, *optional*):
|
55 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
56 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
57 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
58 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
59 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
60 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
61 |
+
`num_attention_heads`.
|
62 |
+
num_cross_attention_key_value_heads (`int`, *optional*):
|
63 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention in the cross-attention layers.
|
64 |
+
If it is not specified, will default to `num_key_value_heads`.
|
65 |
+
ffn_dim (`int`, *optional*, defaults to 4096):
|
66 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer block.
|
67 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
68 |
+
The non-linear activation function (function or string) in the decoder and pooler. If string, `"gelu"`,
|
69 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
70 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
71 |
+
The dropout probability for all fully connected layers in the embeddings, text_encoder, and pooler.
|
72 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
73 |
+
The dropout ratio for the attention probabilities.
|
74 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
75 |
+
The dropout ratio for activations inside the fully connected layer.
|
76 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
77 |
+
The maximum sequence length that this model might ever be used with. Typically, set this to something large
|
78 |
+
just in case (e.g., 512 or 1024 or 2048).
|
79 |
+
initializer_factor (`float`, *optional*, defaults to 0.02):
|
80 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
81 |
+
layerdrop (`float`, *optional*, defaults to 0.0):
|
82 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
83 |
+
for more details.
|
84 |
+
scale_embedding (`bool`, *optional*, defaults to `False`):
|
85 |
+
Scale embeddings by diving by sqrt(hidden_size).
|
86 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
87 |
+
Whether the model should return the last key/values attentions (not used by all models)
|
88 |
+
num_codebooks (`int`, *optional*, defaults to 4):
|
89 |
+
The number of parallel codebooks forwarded to the model.
|
90 |
+
tie_word_embeddings(`bool`, *optional*, defaults to `False`):
|
91 |
+
Whether input and output word embeddings should be tied.
|
92 |
+
rope_embeddings (`bool`, *optional*, defaults to `False`):
|
93 |
+
Whether to use ROPE or absolute positional embeddings.
|
94 |
+
rope_theta (`float`, *optional*, defaults to 100000.0):
|
95 |
+
The base period of the RoPE embeddings.
|
96 |
+
cross_attention_implementation_strategy (`str`, *optional*):
|
97 |
+
If not specified, the cross-attention implementation will be the same as `_attn_implementation`. If `always_eager`, it will always be the eager implementation. If `always_sdpa`, it will always be the sdpa implementation.
|
98 |
+
use_fused_lm_heads(`bool`, *optional*, defaults to `False`):
|
99 |
+
Whether to fuse audio LM heads instead of applying them sequentially.
|
100 |
+
codebook_weights(`List[int]`, *optional*):
|
101 |
+
Weights applied to each codebook when computing the loss.
|
102 |
+
"""
|
103 |
+
|
104 |
+
model_type = "parler_tts_decoder"
|
105 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
106 |
+
|
107 |
+
def __init__(
|
108 |
+
self,
|
109 |
+
vocab_size=2049, # vocab size = 2048 (encodec vocab size) + 1 (eos)
|
110 |
+
max_position_embeddings=2048,
|
111 |
+
num_hidden_layers=24,
|
112 |
+
ffn_dim=4096,
|
113 |
+
num_attention_heads=16,
|
114 |
+
num_key_value_heads=None,
|
115 |
+
num_cross_attention_key_value_heads=None,
|
116 |
+
layerdrop=0.0,
|
117 |
+
use_cache=True,
|
118 |
+
activation_function="gelu",
|
119 |
+
hidden_size=1024,
|
120 |
+
dropout=0.1,
|
121 |
+
attention_dropout=0.0,
|
122 |
+
activation_dropout=0.0,
|
123 |
+
initializer_factor=0.02,
|
124 |
+
scale_embedding=False,
|
125 |
+
num_codebooks=4,
|
126 |
+
pad_token_id=2048,
|
127 |
+
bos_token_id=2049,
|
128 |
+
eos_token_id=2048,
|
129 |
+
tie_word_embeddings=False,
|
130 |
+
rope_embeddings=False,
|
131 |
+
rope_theta=10_000.0,
|
132 |
+
cross_attention_implementation_strategy=None,
|
133 |
+
use_fused_lm_heads=False,
|
134 |
+
codebook_weights=None,
|
135 |
+
**kwargs,
|
136 |
+
):
|
137 |
+
self.vocab_size = vocab_size
|
138 |
+
self.max_position_embeddings = max_position_embeddings
|
139 |
+
self.hidden_size = hidden_size
|
140 |
+
self.ffn_dim = ffn_dim
|
141 |
+
self.num_hidden_layers = num_hidden_layers
|
142 |
+
self.num_attention_heads = num_attention_heads
|
143 |
+
if num_key_value_heads is None:
|
144 |
+
num_key_value_heads = num_attention_heads
|
145 |
+
self.num_key_value_heads = num_key_value_heads
|
146 |
+
if num_cross_attention_key_value_heads is None:
|
147 |
+
num_cross_attention_key_value_heads = num_key_value_heads
|
148 |
+
self.num_cross_attention_key_value_heads = num_cross_attention_key_value_heads
|
149 |
+
self.dropout = dropout
|
150 |
+
self.attention_dropout = attention_dropout
|
151 |
+
self.activation_dropout = activation_dropout
|
152 |
+
self.activation_function = activation_function
|
153 |
+
self.initializer_factor = initializer_factor
|
154 |
+
self.layerdrop = layerdrop
|
155 |
+
self.use_cache = use_cache
|
156 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
157 |
+
self.num_codebooks = num_codebooks
|
158 |
+
self.rope_embeddings = rope_embeddings
|
159 |
+
self.rope_theta = rope_theta
|
160 |
+
self.cross_attention_implementation_strategy = cross_attention_implementation_strategy
|
161 |
+
self.use_fused_lm_heads = use_fused_lm_heads
|
162 |
+
self.codebook_weights = codebook_weights
|
163 |
+
|
164 |
+
if codebook_weights is not None and len(codebook_weights) != num_codebooks:
|
165 |
+
raise ValueError(f"`codebook_weights` has length {len(codebook_weights)} when it should be of length {num_codebooks}.")
|
166 |
+
super().__init__(
|
167 |
+
pad_token_id=pad_token_id,
|
168 |
+
bos_token_id=bos_token_id,
|
169 |
+
eos_token_id=eos_token_id,
|
170 |
+
tie_word_embeddings=tie_word_embeddings,
|
171 |
+
**kwargs,
|
172 |
+
)
|
173 |
+
|
174 |
+
|
175 |
+
class ParlerTTSConfig(PretrainedConfig):
|
176 |
+
r"""
|
177 |
+
This is the configuration class to store the configuration of a [`ParlerTTSModel`]. It is used to instantiate a
|
178 |
+
Parler-TTS model according to the specified arguments, defining the text encoder, audio encoder and Parler-TTS decoder
|
179 |
+
configs.
|
180 |
+
|
181 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
182 |
+
documentation from [`PretrainedConfig`] for more information.
|
183 |
+
|
184 |
+
Args:
|
185 |
+
vocab_size (`int`, *optional*, defaults to 1024):
|
186 |
+
Vocabulary size of the prompt token ids. Defines the number of different tokens that can be
|
187 |
+
represented by the `prompt_inputs_ids`.
|
188 |
+
prompt_cross_attention (`bool`, *optional*, defaults to `False`):
|
189 |
+
Whether to use cross-attention conditioning for the prompt (as well as the description).
|
190 |
+
kwargs (*optional*):
|
191 |
+
Dictionary of keyword arguments. Notably:
|
192 |
+
|
193 |
+
- **text_encoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that
|
194 |
+
defines the text encoder config.
|
195 |
+
- **audio_encoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that
|
196 |
+
defines the audio encoder config.
|
197 |
+
- **decoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
|
198 |
+
the decoder config.
|
199 |
+
|
200 |
+
Example:
|
201 |
+
|
202 |
+
```python
|
203 |
+
>>> from transformers import (
|
204 |
+
... ParlerTTSConfig,
|
205 |
+
... ParlerTTSDecoderConfig,
|
206 |
+
... T5Config,
|
207 |
+
... EncodecConfig,
|
208 |
+
... ParlerTTSForConditionalGeneration,
|
209 |
+
... )
|
210 |
+
|
211 |
+
>>> # Initializing text encoder, audio encoder, and decoder model configurations
|
212 |
+
>>> text_encoder_config = T5Config()
|
213 |
+
>>> audio_encoder_config = EncodecConfig()
|
214 |
+
>>> decoder_config = ParlerTTSDecoderConfig()
|
215 |
+
|
216 |
+
>>> configuration = ParlerTTSConfig.from_sub_models_config(
|
217 |
+
... text_encoder_config, audio_encoder_config, decoder_config
|
218 |
+
... )
|
219 |
+
|
220 |
+
>>> # Initializing a ParlerTTSForConditionalGeneration (with random weights) from the parler-tts/parler-tts-mini-v1 style configuration
|
221 |
+
>>> model = ParlerTTSForConditionalGeneration(configuration)
|
222 |
+
|
223 |
+
>>> # Accessing the model configuration
|
224 |
+
>>> configuration = model.config
|
225 |
+
>>> config_text_encoder = model.config.text_encoder
|
226 |
+
>>> config_audio_encoder = model.config.audio_encoder
|
227 |
+
>>> config_decoder = model.config.decoder
|
228 |
+
|
229 |
+
>>> # Saving the model, including its configuration
|
230 |
+
>>> model.save_pretrained("parler_tts-model")
|
231 |
+
|
232 |
+
>>> # loading model and config from pretrained folder
|
233 |
+
>>> parler_tts_config = ParlerTTSConfig.from_pretrained("parler_tts-model")
|
234 |
+
>>> model = ParlerTTSForConditionalGeneration.from_pretrained("parler_tts-model", config=parler_tts_config)
|
235 |
+
```"""
|
236 |
+
|
237 |
+
model_type = "parler_tts"
|
238 |
+
is_composition = True
|
239 |
+
|
240 |
+
def __init__(self, vocab_size=1024, prompt_cross_attention=False, **kwargs):
|
241 |
+
super().__init__(**kwargs)
|
242 |
+
if "text_encoder" not in kwargs or "audio_encoder" not in kwargs or "decoder" not in kwargs:
|
243 |
+
raise ValueError("Config has to be initialized with text_encoder, audio_encoder and decoder config")
|
244 |
+
|
245 |
+
text_encoder_config = kwargs.pop("text_encoder")
|
246 |
+
text_encoder_model_type = text_encoder_config.pop("model_type")
|
247 |
+
|
248 |
+
audio_encoder_config = kwargs.pop("audio_encoder")
|
249 |
+
audio_encoder_model_type = audio_encoder_config.pop("model_type")
|
250 |
+
|
251 |
+
model_version = kwargs.get("transformers_version", None)
|
252 |
+
if model_version is not None and Version(model_version) <= Version("4.44.2dev") and use_dac_on_the_hub and audio_encoder_model_type=="dac":
|
253 |
+
# here we have to manually change model type if DAC based on transformers version
|
254 |
+
audio_encoder_model_type = "dac_on_the_hub"
|
255 |
+
|
256 |
+
decoder_config = kwargs.pop("decoder")
|
257 |
+
|
258 |
+
self.vocab_size = vocab_size
|
259 |
+
self.prompt_cross_attention = prompt_cross_attention
|
260 |
+
self.text_encoder = AutoConfig.for_model(text_encoder_model_type, **text_encoder_config)
|
261 |
+
self.audio_encoder = AutoConfig.for_model(audio_encoder_model_type, **audio_encoder_config)
|
262 |
+
self.decoder = ParlerTTSDecoderConfig(**decoder_config)
|
263 |
+
self.is_encoder_decoder = True
|
264 |
+
|
265 |
+
@classmethod
|
266 |
+
def from_sub_models_config(
|
267 |
+
cls,
|
268 |
+
text_encoder_config: PretrainedConfig,
|
269 |
+
audio_encoder_config: PretrainedConfig,
|
270 |
+
decoder_config: ParlerTTSDecoderConfig,
|
271 |
+
**kwargs,
|
272 |
+
):
|
273 |
+
r"""
|
274 |
+
Instantiate a [`ParlerTTSConfig`] (or a derived class) from text encoder, audio encoder and decoder
|
275 |
+
configurations.
|
276 |
+
|
277 |
+
Returns:
|
278 |
+
[`ParlerTTSConfig`]: An instance of a configuration object
|
279 |
+
"""
|
280 |
+
|
281 |
+
return cls(
|
282 |
+
text_encoder=text_encoder_config.to_dict(),
|
283 |
+
audio_encoder=audio_encoder_config.to_dict(),
|
284 |
+
decoder=decoder_config.to_dict(),
|
285 |
+
**kwargs,
|
286 |
+
)
|
287 |
+
|
288 |
+
@property
|
289 |
+
# This is a property because you might want to change the codec model on the fly
|
290 |
+
def sampling_rate(self):
|
291 |
+
return self.audio_encoder.sampling_rate
|
parler-tts/parler_tts/dac_wrapper/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from .configuration_dac import DACConfig
|
2 |
+
from .modeling_dac import DACModel
|
parler-tts/parler_tts/dac_wrapper/configuration_dac.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from transformers import PretrainedConfig
|
3 |
+
from importlib.metadata import version
|
4 |
+
from packaging.version import Version
|
5 |
+
|
6 |
+
|
7 |
+
class DACConfig(PretrainedConfig):
|
8 |
+
model_type = "dac" if Version(version("transformers"))<= Version("4.44.2dev") else "dac_on_the_hub"
|
9 |
+
|
10 |
+
def __init__(
|
11 |
+
self,
|
12 |
+
num_codebooks: int = 9,
|
13 |
+
model_bitrate: int = 8, # kbps
|
14 |
+
codebook_size: int = 1024,
|
15 |
+
latent_dim: int = 1024,
|
16 |
+
frame_rate: int = 86,
|
17 |
+
sampling_rate: int = 44100,
|
18 |
+
**kwargs,
|
19 |
+
):
|
20 |
+
self.codebook_size = codebook_size
|
21 |
+
self.model_bitrate = model_bitrate
|
22 |
+
self.latent_dim = latent_dim
|
23 |
+
self.num_codebooks = num_codebooks
|
24 |
+
self.frame_rate = frame_rate
|
25 |
+
self.sampling_rate = sampling_rate
|
26 |
+
|
27 |
+
super().__init__(**kwargs)
|
parler-tts/parler_tts/dac_wrapper/modeling_dac.py
ADDED
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from dac.model import DAC
|
3 |
+
from torch import nn
|
4 |
+
|
5 |
+
from transformers import PreTrainedModel
|
6 |
+
from transformers.models.encodec.modeling_encodec import EncodecDecoderOutput, EncodecEncoderOutput
|
7 |
+
|
8 |
+
from .configuration_dac import DACConfig
|
9 |
+
|
10 |
+
|
11 |
+
# model doesn't support batching yet
|
12 |
+
|
13 |
+
|
14 |
+
class DACModel(PreTrainedModel):
|
15 |
+
config_class = DACConfig
|
16 |
+
main_input_name = "input_values"
|
17 |
+
|
18 |
+
# Set main input to 'input_values' for voice steering
|
19 |
+
main_input_name = "input_values"
|
20 |
+
|
21 |
+
def __init__(self, config):
|
22 |
+
super().__init__(config)
|
23 |
+
|
24 |
+
self.model = DAC(
|
25 |
+
n_codebooks=config.num_codebooks,
|
26 |
+
latent_dim=config.latent_dim,
|
27 |
+
codebook_size=config.codebook_size,
|
28 |
+
)
|
29 |
+
|
30 |
+
self.remove_weight_norm()
|
31 |
+
self.apply_weight_norm()
|
32 |
+
|
33 |
+
def encode(
|
34 |
+
self, input_values, padding_mask=None, bandwidth=None, return_dict=None, n_quantizers=None, sample_rate=None
|
35 |
+
):
|
36 |
+
"""
|
37 |
+
Encodes the input audio waveform into discrete codes.
|
38 |
+
|
39 |
+
Args:
|
40 |
+
input_values (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
|
41 |
+
Float values of the input audio waveform.
|
42 |
+
padding_mask (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
|
43 |
+
Padding mask used to pad the `input_values`.
|
44 |
+
bandwidth (`float`, *optional*):
|
45 |
+
Not used, kept to have the same inferface as HF encodec.
|
46 |
+
n_quantizers (`int`, *optional*) :
|
47 |
+
Number of quantizers to use, by default None
|
48 |
+
If None, all quantizers are used.
|
49 |
+
sample_rate (`int`, *optional*) :
|
50 |
+
Signal sampling_rate
|
51 |
+
|
52 |
+
Returns:
|
53 |
+
A list of frames containing the discrete encoded codes for the input audio waveform, along with rescaling
|
54 |
+
factors for each chunk when `normalize` is True. Each frames is a tuple `(codebook, scale)`, with
|
55 |
+
`codebook` of shape `[batch_size, num_codebooks, frames]`.
|
56 |
+
Scale is not used here.
|
57 |
+
|
58 |
+
"""
|
59 |
+
_, channels, input_length = input_values.shape
|
60 |
+
|
61 |
+
if channels < 1 or channels > 2:
|
62 |
+
raise ValueError(f"Number of audio channels must be 1 or 2, but got {channels}")
|
63 |
+
|
64 |
+
audio_data = self.model.preprocess(input_values, sample_rate)
|
65 |
+
|
66 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
67 |
+
|
68 |
+
# TODO: for now, no chunk length
|
69 |
+
|
70 |
+
chunk_length = None # self.config.chunk_length
|
71 |
+
if chunk_length is None:
|
72 |
+
chunk_length = input_length
|
73 |
+
stride = input_length
|
74 |
+
else:
|
75 |
+
stride = self.config.chunk_stride
|
76 |
+
|
77 |
+
if padding_mask is None:
|
78 |
+
padding_mask = torch.ones_like(input_values).bool()
|
79 |
+
|
80 |
+
encoded_frames = []
|
81 |
+
scales = []
|
82 |
+
|
83 |
+
step = chunk_length - stride
|
84 |
+
if (input_length % stride) - step != 0:
|
85 |
+
raise ValueError(
|
86 |
+
"The input length is not properly padded for batched chunked decoding. Make sure to pad the input correctly."
|
87 |
+
)
|
88 |
+
|
89 |
+
for offset in range(0, input_length - step, stride):
|
90 |
+
mask = padding_mask[..., offset : offset + chunk_length].bool()
|
91 |
+
frame = audio_data[:, :, offset : offset + chunk_length]
|
92 |
+
|
93 |
+
scale = None
|
94 |
+
|
95 |
+
_, encoded_frame, _, _, _ = self.model.encode(frame, n_quantizers=n_quantizers)
|
96 |
+
encoded_frames.append(encoded_frame)
|
97 |
+
scales.append(scale)
|
98 |
+
|
99 |
+
encoded_frames = torch.stack(encoded_frames)
|
100 |
+
|
101 |
+
if not return_dict:
|
102 |
+
return (encoded_frames, scales)
|
103 |
+
|
104 |
+
return EncodecEncoderOutput(encoded_frames, scales)
|
105 |
+
|
106 |
+
def decode(
|
107 |
+
self,
|
108 |
+
audio_codes,
|
109 |
+
audio_scales,
|
110 |
+
padding_mask=None,
|
111 |
+
return_dict=None,
|
112 |
+
):
|
113 |
+
"""
|
114 |
+
Decodes the given frames into an output audio waveform.
|
115 |
+
|
116 |
+
Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be
|
117 |
+
trimmed.
|
118 |
+
|
119 |
+
Args:
|
120 |
+
audio_codes (`torch.FloatTensor` of shape `(batch_size, nb_chunks, chunk_length)`, *optional*):
|
121 |
+
Discret code embeddings computed using `model.encode`.
|
122 |
+
audio_scales (`torch.Tensor` of shape `(batch_size, nb_chunks)`, *optional*):
|
123 |
+
Not used, kept to have the same inferface as HF encodec.
|
124 |
+
padding_mask (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
|
125 |
+
Padding mask used to pad the `input_values`.
|
126 |
+
Not used yet, kept to have the same inferface as HF encodec.
|
127 |
+
return_dict (`bool`, *optional*):
|
128 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
129 |
+
|
130 |
+
"""
|
131 |
+
return_dict = return_dict or self.config.return_dict
|
132 |
+
|
133 |
+
# TODO: for now, no chunk length
|
134 |
+
|
135 |
+
if len(audio_codes) != 1:
|
136 |
+
raise ValueError(f"Expected one frame, got {len(audio_codes)}")
|
137 |
+
|
138 |
+
audio_values = self.model.quantizer.from_codes(audio_codes.squeeze(0))[0]
|
139 |
+
audio_values = self.model.decode(audio_values)
|
140 |
+
if not return_dict:
|
141 |
+
return (audio_values,)
|
142 |
+
return EncodecDecoderOutput(audio_values)
|
143 |
+
|
144 |
+
def forward(self, tensor):
|
145 |
+
raise ValueError("`DACModel.forward` not implemented yet")
|
146 |
+
|
147 |
+
|
148 |
+
def apply_weight_norm(self):
|
149 |
+
weight_norm = nn.utils.weight_norm
|
150 |
+
if hasattr(nn.utils.parametrizations, "weight_norm"):
|
151 |
+
weight_norm = nn.utils.parametrizations.weight_norm
|
152 |
+
|
153 |
+
def _apply_weight_norm(module):
|
154 |
+
if isinstance(module, nn.Conv1d) or isinstance(module, nn.ConvTranspose1d):
|
155 |
+
weight_norm(module)
|
156 |
+
|
157 |
+
self.apply(_apply_weight_norm)
|
158 |
+
|
159 |
+
|
160 |
+
def remove_weight_norm(self):
|
161 |
+
def _remove_weight_norm(module):
|
162 |
+
if isinstance(module, nn.Conv1d) or isinstance(module, nn.ConvTranspose1d):
|
163 |
+
nn.utils.remove_weight_norm(module)
|
164 |
+
self.apply(_remove_weight_norm)
|
parler-tts/parler_tts/logits_processors.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import LogitsProcessor, LogitsProcessorList
|
2 |
+
from transformers.pytorch_utils import isin_mps_friendly
|
3 |
+
import math
|
4 |
+
import torch
|
5 |
+
|
6 |
+
class ParlerTTSLogitsProcessor(LogitsProcessor):
|
7 |
+
r"""This processor ensures that the delayed pattern mask constraints are respected.
|
8 |
+
|
9 |
+
<Tip warning={true}>
|
10 |
+
|
11 |
+
This logits processor is exclusively compatible with Parler-TTS.
|
12 |
+
See the model documentation for examples.
|
13 |
+
|
14 |
+
</Tip>
|
15 |
+
|
16 |
+
Args:
|
17 |
+
eos_token_id (`Union[int, List[int], torch.Tensor]`):
|
18 |
+
The id(s) of the *end-of-sequence* token.
|
19 |
+
min_eos_p (`float`, *optional*):
|
20 |
+
Minimum end of speech threshold.
|
21 |
+
"""
|
22 |
+
|
23 |
+
def __init__(self, eos_token_id, num_codebooks: int, batch_size: int, device: str = "cpu"):
|
24 |
+
if not isinstance(eos_token_id, torch.Tensor):
|
25 |
+
if isinstance(eos_token_id, int):
|
26 |
+
eos_token_id = [eos_token_id]
|
27 |
+
eos_token_id = torch.tensor(eos_token_id, device=device)
|
28 |
+
self.eos_token_id = eos_token_id
|
29 |
+
self.batch_size = batch_size
|
30 |
+
|
31 |
+
if torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any():
|
32 |
+
raise ValueError(f"`eos_token_id` has to be a list of positive integers, but is {eos_token_id}")
|
33 |
+
|
34 |
+
self.num_codebooks = num_codebooks
|
35 |
+
self.device = device
|
36 |
+
|
37 |
+
|
38 |
+
self.codebook_idx = torch.arange(self.batch_size*self.num_codebooks, device=self.device)
|
39 |
+
self.first_codebooks_unfinished = torch.arange(batch_size, device=device)*num_codebooks
|
40 |
+
|
41 |
+
max_codebooks = torch.arange(self.batch_size, device=self.device)*self.num_codebooks + self.num_codebooks -1
|
42 |
+
self.max_codebooks = max_codebooks
|
43 |
+
|
44 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
45 |
+
|
46 |
+
is_eos = isin_mps_friendly(input_ids, self.eos_token_id).sum(1)
|
47 |
+
|
48 |
+
self.first_codebooks_unfinished = torch.where((is_eos[self.first_codebooks_unfinished]>0) & (self.first_codebooks_unfinished<self.max_codebooks), self.first_codebooks_unfinished+1, self.first_codebooks_unfinished)
|
49 |
+
|
50 |
+
# every codebook higher than the first one unfinished will never be eos
|
51 |
+
eos_token_mask = self.codebook_idx > self.first_codebooks_unfinished.repeat_interleave(self.num_codebooks)
|
52 |
+
scores[eos_token_mask, self.eos_token_id] = -math.inf
|
53 |
+
|
54 |
+
return scores
|
parler-tts/parler_tts/modeling_parler_tts.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
parler-tts/parler_tts/streamer.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from .modeling_parler_tts import ParlerTTSForConditionalGeneration
|
3 |
+
from transformers.generation.streamers import BaseStreamer
|
4 |
+
from typing import Optional
|
5 |
+
import torch
|
6 |
+
import numpy as np
|
7 |
+
import math
|
8 |
+
from queue import Queue
|
9 |
+
|
10 |
+
|
11 |
+
class ParlerTTSStreamer(BaseStreamer):
|
12 |
+
def __init__(
|
13 |
+
self,
|
14 |
+
model: ParlerTTSForConditionalGeneration,
|
15 |
+
device: Optional[str] = None,
|
16 |
+
play_steps: Optional[int] = 10,
|
17 |
+
stride: Optional[int] = None,
|
18 |
+
timeout: Optional[float] = None,
|
19 |
+
):
|
20 |
+
"""
|
21 |
+
Streamer that stores playback-ready audio in a queue, to be used by a downstream application as an iterator. This is
|
22 |
+
useful for applications that benefit from accessing the generated audio in a non-blocking way (e.g. in an interactive
|
23 |
+
Gradio demo).
|
24 |
+
Parameters:
|
25 |
+
model (`ParlerTTSForConditionalGeneration`):
|
26 |
+
The Parler-TTS model used to generate the audio waveform.
|
27 |
+
device (`str`, *optional*):
|
28 |
+
The torch device on which to run the computation. If `None`, will default to the device of the model.
|
29 |
+
play_steps (`int`, *optional*, defaults to 10):
|
30 |
+
The number of generation steps with which to return the generated audio array. Using fewer steps will
|
31 |
+
mean the first chunk is ready faster, but will require more codec decoding steps overall. This value
|
32 |
+
should be tuned to your device and latency requirements.
|
33 |
+
stride (`int`, *optional*):
|
34 |
+
The window (stride) between adjacent audio samples. Using a stride between adjacent audio samples reduces
|
35 |
+
the hard boundary between them, giving smoother playback. If `None`, will default to a value equivalent to
|
36 |
+
play_steps // 6 in the audio space.
|
37 |
+
timeout (`int`, *optional*):
|
38 |
+
The timeout for the audio queue. If `None`, the queue will block indefinitely. Useful to handle exceptions
|
39 |
+
in `.generate()`, when it is called in a separate thread.
|
40 |
+
"""
|
41 |
+
self.decoder = model.decoder
|
42 |
+
self.audio_encoder = model.audio_encoder
|
43 |
+
self.generation_config = model.generation_config
|
44 |
+
self.device = device if device is not None else model.device
|
45 |
+
self.use_audio_scales = model.use_audio_scales
|
46 |
+
self.use_4dim_audio_codes = model.use_4dim_audio_codes
|
47 |
+
self.audio_kwargs = {}
|
48 |
+
if self.use_audio_scales:
|
49 |
+
self.audio_kwargs["audio_scales"] = [None]
|
50 |
+
|
51 |
+
# variables used in the streaming process
|
52 |
+
self.play_steps = play_steps
|
53 |
+
if stride is not None:
|
54 |
+
self.stride = stride
|
55 |
+
else:
|
56 |
+
hop_length = math.floor(self.audio_encoder.config.sampling_rate / self.audio_encoder.config.frame_rate)
|
57 |
+
self.stride = hop_length * (play_steps - self.decoder.num_codebooks) // 6
|
58 |
+
self.token_cache = None
|
59 |
+
self.to_yield = 0
|
60 |
+
|
61 |
+
# varibles used in the thread process
|
62 |
+
self.audio_queue = Queue()
|
63 |
+
self.stop_signal = None
|
64 |
+
self.timeout = timeout
|
65 |
+
|
66 |
+
def apply_delay_pattern_mask(self, input_ids):
|
67 |
+
# build the delay pattern mask for offsetting each codebook prediction by 1 (this behaviour is specific to Parler)
|
68 |
+
_, delay_pattern_mask = self.decoder.build_delay_pattern_mask(
|
69 |
+
input_ids[:, :1],
|
70 |
+
bos_token_id=self.generation_config.bos_token_id,
|
71 |
+
pad_token_id=self.generation_config.decoder_start_token_id,
|
72 |
+
max_length=input_ids.shape[-1],
|
73 |
+
)
|
74 |
+
# apply the pattern mask to the input ids
|
75 |
+
input_ids = self.decoder.apply_delay_pattern_mask(input_ids, delay_pattern_mask)
|
76 |
+
|
77 |
+
# revert the pattern delay mask by filtering the pad token id
|
78 |
+
mask = (delay_pattern_mask != self.generation_config.bos_token_id) & (delay_pattern_mask != self.generation_config.pad_token_id)
|
79 |
+
input_ids = input_ids[mask].reshape(1, self.decoder.num_codebooks, -1)
|
80 |
+
|
81 |
+
if self.use_4dim_audio_codes:
|
82 |
+
# append the frame dimension back to the audio codes
|
83 |
+
input_ids = input_ids[None, ...]
|
84 |
+
|
85 |
+
# send the input_ids to the correct device
|
86 |
+
input_ids = input_ids.to(self.audio_encoder.device)
|
87 |
+
|
88 |
+
decode_sequentially = (
|
89 |
+
self.generation_config.bos_token_id in input_ids
|
90 |
+
or self.generation_config.pad_token_id in input_ids
|
91 |
+
or self.generation_config.eos_token_id in input_ids
|
92 |
+
)
|
93 |
+
if not decode_sequentially:
|
94 |
+
sample = self.audio_encoder.decode(
|
95 |
+
audio_codes=input_ids,
|
96 |
+
**self.audio_kwargs,
|
97 |
+
).audio_values
|
98 |
+
output_values = sample if sample.ndim == 3 else sample.unsqueeze(0)
|
99 |
+
else:
|
100 |
+
sample = input_ids[:, 0] if self.use_4dim_audio_codes else input_ids[0]
|
101 |
+
sample_mask = ((sample >= self.audio_encoder.config.codebook_size).sum(dim=(0, 1)) == 0) if self.use_4dim_audio_codes else ((sample >= self.audio_encoder.config.codebook_size).sum(dim=0) == 0)
|
102 |
+
sample = sample[:, :, sample_mask] if self.use_4dim_audio_codes else sample[:, sample_mask]
|
103 |
+
sample = self.audio_encoder.decode(audio_codes=sample[None, ...], **self.audio_kwargs).audio_values
|
104 |
+
output_values = sample if sample.ndim == 3 else sample.unsqueeze(0)
|
105 |
+
|
106 |
+
audio_values = output_values[0, 0]
|
107 |
+
return audio_values.cpu().float().numpy()
|
108 |
+
|
109 |
+
def put(self, value):
|
110 |
+
batch_size = value.shape[0] // self.decoder.num_codebooks
|
111 |
+
if batch_size > 1:
|
112 |
+
raise ValueError("ParlerTTSStreamer only supports batch size 1")
|
113 |
+
|
114 |
+
if self.token_cache is None:
|
115 |
+
self.token_cache = value
|
116 |
+
else:
|
117 |
+
self.token_cache = torch.concatenate([self.token_cache, value[:, None]], dim=-1)
|
118 |
+
|
119 |
+
if self.token_cache.shape[-1] % self.play_steps == 0:
|
120 |
+
audio_values = self.apply_delay_pattern_mask(self.token_cache)
|
121 |
+
self.on_finalized_audio(audio_values[self.to_yield : -self.stride])
|
122 |
+
self.to_yield += len(audio_values) - self.to_yield - self.stride
|
123 |
+
|
124 |
+
def end(self):
|
125 |
+
"""Flushes any remaining cache and appends the stop symbol."""
|
126 |
+
if self.token_cache is not None:
|
127 |
+
audio_values = self.apply_delay_pattern_mask(self.token_cache)
|
128 |
+
else:
|
129 |
+
audio_values = np.zeros(self.to_yield)
|
130 |
+
|
131 |
+
self.on_finalized_audio(audio_values[self.to_yield :], stream_end=True)
|
132 |
+
|
133 |
+
def on_finalized_audio(self, audio: np.ndarray, stream_end: bool = False):
|
134 |
+
"""Put the new audio in the queue. If the stream is ending, also put a stop signal in the queue."""
|
135 |
+
self.audio_queue.put(audio, timeout=self.timeout)
|
136 |
+
if stream_end:
|
137 |
+
self.audio_queue.put(self.stop_signal, timeout=self.timeout)
|
138 |
+
|
139 |
+
def __iter__(self):
|
140 |
+
return self
|
141 |
+
|
142 |
+
def __next__(self):
|
143 |
+
value = self.audio_queue.get(timeout=self.timeout)
|
144 |
+
if not isinstance(value, np.ndarray) and value == self.stop_signal:
|
145 |
+
raise StopIteration()
|
146 |
+
else:
|
147 |
+
return value
|
parler-tts/pyproject.toml
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[tool.black]
|
2 |
+
line-length = 119
|
3 |
+
target-version = ['py37']
|
4 |
+
|
5 |
+
[tool.ruff]
|
6 |
+
# Never enforce `E501` (line length violations).
|
7 |
+
ignore = ["C901", "E501", "E741", "W605"]
|
8 |
+
select = ["C", "E", "F", "I", "W"]
|
9 |
+
line-length = 119
|
10 |
+
|
11 |
+
# Ignore import violations in all `__init__.py` files.
|
12 |
+
[tool.ruff.per-file-ignores]
|
13 |
+
"__init__.py" = ["E402", "F401", "F403", "F811"]
|
14 |
+
|
15 |
+
[tool.ruff.isort]
|
16 |
+
lines-after-imports = 2
|
17 |
+
known-first-party = ["distil_whisper"]
|
parler-tts/setup.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import os
|
16 |
+
|
17 |
+
import setuptools
|
18 |
+
|
19 |
+
|
20 |
+
_deps = [
|
21 |
+
"transformers>=4.46.1,<=4.46.1",
|
22 |
+
"torch",
|
23 |
+
"sentencepiece",
|
24 |
+
"descript-audio-codec",
|
25 |
+
"descript-audiotools @ git+https://github.com/descriptinc/audiotools", # temporary fix as long as 0.7.4 is not published
|
26 |
+
"protobuf>=4.0.0"
|
27 |
+
]
|
28 |
+
|
29 |
+
_extras_dev_deps = [
|
30 |
+
"black~=23.1",
|
31 |
+
"isort>=5.5.4",
|
32 |
+
"ruff>=0.0.241,<=0.0.259",
|
33 |
+
]
|
34 |
+
|
35 |
+
_extras_training_deps = [
|
36 |
+
"jiwer",
|
37 |
+
"wandb",
|
38 |
+
"accelerate",
|
39 |
+
"evaluate",
|
40 |
+
"datasets[audio]>=2.14.5",
|
41 |
+
]
|
42 |
+
|
43 |
+
here = os.path.abspath(os.path.dirname(__file__))
|
44 |
+
|
45 |
+
with open(os.path.join(here, "README.md"), encoding="utf-8") as f:
|
46 |
+
long_description = f.read()
|
47 |
+
|
48 |
+
# read version
|
49 |
+
with open(os.path.join(here, "parler_tts", "__init__.py"), encoding="utf-8") as f:
|
50 |
+
for line in f:
|
51 |
+
if line.startswith("__version__"):
|
52 |
+
version = line.split("=")[1].strip().strip('"')
|
53 |
+
break
|
54 |
+
else:
|
55 |
+
raise RuntimeError("Unable to find version string.")
|
56 |
+
|
57 |
+
setuptools.setup(
|
58 |
+
name="parler_tts",
|
59 |
+
version=version,
|
60 |
+
description="Toolkit for using and training Parler-TTS, a high-quality text-to-speech model.",
|
61 |
+
long_description=long_description,
|
62 |
+
long_description_content_type="text/markdown",
|
63 |
+
packages=setuptools.find_packages(),
|
64 |
+
install_requires=_deps,
|
65 |
+
extras_require={
|
66 |
+
"dev": _extras_dev_deps,
|
67 |
+
"train": _extras_training_deps,
|
68 |
+
},
|
69 |
+
)
|
parler-tts/training/README.md
ADDED
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Training Parler-TTS
|
2 |
+
|
3 |
+
<a target="_blank" href="https://github.com/ylacombe/scripts_and_notebooks/blob/main/Finetuning_Parler_TTS_v1_on_a_single_speaker_dataset.ipynb">
|
4 |
+
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
|
5 |
+
</a>
|
6 |
+
|
7 |
+
**TL;DR:** After having followed the [installation steps](#requirements), you can reproduce the [Parler-TTS Mini v1](https://huggingface.co/parler-tts/parler-tts-mini-v1) training recipe with the following command line:
|
8 |
+
|
9 |
+
```sh
|
10 |
+
accelerate launch ./training/run_parler_tts_training.py ./helpers/training_configs/starting_point_v1.json
|
11 |
+
```
|
12 |
+
|
13 |
+
-------------
|
14 |
+
|
15 |
+
This sub-folder contains all the information to train or fine-tune your own Parler-TTS model. It consists of:
|
16 |
+
- [1. An introduction to the Parler-TTS architecture](#a-architecture)
|
17 |
+
- [2. First steps to get started](#b-getting-started)
|
18 |
+
- [3. Training guide](#c-training)
|
19 |
+
|
20 |
+
> [!IMPORTANT]
|
21 |
+
> You can also follow [this fine-tuning guide](https://github.com/ylacombe/scripts_and_notebooks/blob/main/Finetuning_Parler_TTS_v1_on_a_single_speaker_dataset.ipynb) on a mono-speaker dataset example.
|
22 |
+
|
23 |
+
## 1. Architecture
|
24 |
+
|
25 |
+
At the moment, Parler-TTS architecture is almost a carbon copy of the [MusicGen architecture](https://huggingface.co/docs/transformers/v4.39.3/en/model_doc/musicgen#model-structure) and can be decomposed into three distinct stages:
|
26 |
+
1. Text encoder: maps the text descriptions to a sequence of hidden-state representations. Parler-TTS uses a frozen text encoder initialised entirely from Flan-T5
|
27 |
+
2. Parler-TTS decoder: a language model (LM) that auto-regressively generates audio tokens (or codes) conditional on the encoder hidden-state representations
|
28 |
+
3. Audio codec: used to recover the audio waveform from the audio tokens predicted by the decoder. We use the [DAC model](https://github.com/descriptinc/descript-audio-codec) from Descript, although other codec models, such as [EnCodec](https://huggingface.co/facebook/encodec_48khz), can also be used.
|
29 |
+
|
30 |
+
Parler-TTS however introduces some small tweaks:
|
31 |
+
- The text **description** is passed through the text encoder and used in the cross-attention layers of the decoder.
|
32 |
+
- The text **prompt** is simply passed through an embedding layer and concatenated to the decoder input hidden states.
|
33 |
+
- The audio encoder used is [**DAC**](https://descript.notion.site/Descript-Audio-Codec-11389fce0ce2419891d6591a68f814d5) instead of [Encodec](https://github.com/facebookresearch/encodec), as it exhibits better quality.
|
34 |
+
|
35 |
+
|
36 |
+
## 2. Getting started
|
37 |
+
|
38 |
+
To get started, you need to follow a few steps:
|
39 |
+
1. Install the requirements.
|
40 |
+
2. Find or initialize the model you'll train on.
|
41 |
+
3. Find and/or annotate the dataset you'll train your model on.
|
42 |
+
|
43 |
+
### Requirements
|
44 |
+
|
45 |
+
The Parler-TTS code is written in [PyTorch](https://pytorch.org) and [Accelerate](https://huggingface.co/docs/accelerate/index). It uses some additional requirements, like [wandb](https://wandb.ai/), especially for logging and evaluation.
|
46 |
+
|
47 |
+
To install the package for training, you need to clone the repository from source...
|
48 |
+
|
49 |
+
```bash
|
50 |
+
git clone https://github.com/huggingface/parler-tts.git
|
51 |
+
cd parler-tts
|
52 |
+
```
|
53 |
+
|
54 |
+
... And then install the requirements:
|
55 |
+
|
56 |
+
```bash
|
57 |
+
pip install -e .[train]
|
58 |
+
```
|
59 |
+
|
60 |
+
Optionally, you can create a wandb account and login to it by following [this guide](https://docs.wandb.ai/quickstart). [`wandb`](https://docs.wandb.ai/) allows for better tracking of the experiments metrics and losses.
|
61 |
+
|
62 |
+
You also have the option to configure Accelerate by running the following command. Note that you should set the number of GPUs you wish to use for training, and also the data type (dtype) to your preferred dtype for training/inference (e.g. `bfloat16` on A100 GPUs, `float16` on V100 GPUs, etc.):
|
63 |
+
|
64 |
+
```bash
|
65 |
+
accelerate config
|
66 |
+
```
|
67 |
+
|
68 |
+
Lastly, you can link you Hugging Face account so that you can push model repositories on the Hub. This will allow you to save your trained models on the Hub so that you can share them with the community. Run the command:
|
69 |
+
|
70 |
+
```bash
|
71 |
+
git config --global credential.helper store
|
72 |
+
huggingface-cli login
|
73 |
+
```
|
74 |
+
And then enter an authentication token from https://huggingface.co/settings/tokens. Create a new token if you do not have one already. You should make sure that this token has "write" privileges.
|
75 |
+
|
76 |
+
### Initialize a model from scratch or use a pre-trained one.
|
77 |
+
|
78 |
+
Depending on your compute resources and your dataset, you need to choose between fine-tuning a pre-trained model and training a new model from scratch.
|
79 |
+
|
80 |
+
In that sense, we released a 880M checkpoint trained on 45K hours of annotated data under the repository id: [`parler-tts/parler-tts-mini-v1`](https://huggingface.co/parler-tts/parler-tts-mini-v1), that you can fine-tune for your own use-case.
|
81 |
+
|
82 |
+
You can also train you own model from scratch. You can find [here](/helpers/model_init_scripts/) examples on how to initialize a model from scratch. For example, you can initialize a dummy model with:
|
83 |
+
|
84 |
+
```sh
|
85 |
+
python helpers/model_init_scripts/init_dummy_model.py ./parler-tts-untrained-dummy --text_model "google-t5/t5-small" --audio_model "parler-tts/dac_44khZ_8kbps"
|
86 |
+
```
|
87 |
+
|
88 |
+
In the rest of this guide, and to reproduce the Parler-TTS Mini v1 training recipe, we'll use a 880M parameters model that we'll initialize with:
|
89 |
+
|
90 |
+
```sh
|
91 |
+
python helpers/model_init_scripts/init_model_600M.py ./parler-tts-untrained-600M --text_model "google/flan-t5-large" --audio_model "parler-tts/dac_44khZ_8kbps"
|
92 |
+
```
|
93 |
+
|
94 |
+
|
95 |
+
### Create or find datasets
|
96 |
+
|
97 |
+
To train your own Parler-TTS, you need datasets with 3 main features:
|
98 |
+
- speech data
|
99 |
+
- text transcription of the speech data
|
100 |
+
- conditionning text description - that you can create using [Data-Speech](https://github.com/huggingface/dataspeech), a library that allows you to annotate the speaker and utterance characteristics with natural language description.
|
101 |
+
|
102 |
+
Note that we made the choice to use description of the main speech characteristics (speaker pitch, speaking rate, level of noise, etc.) but that you are free to use any handmade or generated text description that makes sense.
|
103 |
+
|
104 |
+
To train Parler-TTS Mini v1, we used:
|
105 |
+
* A [filtered version](https://huggingface.co/datasets/parler-tts/libritts_r_filtered) of [LibriTTS-R dataset](https://huggingface.co/datasets/blabble-io/libritts_r), a 1K hours high-quality speech dataset.
|
106 |
+
* The [English subset](https://huggingface.co/datasets/parler-tts/mls_eng) of [Multilingual LibriSpeech](https://huggingface.co/datasets/facebook/multilingual_librispeech).
|
107 |
+
|
108 |
+
Both datasets have been annotated using the [Data-Speech](https://github.com/huggingface/dataspeech) recipe, respectively [here](https://huggingface.co/datasets/parler-tts/libritts-r-filtered-speaker-descriptions) and [here](https://huggingface.co/datasets/parler-tts/mls-eng-speaker-descriptions).
|
109 |
+
|
110 |
+
|
111 |
+
## 3. Training
|
112 |
+
|
113 |
+
The script [`run_parler_tts_training.py`](/training/run_parler_tts_training.py) is an end-to-end script that:
|
114 |
+
1. load dataset(s) and merge them to the annotation dataset(s) if necessary
|
115 |
+
2. pre-compute audio tokens
|
116 |
+
3. train Parler-TTS
|
117 |
+
|
118 |
+
To train Parler-TTS Mini v1, we roughly used:
|
119 |
+
|
120 |
+
```sh
|
121 |
+
accelerate launch ./training/run_parler_tts_training.py \
|
122 |
+
--model_name_or_path "./parler-tts-untrained-600M/parler-tts-untrained-600M/" \
|
123 |
+
--feature_extractor_name "parler-tts/dac_44khZ_8kbps" \
|
124 |
+
--description_tokenizer_name "google/flan-t5-large" \
|
125 |
+
--prompt_tokenizer_name "google/flan-t5-large" \
|
126 |
+
--report_to "wandb" \
|
127 |
+
--overwrite_output_dir true \
|
128 |
+
--train_dataset_name "parler-tts/libritts_r_filtered+parler-tts/libritts_r_filtered+parler-tts/libritts_r_filtered+parler-tts/mls_eng" \
|
129 |
+
--train_metadata_dataset_name "parler-tts/libritts-r-filtered-speaker-descriptions+parler-tts/libritts-r-filtered-speaker-descriptions+parler-tts/libritts-r-filtered-speaker-descriptions+parler-tts/mls-eng-speaker-descriptions" \
|
130 |
+
--train_dataset_config_name "clean+clean+other+default" \
|
131 |
+
--train_split_name "train.clean.360+train.clean.100+train.other.500+train" \
|
132 |
+
--eval_dataset_name "parler-tts/libritts_r_filtered+parler-tts/mls_eng" \
|
133 |
+
--eval_metadata_dataset_name "parler-tts/libritts-r-filtered-speaker-descriptions+parler-tts/mls-eng-speaker-descriptions" \
|
134 |
+
--eval_dataset_config_name "other+default" \
|
135 |
+
--eval_split_name "test.other+test" \
|
136 |
+
--target_audio_column_name "audio" \
|
137 |
+
--description_column_name "text_description" \
|
138 |
+
--prompt_column_name "text" \
|
139 |
+
--max_duration_in_seconds 30 \
|
140 |
+
--min_duration_in_seconds 2.0 \
|
141 |
+
--max_text_length 600 \
|
142 |
+
--add_audio_samples_to_wandb true \
|
143 |
+
--id_column_name "id" \
|
144 |
+
--preprocessing_num_workers 8 \
|
145 |
+
--do_train true \
|
146 |
+
--num_train_epochs 4 \
|
147 |
+
--gradient_accumulation_steps 6 \
|
148 |
+
--gradient_checkpointing false \
|
149 |
+
--per_device_train_batch_size 4 \
|
150 |
+
--learning_rate 0.00095 \
|
151 |
+
--adam_beta1 0.9 \
|
152 |
+
--adam_beta2 0.99 \
|
153 |
+
--weight_decay 0.01 \
|
154 |
+
--lr_scheduler_type "constant_with_warmup" \
|
155 |
+
--warmup_steps 20000 \
|
156 |
+
--logging_steps 1000 \
|
157 |
+
--freeze_text_encoder true \
|
158 |
+
--do_eval true \
|
159 |
+
--predict_with_generate true \
|
160 |
+
--include_inputs_for_metrics true \
|
161 |
+
--evaluation_strategy steps \
|
162 |
+
--eval_steps 10000 \
|
163 |
+
--save_steps 10000 \
|
164 |
+
--per_device_eval_batch_size 4 \
|
165 |
+
--audio_encoder_per_device_batch_size 24 \
|
166 |
+
--dtype "bfloat16" \
|
167 |
+
--seed 456 \
|
168 |
+
--output_dir "./output_dir_training/" \
|
169 |
+
--temporary_save_to_disk "./audio_code_tmp/" \
|
170 |
+
--save_to_disk "./tmp_dataset_audio/" \
|
171 |
+
--max_eval_samples 96 \
|
172 |
+
--dataloader_num_workers 8 \
|
173 |
+
--group_by_length true \
|
174 |
+
--attn_implementation "sdpa"
|
175 |
+
```
|
176 |
+
|
177 |
+
In particular, note how multiple training datasets, metadataset, configurations and splits can be loaded by separating the dataset arguments by + symbols:
|
178 |
+
```sh
|
179 |
+
"train_dataset_name": "parler-tts/libritts_r_filtered+parler-tts/libritts_r_filtered+parler-tts/libritts_r_filtered+parler-tts/mls_eng",
|
180 |
+
"train_metadata_dataset_name": "parler-tts/libritts-r-filtered-speaker-descriptions+parler-tts/libritts-r-filtered-speaker-descriptions+parler-tts/libritts-r-filtered-speaker-descriptions+parler-tts/mls-eng-speaker-descriptions",
|
181 |
+
"train_dataset_config_name": "clean+clean+other+default",
|
182 |
+
"train_split_name": "train.clean.360+train.clean.100+train.other.500+train",
|
183 |
+
```
|
184 |
+
|
185 |
+
|
186 |
+
Additionally, you can also write a JSON config file. Here, [starting_point_v1.json](helpers/training_configs/starting_point_v1.json) contains the exact same hyper-parameters than above and can be launched like that:
|
187 |
+
```sh
|
188 |
+
accelerate launch ./training/run_parler_tts_training.py ./helpers/training_configs/starting_point_v1.json
|
189 |
+
```
|
190 |
+
|
191 |
+
Training logs will be reported to wandb, provided that you passed `--report_to "wandb"` to the arguments.
|
192 |
+
|
193 |
+
> [!TIP]
|
194 |
+
> Starting training a new model from scratch can easily be overwhelming, so here's what training looked like for v1: [logs](https://api.wandb.ai/links/ylacombe/j7g8isjn)
|
195 |
+
|
196 |
+
Scaling to multiple GPUs using [distributed data parallelism (DDP)](https://pytorch.org/tutorials/beginner/ddp_series_theory.html) is trivial: simply run `accelerate config` and select the multi-GPU option, specifying the IDs of the GPUs you wish to use. The above script can then be run using DDP with no code changes. In our case, we used 4 nodes of 8 H100 80GB to train Parler-TTS Mini for around 1.5 days.
|
197 |
+
|
198 |
+
|
199 |
+
There are a few other noteworthy arguments:
|
200 |
+
1. `train_metadata_dataset_name` and `eval_metadata_dataset_name` specify, if necessary, the names of the dataset(s) that contain(s) the conditionning text descriptions. For example, this [dataset resulting from the Data-Speech annotation process](https://huggingface.co/datasets/parler-tts/libritts-r-filtered-speaker-descriptions) is saved without the audio column, as it's costly to write and push audio data, so it needs to be concatenated back to the original LibriTTS-R dataset.
|
201 |
+
2. As noted above, the script pre-computes audio tokens as computing audio codes is costly and only needs to be done once, since we're freezing the audio encoder. `audio_encoder_per_device_batch_size` is used to precise the per devie batch size for this pre-processing step.
|
202 |
+
3. Additionnally, when scaling up the training data and iterating on the hyper-parameters or the model architecture, we might want to avoid recomputing the audio tokens at each training run. That's why we introduced two additional parameters, `save_to_disk` and `temporary_save_to_disk` that serves as temporary buffers to save intermediary datasets. Note that processed data is made of text and audio tokens which are much more memory efficient, so the additional required space is negligible.
|
203 |
+
4. `predict_with_generate` and `add_audio_samples_to_wandb` are required to store generated audios and to compute WER and CLAP similarity.
|
204 |
+
5. `freeze_text_encoder`: which allows to freeze the text encoder, to save compute resources.
|
205 |
+
|
206 |
+
And finally, two additional comments:
|
207 |
+
1. `lr_scheduler_stype`: defines the learning rate schedule, one of `constant_with_warmup` or `cosine`. When experimenting with a training set-up or training for very few epochs, using `constant_with_warmup` is typically beneficial, since the learning rate remains high over the short training run. When performing longer training runs, using a `cosine` schedule shoud give better results.
|
208 |
+
2. `dtype`: data type (dtype) in which the model computation should be performed. Note that this only controls the dtype of the computations (forward and backward pass), and not the dtype of the parameters or optimiser states.
|
209 |
+
|
210 |
+
> [!TIP]
|
211 |
+
> Fine-tuning is as easy as modifying `model_name_or_path` to a pre-trained model.
|
212 |
+
> For example: `--model_name_or_path parler-tts/parler-tts-mini-v1`.
|
parler-tts/training/__init__.py
ADDED
File without changes
|
parler-tts/training/arguments.py
ADDED
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass, field
|
2 |
+
from typing import Optional, List
|
3 |
+
|
4 |
+
from transformers import Seq2SeqTrainingArguments
|
5 |
+
|
6 |
+
|
7 |
+
@dataclass
|
8 |
+
class ModelArguments:
|
9 |
+
"""
|
10 |
+
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
|
11 |
+
"""
|
12 |
+
|
13 |
+
model_name_or_path: str = field(
|
14 |
+
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
|
15 |
+
)
|
16 |
+
config_name: Optional[str] = field(
|
17 |
+
default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
|
18 |
+
)
|
19 |
+
feature_extractor_name: Optional[str] = field(
|
20 |
+
default=None, metadata={"help": "Pretrained feature extractor name or path if not the same as model_name"}
|
21 |
+
)
|
22 |
+
description_tokenizer_name: Optional[str] = field(
|
23 |
+
default=None, metadata={"help": "Pretrained description tokenizer name or path if not the same as model_name"}
|
24 |
+
)
|
25 |
+
prompt_tokenizer_name: Optional[str] = field(
|
26 |
+
default=None,
|
27 |
+
metadata={"help": "Pretrained prompt tokenizer name or path if not the same as description_tokenizer_name"},
|
28 |
+
)
|
29 |
+
cache_dir: Optional[str] = field(
|
30 |
+
default=None,
|
31 |
+
metadata={"help": "Where to store the pretrained models downloaded from huggingface.co"},
|
32 |
+
)
|
33 |
+
use_fast_tokenizer: bool = field(
|
34 |
+
default=True,
|
35 |
+
metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
|
36 |
+
)
|
37 |
+
model_revision: str = field(
|
38 |
+
default="main",
|
39 |
+
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
|
40 |
+
)
|
41 |
+
pad_token_id: int = field(
|
42 |
+
default=None,
|
43 |
+
metadata={"help": "If specified, change the model pad token id."},
|
44 |
+
)
|
45 |
+
decoder_start_token_id: int = field(
|
46 |
+
default=None,
|
47 |
+
metadata={"help": "If specified, change the model decoder start token id."},
|
48 |
+
)
|
49 |
+
freeze_text_encoder: bool = field(
|
50 |
+
default=False,
|
51 |
+
metadata={"help": "Whether to freeze the text encoder."},
|
52 |
+
)
|
53 |
+
do_sample: bool = field(
|
54 |
+
default=True,
|
55 |
+
metadata={"help": "Whether to do sampling or greedy decoding."},
|
56 |
+
)
|
57 |
+
temperature: float = field(
|
58 |
+
default=1.0,
|
59 |
+
metadata={"help": "Temperature if sampling."},
|
60 |
+
)
|
61 |
+
max_length: int = field(
|
62 |
+
default=2580,
|
63 |
+
metadata={"help": "Generation max length."},
|
64 |
+
)
|
65 |
+
bandwidth: float = field(
|
66 |
+
default=6,
|
67 |
+
metadata={"help": "Audio encoder bandwidth."},
|
68 |
+
)
|
69 |
+
asr_model_name_or_path: str = field(
|
70 |
+
default="distil-whisper/distil-large-v2",
|
71 |
+
metadata={
|
72 |
+
"help": "Used to compute WER during evaluation. Path to pretrained model or model identifier from huggingface.co/models"
|
73 |
+
},
|
74 |
+
)
|
75 |
+
clap_model_name_or_path: str = field(
|
76 |
+
default="laion/larger_clap_music_and_speech",
|
77 |
+
metadata={
|
78 |
+
"help": "Used to compute audio similarity during evaluation. Path to pretrained model or model identifier from huggingface.co/models"
|
79 |
+
},
|
80 |
+
)
|
81 |
+
attn_implementation: str = field(
|
82 |
+
default="eager",
|
83 |
+
metadata={"help": "Attention implementation used. One of `eager`, `sdpa`, `flash_attention_2`"},
|
84 |
+
)
|
85 |
+
cross_attention_implementation_strategy: str = field(
|
86 |
+
default=None,
|
87 |
+
metadata={
|
88 |
+
"help": "If not specified, the cross-attention implementation will be the same as `_attn_implementation`. If `always_eager`, it will always be the eager implementation. If `always_sdpa`, it will always be the sdpa implementation."
|
89 |
+
},
|
90 |
+
)
|
91 |
+
prompt_padding_side: Optional[str] = field(
|
92 |
+
default="left",
|
93 |
+
metadata={
|
94 |
+
"help": "Prompt tokenizer padding side. Defaults to `left`. If the prompt is pre-pended to the codebooks hidden states, it should be padded on the left."
|
95 |
+
},
|
96 |
+
)
|
97 |
+
|
98 |
+
|
99 |
+
@dataclass
|
100 |
+
class DataTrainingArguments:
|
101 |
+
"""
|
102 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
103 |
+
|
104 |
+
Using `HfArgumentParser` we can turn this class
|
105 |
+
into argparse arguments to be able to specify them on
|
106 |
+
the command line.
|
107 |
+
"""
|
108 |
+
|
109 |
+
train_dataset_name: str = field(
|
110 |
+
default=None,
|
111 |
+
metadata={
|
112 |
+
"help": "The name of the training dataset to use (via the datasets library). Load and combine "
|
113 |
+
"multiple datasets by separating dataset ids by a '+' symbol. For example, to load and combine "
|
114 |
+
" librispeech and common voice, set `train_dataset_name='librispeech_asr+common_voice'`."
|
115 |
+
},
|
116 |
+
)
|
117 |
+
train_dataset_config_name: Optional[str] = field(
|
118 |
+
default=None,
|
119 |
+
metadata={
|
120 |
+
"help": "The configuration name of the training dataset to use (via the datasets library). Load and combine "
|
121 |
+
"multiple datasets by separating dataset configs by a '+' symbol."
|
122 |
+
},
|
123 |
+
)
|
124 |
+
train_split_name: str = field(
|
125 |
+
default="train",
|
126 |
+
metadata={
|
127 |
+
"help": ("The name of the training data set split to use (via the datasets library). Defaults to 'train'")
|
128 |
+
},
|
129 |
+
)
|
130 |
+
train_dataset_samples: str = field(
|
131 |
+
default=None,
|
132 |
+
metadata={
|
133 |
+
"help": "Number of samples in the training data. Load and combine "
|
134 |
+
"multiple datasets by separating dataset samples by a '+' symbol."
|
135 |
+
},
|
136 |
+
)
|
137 |
+
train_metadata_dataset_name: str = field(
|
138 |
+
default=None,
|
139 |
+
metadata={
|
140 |
+
"help": "The name of the metadata training dataset to use (via the datasets library). Load and combine "
|
141 |
+
"multiple datasets by separating dataset ids by a '+' symbol. For example, to load and combine "
|
142 |
+
" librispeech and common voice, set `train_dataset_name='librispeech_asr+common_voice'`."
|
143 |
+
},
|
144 |
+
)
|
145 |
+
eval_dataset_name: str = field(
|
146 |
+
default=None,
|
147 |
+
metadata={
|
148 |
+
"help": "The name of the evaluation dataset to use (via the datasets library). Defaults to the training dataset name if unspecified."
|
149 |
+
},
|
150 |
+
)
|
151 |
+
eval_dataset_config_name: Optional[str] = field(
|
152 |
+
default=None,
|
153 |
+
metadata={
|
154 |
+
"help": "The configuration name of the evaluation dataset to use (via the datasets library). Defaults to the training dataset config name if unspecified"
|
155 |
+
},
|
156 |
+
)
|
157 |
+
eval_split_name: str = field(
|
158 |
+
default="test",
|
159 |
+
metadata={
|
160 |
+
"help": "The name of the evaluation data set split to use (via the datasets library). Defaults to 'test'"
|
161 |
+
},
|
162 |
+
)
|
163 |
+
eval_metadata_dataset_name: str = field(
|
164 |
+
default=None,
|
165 |
+
metadata={
|
166 |
+
"help": "The name of the metadata training dataset to use (via the datasets library). Load and combine "
|
167 |
+
"multiple datasets by separating dataset ids by a '+' symbol. For example, to load and combine "
|
168 |
+
" librispeech and common voice, set `train_dataset_name='librispeech_asr+common_voice'`."
|
169 |
+
},
|
170 |
+
)
|
171 |
+
target_audio_column_name: str = field(
|
172 |
+
default="audio",
|
173 |
+
metadata={"help": "The name of the dataset column containing the target audio data. Defaults to 'audio'"},
|
174 |
+
)
|
175 |
+
description_column_name: str = field(
|
176 |
+
default=None,
|
177 |
+
metadata={"help": "The name of the dataset column containing the description text data. Defaults to 'None'."},
|
178 |
+
)
|
179 |
+
prompt_column_name: str = field(
|
180 |
+
default=None,
|
181 |
+
metadata={"help": "The name of the dataset column containing the prompt text data. Defaults to 'None'."},
|
182 |
+
)
|
183 |
+
overwrite_cache: bool = field(
|
184 |
+
default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
|
185 |
+
)
|
186 |
+
preprocessing_num_workers: Optional[int] = field(
|
187 |
+
default=None,
|
188 |
+
metadata={"help": "The number of processes to use for the preprocessing."},
|
189 |
+
)
|
190 |
+
max_train_samples: Optional[int] = field(
|
191 |
+
default=None,
|
192 |
+
metadata={
|
193 |
+
"help": (
|
194 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
195 |
+
"value if set."
|
196 |
+
)
|
197 |
+
},
|
198 |
+
)
|
199 |
+
max_eval_samples: Optional[int] = field(
|
200 |
+
default=None,
|
201 |
+
metadata={
|
202 |
+
"help": (
|
203 |
+
"For debugging purposes or quicker training, truncate the number of validation examples to this "
|
204 |
+
"value if set."
|
205 |
+
)
|
206 |
+
},
|
207 |
+
)
|
208 |
+
max_duration_in_seconds: float = field(
|
209 |
+
default=35.0,
|
210 |
+
metadata={
|
211 |
+
"help": (
|
212 |
+
"Filter audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`."
|
213 |
+
"Also, used to set maximum audio length if `pad_to_max_length=True`."
|
214 |
+
)
|
215 |
+
},
|
216 |
+
)
|
217 |
+
min_duration_in_seconds: float = field(
|
218 |
+
default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"}
|
219 |
+
)
|
220 |
+
max_text_length: int = field(
|
221 |
+
default=500, metadata={"help": "If set, max description lengths in number of characters."}
|
222 |
+
)
|
223 |
+
max_prompt_token_length: int = field(
|
224 |
+
default=None,
|
225 |
+
metadata={
|
226 |
+
"help": (
|
227 |
+
"If set, filter samples with prompts that are longer than `max_prompt_token_length` tokens."
|
228 |
+
"Also, used to set maximum prompt token length if `pad_to_max_length=True`."
|
229 |
+
)
|
230 |
+
},
|
231 |
+
)
|
232 |
+
max_description_token_length: int = field(
|
233 |
+
default=None,
|
234 |
+
metadata={
|
235 |
+
"help": (
|
236 |
+
"If set, filter samples with descriptions that are longer than `max_description_token_length` tokens."
|
237 |
+
"Also, used to set maximum description token length if `pad_to_max_length=True`."
|
238 |
+
)
|
239 |
+
},
|
240 |
+
)
|
241 |
+
pad_to_max_length: bool = field(
|
242 |
+
default=False,
|
243 |
+
metadata={
|
244 |
+
"help": (
|
245 |
+
"If `True`, pad audio, prompt and description to a maximum length set with respectively "
|
246 |
+
"`max_duration_in_seconds`, `max_prompt_token_length`, `max_description_token_length`."
|
247 |
+
)
|
248 |
+
},
|
249 |
+
)
|
250 |
+
preprocessing_only: bool = field(
|
251 |
+
default=False,
|
252 |
+
metadata={
|
253 |
+
"help": (
|
254 |
+
"Whether to only do data preprocessing and skip training. This is especially useful when data"
|
255 |
+
" preprocessing errors out in distributed training due to timeout. In this case, one should run the"
|
256 |
+
" preprocessing in a non-distributed setup with `preprocessing_only=True` so that the cached datasets"
|
257 |
+
" can consequently be loaded in distributed training."
|
258 |
+
" In this training script, `save_to_disk` must be set to the path in which the dataset should be saved. "
|
259 |
+
)
|
260 |
+
},
|
261 |
+
)
|
262 |
+
token: str = field(
|
263 |
+
default=None,
|
264 |
+
metadata={
|
265 |
+
"help": (
|
266 |
+
"The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
|
267 |
+
"generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
|
268 |
+
)
|
269 |
+
},
|
270 |
+
)
|
271 |
+
use_auth_token: bool = field(
|
272 |
+
default=None,
|
273 |
+
metadata={
|
274 |
+
"help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead."
|
275 |
+
},
|
276 |
+
)
|
277 |
+
trust_remote_code: bool = field(
|
278 |
+
default=False,
|
279 |
+
metadata={
|
280 |
+
"help": (
|
281 |
+
"Whether or not to allow for custom models defined on the Hub in their own modeling files. This option "
|
282 |
+
"should only be set to `True` for repositories you trust and in which you have read the code, as it will "
|
283 |
+
"execute code present on the Hub on your local machine."
|
284 |
+
)
|
285 |
+
},
|
286 |
+
)
|
287 |
+
add_audio_samples_to_wandb: bool = field(
|
288 |
+
default=False,
|
289 |
+
metadata={"help": "If set and if `wandb` in args.report_to, will add generated audio samples to wandb logs."},
|
290 |
+
)
|
291 |
+
id_column_name: str = field(default=None, metadata={"help": "id column name."})
|
292 |
+
wandb_project: str = field(
|
293 |
+
default="parler-speech",
|
294 |
+
metadata={"help": "The name of the wandb project."},
|
295 |
+
)
|
296 |
+
wandb_run_name: str = field(
|
297 |
+
default=None,
|
298 |
+
metadata={
|
299 |
+
"help": "If specified, the name of the run. If not specified, wandb will give a random name to this run."
|
300 |
+
},
|
301 |
+
)
|
302 |
+
save_to_disk: str = field(
|
303 |
+
default=None,
|
304 |
+
metadata={
|
305 |
+
"help": "If set, will save the dataset to this path if this is an empyt folder. If not empty, will load the datasets from it."
|
306 |
+
},
|
307 |
+
)
|
308 |
+
temporary_save_to_disk: str = field(default=None, metadata={"help": "Temporarily save audio labels here."})
|
309 |
+
save_codec_steps: Optional[int] = field(
|
310 |
+
default=500,
|
311 |
+
metadata={"help": "Temporarily save the audio labels every `save_steps`."},
|
312 |
+
)
|
313 |
+
pad_to_multiple_of: Optional[int] = field(
|
314 |
+
default=2,
|
315 |
+
metadata={"help": ("Pad to multiple of for tokenizers.")},
|
316 |
+
)
|
317 |
+
|
318 |
+
|
319 |
+
@dataclass
|
320 |
+
class ParlerTTSTrainingArguments(Seq2SeqTrainingArguments):
|
321 |
+
dtype: Optional[str] = field(
|
322 |
+
default="float32",
|
323 |
+
metadata={
|
324 |
+
"help": (
|
325 |
+
"The data type (dtype) in which to run training. One of `float32` (full-precision), "
|
326 |
+
"`float16` or `bfloat16` (both half-precision)."
|
327 |
+
)
|
328 |
+
},
|
329 |
+
)
|
330 |
+
audio_encoder_per_device_batch_size: int = field(
|
331 |
+
default=8,
|
332 |
+
metadata={"help": ("Specify the batch size of the audio encoding pre-processing steps.")},
|
333 |
+
)
|
334 |
+
eval_dataloader_num_workers: Optional[int] = field(
|
335 |
+
default=0,
|
336 |
+
metadata={
|
337 |
+
"help": (
|
338 |
+
"Number of subprocesses to use for evaluation data loading (PyTorch only). 0 means that the data will be loaded in the main process."
|
339 |
+
)
|
340 |
+
},
|
341 |
+
)
|
342 |
+
compute_clap_similarity_metric: bool = field(
|
343 |
+
default=True,
|
344 |
+
metadata={
|
345 |
+
"help": (
|
346 |
+
"Whether or not to compute the clap similarity metric between the description and the generation during evalution."
|
347 |
+
)
|
348 |
+
},
|
349 |
+
)
|
350 |
+
compute_noise_level_metric: bool = field(
|
351 |
+
default=True,
|
352 |
+
metadata={"help": ("Whether or not to compute the squim si-sdr measure of the generations.")},
|
353 |
+
)
|
354 |
+
noise_level_to_compute_clean_wer: float = field(
|
355 |
+
default=25,
|
356 |
+
metadata={
|
357 |
+
"help": (
|
358 |
+
"if `compute_noise_level_metric=True`, will compute a 'clean' WER on samples with generated noise higher than `noise_level_to_compute_clean_wer`."
|
359 |
+
"This is a proxy measure to compute WER on clean audios, provided that the model learn to generate clean audios."
|
360 |
+
)
|
361 |
+
},
|
362 |
+
)
|
363 |
+
eval_generation_steps: Optional[int] = field(
|
364 |
+
default=None,
|
365 |
+
metadata={
|
366 |
+
"help": (
|
367 |
+
"Number of update steps between two generation evaluation. Will default to the same"
|
368 |
+
"value as `eval_steps` if not set. Should be an integer and a multiple of `eval_steps`."
|
369 |
+
)
|
370 |
+
},
|
371 |
+
)
|
372 |
+
codebook_weights: Optional[List[float]] = field(
|
373 |
+
default=None,
|
374 |
+
metadata={"help": "Weights applied to each codebook."},
|
375 |
+
)
|
parler-tts/training/data.py
ADDED
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from dataclasses import dataclass
|
3 |
+
from typing import Dict, List, Optional, Set, Union
|
4 |
+
|
5 |
+
import datasets
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
from accelerate import Accelerator
|
9 |
+
from datasets import Dataset, IterableDataset, concatenate_datasets, interleave_datasets, load_dataset
|
10 |
+
from tqdm import tqdm
|
11 |
+
from transformers import AutoFeatureExtractor, AutoTokenizer
|
12 |
+
|
13 |
+
|
14 |
+
@dataclass
|
15 |
+
class DataCollatorEncodecWithPadding:
|
16 |
+
"""
|
17 |
+
Data collator that will dynamically pad the inputs received to the longest sequence in the batch or
|
18 |
+
to `max_length` if `max_length` is set and `padding=max_length`.
|
19 |
+
"""
|
20 |
+
|
21 |
+
feature_extractor: AutoFeatureExtractor
|
22 |
+
audio_column_name: str
|
23 |
+
feature_extractor_input_name: Optional[str] = "input_values"
|
24 |
+
max_length: Optional[int] = None
|
25 |
+
padding: Optional[str] = "longest"
|
26 |
+
|
27 |
+
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
28 |
+
# split inputs and labels since they have to be of different lengths and need
|
29 |
+
# different padding methods
|
30 |
+
audios = [feature[self.audio_column_name]["array"] for feature in features]
|
31 |
+
len_audio = [len(audio) for audio in audios]
|
32 |
+
if self.max_length is not None:
|
33 |
+
audios = [audio[: min(l, self.max_length)] for audio, l in zip(audios, len_audio)]
|
34 |
+
|
35 |
+
# since resampling has already been performed in the 'load_multiple_datasets' function,
|
36 |
+
# a fixed sampling_rate(44100hz) is passed to the feature_extractor.
|
37 |
+
sampling_rate = self.feature_extractor.sampling_rate
|
38 |
+
batch = self.feature_extractor(
|
39 |
+
audios, sampling_rate=sampling_rate, return_tensors="pt", padding=self.padding, max_length=self.max_length
|
40 |
+
)
|
41 |
+
batch["len_audio"] = torch.tensor(len_audio).unsqueeze(1)
|
42 |
+
return batch
|
43 |
+
|
44 |
+
|
45 |
+
@dataclass
|
46 |
+
class DataCollatorParlerTTSWithPadding:
|
47 |
+
"""
|
48 |
+
Data collator that will dynamically pad the inputs received.
|
49 |
+
Args:
|
50 |
+
prompt_tokenizer (:class:`~transformers.AutoTokenizer`)
|
51 |
+
The prompt_tokenizer used for proccessing the data.
|
52 |
+
description_tokenizer (:class:`~transformers.AutoTokenizer`)
|
53 |
+
The description_tokenizer used for proccessing the data.
|
54 |
+
padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`):
|
55 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
|
56 |
+
among:
|
57 |
+
* :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
58 |
+
sequence if provided).
|
59 |
+
* :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the
|
60 |
+
maximum acceptable input length for the model if that argument is not provided.
|
61 |
+
* :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of
|
62 |
+
different lengths).
|
63 |
+
pad_to_multiple_of (:obj:`int`, `optional`):
|
64 |
+
If set will pad the sequence to a multiple of the provided value.
|
65 |
+
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
|
66 |
+
7.5 (Volta).
|
67 |
+
"""
|
68 |
+
|
69 |
+
prompt_tokenizer: AutoTokenizer
|
70 |
+
description_tokenizer: AutoTokenizer
|
71 |
+
padding: Union[bool, str] = "longest"
|
72 |
+
pad_to_multiple_of: Optional[int] = None
|
73 |
+
prompt_max_length: Optional[int] = None
|
74 |
+
description_max_length: Optional[int] = None
|
75 |
+
audio_max_length: Optional[int] = None
|
76 |
+
|
77 |
+
def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
|
78 |
+
# split inputs and labels since they have to be of different lengths and need
|
79 |
+
# different padding methods
|
80 |
+
|
81 |
+
labels = [torch.tensor(feature["labels"]).transpose(0, 1) for feature in features]
|
82 |
+
# (bsz, seq_len, num_codebooks)
|
83 |
+
labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=-100)
|
84 |
+
if self.audio_max_length is not None and self.padding == "max_length":
|
85 |
+
labels = torch.nn.functional.pad(
|
86 |
+
labels, pad=(0, 0, 0, max(self.audio_max_length - labels.shape[1], 0)), value=-100
|
87 |
+
)
|
88 |
+
|
89 |
+
input_ids = [{"input_ids": feature["input_ids"]} for feature in features]
|
90 |
+
|
91 |
+
input_ids = self.description_tokenizer.pad(
|
92 |
+
input_ids,
|
93 |
+
return_tensors="pt",
|
94 |
+
padding=self.padding,
|
95 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
96 |
+
max_length=self.description_max_length,
|
97 |
+
)
|
98 |
+
|
99 |
+
batch = {"labels": labels, **input_ids}
|
100 |
+
|
101 |
+
prompt_input_ids = [{"input_ids": feature["prompt_input_ids"]} for feature in features]
|
102 |
+
prompt_input_ids = self.prompt_tokenizer.pad(
|
103 |
+
prompt_input_ids,
|
104 |
+
return_tensors="pt",
|
105 |
+
padding=self.padding,
|
106 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
107 |
+
max_length=self.prompt_max_length,
|
108 |
+
)
|
109 |
+
|
110 |
+
batch["prompt_input_ids"] = prompt_input_ids["input_ids"]
|
111 |
+
if "attention_mask" in prompt_input_ids:
|
112 |
+
batch["prompt_attention_mask"] = prompt_input_ids["attention_mask"]
|
113 |
+
|
114 |
+
return batch
|
115 |
+
|
116 |
+
|
117 |
+
def convert_dataset_str_to_list(
|
118 |
+
dataset_names,
|
119 |
+
dataset_config_names,
|
120 |
+
metadata_dataset_names=None,
|
121 |
+
splits=None,
|
122 |
+
dataset_samples=None,
|
123 |
+
default_split="train",
|
124 |
+
):
|
125 |
+
if isinstance(dataset_names, str):
|
126 |
+
dataset_names = dataset_names.split("+")
|
127 |
+
dataset_config_names = dataset_config_names.split("+")
|
128 |
+
splits = splits.split("+") if splits is not None else None
|
129 |
+
dataset_samples = dataset_samples.split("+") if dataset_samples is not None else None
|
130 |
+
metadata_dataset_names = metadata_dataset_names.split("+") if metadata_dataset_names is not None else None
|
131 |
+
|
132 |
+
# basic checks to ensure we've got the right number of datasets/configs/splits/columns/probs
|
133 |
+
if len(dataset_names) != len(dataset_config_names):
|
134 |
+
raise ValueError(
|
135 |
+
f"Ensure one config is passed for each dataset, got {len(dataset_names)} datasets and"
|
136 |
+
f" {len(dataset_config_names)} configs."
|
137 |
+
)
|
138 |
+
|
139 |
+
if splits is not None and len(splits) != len(dataset_names):
|
140 |
+
raise ValueError(
|
141 |
+
f"Ensure one split is passed for each dataset, got {len(dataset_names)} datasets and {len(splits)} splits."
|
142 |
+
)
|
143 |
+
|
144 |
+
if metadata_dataset_names is not None and len(metadata_dataset_names) != len(dataset_names):
|
145 |
+
raise ValueError(
|
146 |
+
f"Ensure one metadata dataset is passed for each dataset, got {len(dataset_names)} datasets and {len(metadata_dataset_names)} metadata datasets."
|
147 |
+
)
|
148 |
+
|
149 |
+
if dataset_samples is not None:
|
150 |
+
if len(dataset_samples) != len(dataset_names):
|
151 |
+
raise ValueError(
|
152 |
+
f"Ensure one sample is passed for each dataset, got {len(dataset_names)} datasets and "
|
153 |
+
f"{len(dataset_samples)} samples."
|
154 |
+
)
|
155 |
+
dataset_samples = [float(ds_sample) for ds_sample in dataset_samples]
|
156 |
+
else:
|
157 |
+
dataset_samples = [None] * len(dataset_names)
|
158 |
+
|
159 |
+
splits = splits if splits is not None else [default_split for _ in range(len(dataset_names))]
|
160 |
+
|
161 |
+
dataset_names_dict = []
|
162 |
+
for i, ds_name in enumerate(dataset_names):
|
163 |
+
dataset_names_dict.append(
|
164 |
+
{
|
165 |
+
"name": ds_name,
|
166 |
+
"config": dataset_config_names[i],
|
167 |
+
"split": splits[i],
|
168 |
+
"metadata_dataset_name": metadata_dataset_names[i],
|
169 |
+
"samples": dataset_samples[i],
|
170 |
+
}
|
171 |
+
)
|
172 |
+
return dataset_names_dict
|
173 |
+
|
174 |
+
|
175 |
+
def load_multiple_datasets(
|
176 |
+
accelerator: Accelerator,
|
177 |
+
dataset_names: Union[List, str],
|
178 |
+
dataset_config_names: Union[List, str],
|
179 |
+
metadata_dataset_names: Optional[str] = None,
|
180 |
+
splits: Optional[Union[List, str]] = None,
|
181 |
+
label_column_names: Optional[List] = None,
|
182 |
+
stopping_strategy: Optional[str] = "first_exhausted",
|
183 |
+
dataset_samples: Optional[Union[List, np.array]] = None,
|
184 |
+
streaming: Optional[bool] = False,
|
185 |
+
seed: Optional[int] = None,
|
186 |
+
id_column_name: Optional[str] = None,
|
187 |
+
columns_to_keep: Optional[Set[str]] = None,
|
188 |
+
prompt_column_name: Optional[str] = None,
|
189 |
+
sampling_rate: Optional[int] = None,
|
190 |
+
audio_column_name: Optional[str] = None,
|
191 |
+
logger: Optional[logging.Logger] = None,
|
192 |
+
**kwargs,
|
193 |
+
) -> Union[Dataset, IterableDataset]:
|
194 |
+
dataset_names_dict = convert_dataset_str_to_list(
|
195 |
+
dataset_names, dataset_config_names, metadata_dataset_names, splits, label_column_names, dataset_samples
|
196 |
+
)
|
197 |
+
|
198 |
+
if dataset_samples is not None:
|
199 |
+
dataset_samples = [ds_dict["samples"] for ds_dict in dataset_names_dict]
|
200 |
+
probabilities = np.array(dataset_samples) / np.sum(dataset_samples)
|
201 |
+
else:
|
202 |
+
probabilities = None
|
203 |
+
|
204 |
+
all_datasets = []
|
205 |
+
# iterate over the datasets we want to interleave
|
206 |
+
for dataset_dict in tqdm(dataset_names_dict, desc="Combining datasets..."):
|
207 |
+
with accelerator.local_main_process_first():
|
208 |
+
dataset = load_dataset(
|
209 |
+
dataset_dict["name"],
|
210 |
+
dataset_dict["config"],
|
211 |
+
split=dataset_dict["split"],
|
212 |
+
streaming=streaming,
|
213 |
+
**kwargs,
|
214 |
+
)
|
215 |
+
dataset_features = dataset.features.keys()
|
216 |
+
|
217 |
+
if sampling_rate is not None and audio_column_name is not None:
|
218 |
+
# resample target audio
|
219 |
+
dataset = dataset.cast_column(audio_column_name, datasets.features.Audio(sampling_rate=sampling_rate))
|
220 |
+
|
221 |
+
metadata_dataset_name = dataset_dict["metadata_dataset_name"]
|
222 |
+
if metadata_dataset_name is not None:
|
223 |
+
logger.info(
|
224 |
+
f'Merging {dataset_dict["name"]} - {dataset_dict["split"]} with {metadata_dataset_name} - {dataset_dict["split"]}'
|
225 |
+
)
|
226 |
+
metadata_dataset = load_dataset(
|
227 |
+
metadata_dataset_name,
|
228 |
+
dataset_dict["config"],
|
229 |
+
split=dataset_dict["split"],
|
230 |
+
streaming=streaming,
|
231 |
+
**kwargs,
|
232 |
+
)
|
233 |
+
|
234 |
+
# TODO(YL): I forgot to create unique ids for MLS english.
|
235 |
+
# To iterate faster, I bypass the original id check and do another one. - Done once because assuming it won't change next time
|
236 |
+
# if dataset_dict["name"] == "parler-tts/mls_eng_10k":
|
237 |
+
# def concat_ids(book_id, speaker_id, begin_time):
|
238 |
+
# return {"id": f"{book_id}_{speaker_id}_{str(begin_time).replace('.', '_')}"}
|
239 |
+
# dataset = dataset.map(concat_ids, input_columns=["book_id", "speaker_id", "begin_time"], num_proc=24)
|
240 |
+
# metadata_dataset = metadata_dataset.map(concat_ids, input_columns=["book_id", "speaker_id", "begin_time"], num_proc=24)
|
241 |
+
# metadata_dataset = metadata_dataset.rename_column(id_column_name, f"metadata_{id_column_name}")
|
242 |
+
|
243 |
+
if dataset_dict["name"] not in {"parler-tts/mls_eng_10k", "parler-tts/mls_eng"}:
|
244 |
+
if id_column_name is not None and id_column_name not in dataset.column_names:
|
245 |
+
raise ValueError(
|
246 |
+
f"id_column_name={id_column_name} but has not been found in the dataset columns"
|
247 |
+
f"- one of {', '.join(list(dataset.column_names))}."
|
248 |
+
)
|
249 |
+
if id_column_name is not None and id_column_name not in metadata_dataset.column_names:
|
250 |
+
raise ValueError(
|
251 |
+
f"id_column_name={id_column_name} but has not been found in the metadata dataset columns"
|
252 |
+
f"- one of {', '.join(list(metadata_dataset.column_names))}."
|
253 |
+
)
|
254 |
+
elif id_column_name is not None:
|
255 |
+
metadata_dataset = metadata_dataset.rename_column(id_column_name, f"metadata_{id_column_name}")
|
256 |
+
|
257 |
+
metadata_columns_to_remove = set(metadata_dataset.column_names).intersection(set(dataset.column_names))
|
258 |
+
|
259 |
+
if prompt_column_name is not None:
|
260 |
+
# We might have applied some transformations to the prompts (e.g punctuation restoration)
|
261 |
+
# so we make sure to remove it from the original dataset
|
262 |
+
if prompt_column_name in dataset.column_names:
|
263 |
+
logger.info(
|
264 |
+
f"REMOVE {prompt_column_name} from dataset {dataset_dict['name']} - dataset_dict['split']"
|
265 |
+
)
|
266 |
+
dataset.remove_columns(prompt_column_name)
|
267 |
+
|
268 |
+
metadata_columns_to_remove = set(metadata_dataset.column_names).intersection(set(dataset.column_names))
|
269 |
+
metadata_dataset = metadata_dataset.remove_columns(metadata_columns_to_remove)
|
270 |
+
|
271 |
+
dataset = concatenate_datasets([dataset, metadata_dataset], axis=1)
|
272 |
+
|
273 |
+
if id_column_name is not None and dataset_dict["name"] not in {
|
274 |
+
"parler-tts/mls_eng_10k",
|
275 |
+
"parler-tts/mls_eng",
|
276 |
+
}:
|
277 |
+
if (
|
278 |
+
len(
|
279 |
+
dataset.filter(
|
280 |
+
lambda id1, id2: id1 != id2,
|
281 |
+
input_columns=[id_column_name, f"metadata_{id_column_name}"],
|
282 |
+
)
|
283 |
+
)
|
284 |
+
!= 0
|
285 |
+
):
|
286 |
+
raise ValueError(
|
287 |
+
f"Concatenate didn't work. Some ids don't correspond on dataset {dataset_dict['name']}"
|
288 |
+
)
|
289 |
+
|
290 |
+
dataset_features = dataset.features.keys()
|
291 |
+
|
292 |
+
if columns_to_keep is not None:
|
293 |
+
dataset = dataset.remove_columns(set(dataset_features - columns_to_keep))
|
294 |
+
all_datasets.append(dataset)
|
295 |
+
|
296 |
+
if len(all_datasets) == 1:
|
297 |
+
# we have a single dataset so just return it as is
|
298 |
+
return all_datasets[0]
|
299 |
+
|
300 |
+
if streaming:
|
301 |
+
interleaved_dataset = interleave_datasets(
|
302 |
+
all_datasets,
|
303 |
+
stopping_strategy=stopping_strategy,
|
304 |
+
probabilities=probabilities,
|
305 |
+
seed=seed,
|
306 |
+
)
|
307 |
+
else:
|
308 |
+
with accelerator.local_main_process_first():
|
309 |
+
interleaved_dataset = concatenate_datasets(all_datasets)
|
310 |
+
|
311 |
+
return interleaved_dataset
|
parler-tts/training/eval.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torchaudio.pipelines import SQUIM_OBJECTIVE
|
3 |
+
import torchaudio
|
4 |
+
import evaluate
|
5 |
+
from transformers import (
|
6 |
+
AutoModel,
|
7 |
+
AutoProcessor,
|
8 |
+
pipeline,
|
9 |
+
WhisperForConditionalGeneration,
|
10 |
+
WhisperTokenizer,
|
11 |
+
WhisperTokenizerFast,
|
12 |
+
)
|
13 |
+
from accelerate.utils.memory import release_memory
|
14 |
+
import numpy as np
|
15 |
+
|
16 |
+
|
17 |
+
def clap_similarity(clap_model_name_or_path, texts, audios, device, input_sampling_rate=44100):
|
18 |
+
clap = AutoModel.from_pretrained(clap_model_name_or_path)
|
19 |
+
clap_processor = AutoProcessor.from_pretrained(clap_model_name_or_path)
|
20 |
+
output_sampling_rate = clap_processor.feature_extractor.sampling_rate
|
21 |
+
if input_sampling_rate != output_sampling_rate:
|
22 |
+
audios = [
|
23 |
+
torchaudio.functional.resample(torch.from_numpy(audio), input_sampling_rate, output_sampling_rate).numpy()
|
24 |
+
for audio in audios
|
25 |
+
]
|
26 |
+
clap_inputs = clap_processor(
|
27 |
+
text=texts, audios=audios, padding=True, return_tensors="pt", sampling_rate=output_sampling_rate
|
28 |
+
).to(device)
|
29 |
+
|
30 |
+
clap.to(device)
|
31 |
+
with torch.no_grad():
|
32 |
+
text_features = clap.get_text_features(
|
33 |
+
clap_inputs["input_ids"], attention_mask=clap_inputs.get("attention_mask", None)
|
34 |
+
)
|
35 |
+
audio_features = clap.get_audio_features(clap_inputs["input_features"])
|
36 |
+
|
37 |
+
cosine_sim = torch.nn.functional.cosine_similarity(audio_features, text_features, dim=1, eps=1e-8).mean()
|
38 |
+
|
39 |
+
cosine_sim = cosine_sim.to("cpu")
|
40 |
+
|
41 |
+
clap.to("cpu")
|
42 |
+
clap, clap_inputs, audio_features, text_features = release_memory(clap, clap_inputs, audio_features, text_features)
|
43 |
+
return cosine_sim
|
44 |
+
|
45 |
+
|
46 |
+
def si_sdr(audios, device, input_sampling_rate=44100):
|
47 |
+
max_audio_length = 15 * SQUIM_OBJECTIVE.sample_rate
|
48 |
+
model = SQUIM_OBJECTIVE.get_model().to((device))
|
49 |
+
|
50 |
+
output_sampling_rate = SQUIM_OBJECTIVE.sample_rate
|
51 |
+
if input_sampling_rate != output_sampling_rate:
|
52 |
+
audios = [
|
53 |
+
torchaudio.functional.resample(
|
54 |
+
torch.tensor(audio)[None, :].to(device).float(), input_sampling_rate, output_sampling_rate
|
55 |
+
)
|
56 |
+
for audio in audios
|
57 |
+
]
|
58 |
+
|
59 |
+
def apply_squim(waveform):
|
60 |
+
with torch.no_grad():
|
61 |
+
waveform = waveform[:, : min(max_audio_length, waveform.shape[1])]
|
62 |
+
_, _, sdr_sample = model(waveform)
|
63 |
+
sdr_sample = sdr_sample.cpu()[0]
|
64 |
+
return sdr_sample
|
65 |
+
|
66 |
+
si_sdrs = [apply_squim(audio) for audio in audios]
|
67 |
+
audios, model = release_memory(audios, model)
|
68 |
+
return si_sdrs
|
69 |
+
|
70 |
+
|
71 |
+
def wer(
|
72 |
+
asr_model_name_or_path,
|
73 |
+
prompts,
|
74 |
+
audios,
|
75 |
+
device,
|
76 |
+
per_device_eval_batch_size,
|
77 |
+
sampling_rate,
|
78 |
+
noise_level_to_compute_clean_wer,
|
79 |
+
si_sdr_measures,
|
80 |
+
):
|
81 |
+
metric = evaluate.load("wer")
|
82 |
+
asr_pipeline = pipeline(model=asr_model_name_or_path, device=device, chunk_length_s=25.0)
|
83 |
+
|
84 |
+
return_language = None
|
85 |
+
if isinstance(asr_pipeline.model, WhisperForConditionalGeneration):
|
86 |
+
return_language = True
|
87 |
+
|
88 |
+
transcriptions = asr_pipeline(
|
89 |
+
[{"raw": audio, "sampling_rate": sampling_rate} for audio in audios],
|
90 |
+
batch_size=int(per_device_eval_batch_size),
|
91 |
+
return_language=return_language,
|
92 |
+
)
|
93 |
+
|
94 |
+
if isinstance(asr_pipeline.tokenizer, (WhisperTokenizer, WhisperTokenizerFast)):
|
95 |
+
tokenizer = asr_pipeline.tokenizer
|
96 |
+
else:
|
97 |
+
tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-large-v3")
|
98 |
+
|
99 |
+
english_normalizer = tokenizer.normalize
|
100 |
+
basic_normalizer = tokenizer.basic_normalize
|
101 |
+
|
102 |
+
normalized_predictions = []
|
103 |
+
normalized_references = []
|
104 |
+
|
105 |
+
for pred, ref in zip(transcriptions, prompts):
|
106 |
+
normalizer = (
|
107 |
+
english_normalizer
|
108 |
+
if isinstance(pred.get("chunks", None), list) and pred["chunks"][0].get("language", None) == "english"
|
109 |
+
else basic_normalizer
|
110 |
+
)
|
111 |
+
norm_ref = normalizer(ref)
|
112 |
+
if len(norm_ref) > 0:
|
113 |
+
norm_pred = normalizer(pred["text"])
|
114 |
+
normalized_predictions.append(norm_pred)
|
115 |
+
normalized_references.append(norm_ref)
|
116 |
+
|
117 |
+
word_error = 100
|
118 |
+
clean_word_error = None
|
119 |
+
noisy_word_error = None
|
120 |
+
percent_clean_samples = 0
|
121 |
+
if len(normalized_references) > 0:
|
122 |
+
word_error = 100 * metric.compute(predictions=normalized_predictions, references=normalized_references)
|
123 |
+
|
124 |
+
|
125 |
+
if noise_level_to_compute_clean_wer and si_sdr_measures:
|
126 |
+
si_sdr_measures = np.array(si_sdr_measures)
|
127 |
+
mask = si_sdr_measures >= noise_level_to_compute_clean_wer
|
128 |
+
if mask.any():
|
129 |
+
clean_word_error = 100 * metric.compute(
|
130 |
+
predictions=np.array(normalized_predictions)[mask], references=np.array(normalized_references)[mask]
|
131 |
+
)
|
132 |
+
if not mask.all():
|
133 |
+
noisy_word_error = 100 * metric.compute(
|
134 |
+
predictions=np.array(normalized_predictions)[~mask], references=np.array(normalized_references)[~mask]
|
135 |
+
)
|
136 |
+
else:
|
137 |
+
noisy_word_error = 0
|
138 |
+
percent_clean_samples = mask.sum() / len(mask)
|
139 |
+
|
140 |
+
asr_pipeline.model.to("cpu")
|
141 |
+
asr_pipeline = release_memory(asr_pipeline)
|
142 |
+
return word_error, [t["text"] for t in transcriptions], clean_word_error, noisy_word_error, percent_clean_samples
|
parler-tts/training/run_parler_tts_training.py
ADDED
@@ -0,0 +1,1249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding=utf-8
|
3 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
|
17 |
+
""" Train Parler-TTS using 🤗 Accelerate"""
|
18 |
+
|
19 |
+
import logging
|
20 |
+
import os
|
21 |
+
import re
|
22 |
+
import sys
|
23 |
+
import time
|
24 |
+
import math
|
25 |
+
import contextlib
|
26 |
+
from multiprocess import set_start_method
|
27 |
+
from datetime import timedelta
|
28 |
+
import inspect
|
29 |
+
from tqdm import tqdm
|
30 |
+
from pathlib import Path
|
31 |
+
|
32 |
+
import torch
|
33 |
+
from torch.utils.data import DataLoader
|
34 |
+
|
35 |
+
import datasets
|
36 |
+
from datasets import DatasetDict, Dataset, IterableDataset, concatenate_datasets
|
37 |
+
|
38 |
+
from huggingface_hub import HfApi
|
39 |
+
|
40 |
+
import transformers
|
41 |
+
from transformers import AutoFeatureExtractor, AutoTokenizer, HfArgumentParser
|
42 |
+
from transformers.trainer_pt_utils import LengthGroupedSampler
|
43 |
+
from transformers.optimization import get_scheduler
|
44 |
+
from transformers.utils import send_example_telemetry
|
45 |
+
|
46 |
+
|
47 |
+
from accelerate import Accelerator, skip_first_batches
|
48 |
+
from accelerate.utils import set_seed, AutocastKwargs, InitProcessGroupKwargs, TorchDynamoPlugin, DistributedDataParallelKwargs
|
49 |
+
from accelerate.utils.memory import release_memory
|
50 |
+
|
51 |
+
from parler_tts import (
|
52 |
+
ParlerTTSConfig,
|
53 |
+
ParlerTTSForConditionalGeneration,
|
54 |
+
build_delay_pattern_mask,
|
55 |
+
)
|
56 |
+
|
57 |
+
from training.utils import (
|
58 |
+
get_last_checkpoint,
|
59 |
+
rotate_checkpoints,
|
60 |
+
log_pred,
|
61 |
+
log_metric,
|
62 |
+
load_all_codec_checkpoints,
|
63 |
+
save_codec_checkpoint,
|
64 |
+
get_last_codec_checkpoint_step,
|
65 |
+
)
|
66 |
+
from training.arguments import ModelArguments, DataTrainingArguments, ParlerTTSTrainingArguments
|
67 |
+
from training.data import load_multiple_datasets, DataCollatorParlerTTSWithPadding, DataCollatorEncodecWithPadding
|
68 |
+
from training.eval import clap_similarity, wer, si_sdr
|
69 |
+
|
70 |
+
logger = logging.getLogger(__name__)
|
71 |
+
|
72 |
+
|
73 |
+
def main():
|
74 |
+
# See all possible arguments in src/transformers/training_args.py
|
75 |
+
# or by passing the --help flag to this script.
|
76 |
+
# We now keep distinct sets of args, for a cleaner separation of concerns.
|
77 |
+
|
78 |
+
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, ParlerTTSTrainingArguments))
|
79 |
+
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
|
80 |
+
# If we pass only one argument to the script and it's the path to a json file,
|
81 |
+
# let's parse it to get our arguments.
|
82 |
+
model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
|
83 |
+
else:
|
84 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
85 |
+
|
86 |
+
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
|
87 |
+
# information sent is the one passed as arguments along with your Python/PyTorch versions.
|
88 |
+
send_example_telemetry("run_parler_tts", model_args, data_args)
|
89 |
+
|
90 |
+
if training_args.dtype == "float16":
|
91 |
+
mixed_precision = "fp16"
|
92 |
+
torch_dtype = torch.float16
|
93 |
+
elif training_args.dtype == "bfloat16":
|
94 |
+
mixed_precision = "bf16"
|
95 |
+
torch_dtype = torch.bfloat16
|
96 |
+
else:
|
97 |
+
mixed_precision = "no"
|
98 |
+
torch_dtype = torch.float32
|
99 |
+
|
100 |
+
if data_args.pad_to_max_length and (
|
101 |
+
data_args.max_duration_in_seconds is None
|
102 |
+
or data_args.max_prompt_token_length is None
|
103 |
+
or data_args.max_description_token_length is None
|
104 |
+
):
|
105 |
+
raise ValueError(
|
106 |
+
"`pad_to_max_length` is `True` but one of the following parameters has not been set: `max_duration_in_seconds`, `max_prompt_token_length`, `max_description_token_length`"
|
107 |
+
)
|
108 |
+
|
109 |
+
padding = "max_length" if data_args.pad_to_max_length else "longest"
|
110 |
+
|
111 |
+
####### A. Preparation
|
112 |
+
kwargs_handlers = [InitProcessGroupKwargs(timeout=timedelta(minutes=120)), DistributedDataParallelKwargs(find_unused_parameters=False)]
|
113 |
+
|
114 |
+
accelerator = Accelerator(
|
115 |
+
gradient_accumulation_steps=training_args.gradient_accumulation_steps,
|
116 |
+
mixed_precision=mixed_precision,
|
117 |
+
log_with=training_args.report_to,
|
118 |
+
project_dir=training_args.output_dir,
|
119 |
+
kwargs_handlers=kwargs_handlers,
|
120 |
+
)
|
121 |
+
|
122 |
+
accelerator.init_trackers(
|
123 |
+
project_name=data_args.wandb_project,
|
124 |
+
config={
|
125 |
+
"learning_rate": training_args.learning_rate,
|
126 |
+
"model_name_or_path": model_args.model_name_or_path,
|
127 |
+
"num_train_epochs": training_args.num_train_epochs,
|
128 |
+
"gradient_accumulation_steps": training_args.gradient_accumulation_steps,
|
129 |
+
"per_device_train_batch_size": training_args.per_device_train_batch_size,
|
130 |
+
"global_batch_size": training_args.per_device_train_batch_size * accelerator.num_processes,
|
131 |
+
"mixed_precision": mixed_precision,
|
132 |
+
"lr_scheduler_type": training_args.lr_scheduler_type,
|
133 |
+
"warmup_steps": training_args.warmup_steps,
|
134 |
+
"freeze_text_encoder": model_args.freeze_text_encoder,
|
135 |
+
"max_duration_in_seconds": data_args.max_duration_in_seconds,
|
136 |
+
"weight_decay": training_args.weight_decay,
|
137 |
+
"adam_beta1": training_args.adam_beta1,
|
138 |
+
"adam_beta2": training_args.adam_beta2,
|
139 |
+
"temperature": model_args.temperature,
|
140 |
+
},
|
141 |
+
init_kwargs={"wandb": {"name": data_args.wandb_run_name}} if data_args.wandb_run_name else {},
|
142 |
+
)
|
143 |
+
|
144 |
+
# Detecting last checkpoint and eventually continue from last checkpoint
|
145 |
+
last_checkpoint = None
|
146 |
+
if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
|
147 |
+
last_checkpoint = get_last_checkpoint(training_args.output_dir)
|
148 |
+
if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
|
149 |
+
raise ValueError(
|
150 |
+
f"Output directory ({training_args.output_dir}) already exists and is not empty. "
|
151 |
+
"Use --overwrite_output_dir to overcome."
|
152 |
+
)
|
153 |
+
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
|
154 |
+
logger.info(
|
155 |
+
f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
|
156 |
+
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
|
157 |
+
)
|
158 |
+
|
159 |
+
# Setup logging
|
160 |
+
logging.basicConfig(
|
161 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
162 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
163 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
164 |
+
)
|
165 |
+
logger.setLevel(logging.INFO if accelerator.is_main_process else logging.WARN)
|
166 |
+
|
167 |
+
# Log a small summary on each proces
|
168 |
+
logger.warning(
|
169 |
+
f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, "
|
170 |
+
f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
|
171 |
+
)
|
172 |
+
|
173 |
+
# Set the verbosity to info of the Transformers logger (on main process only)
|
174 |
+
if accelerator.is_local_main_process:
|
175 |
+
datasets.utils.logging.set_verbosity_warning()
|
176 |
+
transformers.utils.logging.set_verbosity_info()
|
177 |
+
else:
|
178 |
+
datasets.utils.logging.set_verbosity_error()
|
179 |
+
transformers.utils.logging.set_verbosity_error()
|
180 |
+
|
181 |
+
logger.info("Training/evaluation parameters %s", training_args)
|
182 |
+
|
183 |
+
# Set seed before initializing model.
|
184 |
+
set_seed(training_args.seed)
|
185 |
+
num_workers = data_args.preprocessing_num_workers
|
186 |
+
|
187 |
+
# 1. First, lett's instantiate the feature extractor, tokenizers and model
|
188 |
+
# Note for distributed training, the .from_pretrained methods guarantee that only
|
189 |
+
# one local process can concurrently download model & vocab.
|
190 |
+
|
191 |
+
# load feature extractor
|
192 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(
|
193 |
+
model_args.feature_extractor_name or model_args.model_name_or_path,
|
194 |
+
cache_dir=model_args.cache_dir,
|
195 |
+
token=data_args.token,
|
196 |
+
trust_remote_code=data_args.trust_remote_code,
|
197 |
+
)
|
198 |
+
sampling_rate = feature_extractor.sampling_rate
|
199 |
+
|
200 |
+
# load prompt tokenizer
|
201 |
+
prompt_tokenizer = AutoTokenizer.from_pretrained(
|
202 |
+
model_args.prompt_tokenizer_name or model_args.description_tokenizer_name or model_args.model_name_or_path,
|
203 |
+
cache_dir=model_args.cache_dir,
|
204 |
+
token=data_args.token,
|
205 |
+
trust_remote_code=data_args.trust_remote_code,
|
206 |
+
use_fast=model_args.use_fast_tokenizer,
|
207 |
+
padding_side=model_args.prompt_padding_side,
|
208 |
+
)
|
209 |
+
|
210 |
+
# load description tokenizer
|
211 |
+
description_tokenizer = AutoTokenizer.from_pretrained(
|
212 |
+
model_args.description_tokenizer_name or model_args.model_name_or_path,
|
213 |
+
cache_dir=model_args.cache_dir,
|
214 |
+
token=data_args.token,
|
215 |
+
trust_remote_code=data_args.trust_remote_code,
|
216 |
+
use_fast=model_args.use_fast_tokenizer,
|
217 |
+
)
|
218 |
+
|
219 |
+
if model_args.use_fast_tokenizer:
|
220 |
+
logger.warning(
|
221 |
+
"Disabling fast tokenizer warning: https://github.com/huggingface/transformers/blob/main/src/transformers/tokenization_utils_base.py#L3231-L3235"
|
222 |
+
)
|
223 |
+
prompt_tokenizer.deprecation_warnings["Asking-to-pad-a-fast-tokenizer"] = True
|
224 |
+
description_tokenizer.deprecation_warnings["Asking-to-pad-a-fast-tokenizer"] = True
|
225 |
+
|
226 |
+
# 2. Now, let's load the dataset
|
227 |
+
|
228 |
+
if data_args.save_to_disk is not None:
|
229 |
+
os.makedirs(data_args.save_to_disk, exist_ok=True)
|
230 |
+
|
231 |
+
# assume that the dataset has been saved to `save_to_disk` if the latter is not empty
|
232 |
+
dataset_was_precomputed = len(os.listdir(data_args.save_to_disk)) > 0
|
233 |
+
if dataset_was_precomputed:
|
234 |
+
with accelerator.local_main_process_first():
|
235 |
+
vectorized_datasets = datasets.load_from_disk(data_args.save_to_disk)
|
236 |
+
else:
|
237 |
+
raw_datasets = DatasetDict()
|
238 |
+
|
239 |
+
columns_to_keep = {
|
240 |
+
"target_audio_column_name": data_args.target_audio_column_name,
|
241 |
+
"prompt_column_name": data_args.prompt_column_name,
|
242 |
+
}
|
243 |
+
if data_args.description_column_name is not None:
|
244 |
+
columns_to_keep["description_column_name"] = data_args.description_column_name
|
245 |
+
|
246 |
+
if training_args.do_train:
|
247 |
+
raw_datasets["train"] = load_multiple_datasets(
|
248 |
+
accelerator,
|
249 |
+
data_args.train_dataset_name,
|
250 |
+
data_args.train_dataset_config_name,
|
251 |
+
metadata_dataset_names=data_args.train_metadata_dataset_name,
|
252 |
+
splits=data_args.train_split_name,
|
253 |
+
dataset_samples=data_args.train_dataset_samples,
|
254 |
+
seed=training_args.seed,
|
255 |
+
cache_dir=model_args.cache_dir,
|
256 |
+
num_proc=data_args.preprocessing_num_workers,
|
257 |
+
id_column_name=data_args.id_column_name,
|
258 |
+
columns_to_keep=columns_to_keep.values(),
|
259 |
+
prompt_column_name=data_args.prompt_column_name,
|
260 |
+
audio_column_name=data_args.target_audio_column_name,
|
261 |
+
sampling_rate=sampling_rate,
|
262 |
+
logger=logger,
|
263 |
+
# streaming=data_args.streaming, TODO(SG): optionally enable streaming mode
|
264 |
+
)
|
265 |
+
|
266 |
+
for key in columns_to_keep:
|
267 |
+
if columns_to_keep[key] not in raw_datasets["train"].column_names:
|
268 |
+
raise ValueError(
|
269 |
+
f"--{key} '{columns_to_keep[key]}' not found in dataset '{data_args.train_dataset_name}'."
|
270 |
+
f" Make sure to set `--{key}` to the correct audio column - one of"
|
271 |
+
f" {', '.join(raw_datasets['train'].column_names)}."
|
272 |
+
)
|
273 |
+
|
274 |
+
if data_args.max_train_samples is not None:
|
275 |
+
raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples))
|
276 |
+
|
277 |
+
if training_args.do_eval:
|
278 |
+
raw_datasets["eval"] = load_multiple_datasets(
|
279 |
+
accelerator,
|
280 |
+
data_args.eval_dataset_name if data_args.eval_dataset_name else data_args.train_dataset_name,
|
281 |
+
data_args.eval_dataset_config_name
|
282 |
+
if data_args.eval_dataset_config_name
|
283 |
+
else data_args.train_dataset_config_name,
|
284 |
+
metadata_dataset_names=data_args.eval_metadata_dataset_name,
|
285 |
+
splits=data_args.eval_split_name,
|
286 |
+
cache_dir=model_args.cache_dir,
|
287 |
+
num_proc=data_args.preprocessing_num_workers,
|
288 |
+
id_column_name=data_args.id_column_name,
|
289 |
+
columns_to_keep=columns_to_keep.values(),
|
290 |
+
prompt_column_name=data_args.prompt_column_name,
|
291 |
+
audio_column_name=data_args.target_audio_column_name,
|
292 |
+
sampling_rate=sampling_rate,
|
293 |
+
logger=logger,
|
294 |
+
# streaming=data_args.streaming, TODO(SG): optionally enable streaming mode
|
295 |
+
)
|
296 |
+
|
297 |
+
if data_args.max_eval_samples is not None:
|
298 |
+
with accelerator.local_main_process_first():
|
299 |
+
raw_datasets["eval"] = (
|
300 |
+
raw_datasets["eval"].shuffle(seed=training_args.seed).select(range(data_args.max_eval_samples))
|
301 |
+
)
|
302 |
+
|
303 |
+
# 3. Next, let's load the config.
|
304 |
+
config = ParlerTTSConfig.from_pretrained(
|
305 |
+
model_args.model_name_or_path,
|
306 |
+
cache_dir=model_args.cache_dir,
|
307 |
+
token=data_args.token,
|
308 |
+
trust_remote_code=data_args.trust_remote_code,
|
309 |
+
)
|
310 |
+
|
311 |
+
if training_args.codebook_weights is not None and len(training_args.codebook_weights) != config.decoder.num_codebooks:
|
312 |
+
raise ValueError(f"`codebook_weights` has length {len(training_args.codebook_weights)} when it should be of length {config.decoder.num_codebooks}.")
|
313 |
+
|
314 |
+
# update pad token id and decoder_start_token_id
|
315 |
+
config.decoder.update(
|
316 |
+
{
|
317 |
+
"cross_attention_implementation_strategy": model_args.cross_attention_implementation_strategy
|
318 |
+
if model_args.cross_attention_implementation_strategy is not None
|
319 |
+
else None,
|
320 |
+
"codebook_weights": training_args.codebook_weights if training_args.codebook_weights is not None else config.decoder.codebook_weights
|
321 |
+
}
|
322 |
+
)
|
323 |
+
config.update(
|
324 |
+
{
|
325 |
+
"pad_token_id": model_args.pad_token_id if model_args.pad_token_id is not None else config.pad_token_id,
|
326 |
+
"decoder_start_token_id": model_args.decoder_start_token_id
|
327 |
+
if model_args.decoder_start_token_id is not None
|
328 |
+
else config.decoder_start_token_id,
|
329 |
+
}
|
330 |
+
)
|
331 |
+
|
332 |
+
# create model
|
333 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained(
|
334 |
+
model_args.model_name_or_path,
|
335 |
+
cache_dir=model_args.cache_dir,
|
336 |
+
config=config,
|
337 |
+
token=data_args.token,
|
338 |
+
trust_remote_code=data_args.trust_remote_code,
|
339 |
+
attn_implementation={"decoder": model_args.attn_implementation, "text_encoder": "eager"},
|
340 |
+
)
|
341 |
+
|
342 |
+
# enable gradient checkpointing if necessary
|
343 |
+
if training_args.gradient_checkpointing:
|
344 |
+
model.gradient_checkpointing_enable()
|
345 |
+
|
346 |
+
# 4. Now we preprocess the datasets including loading the audio, resampling and normalization
|
347 |
+
# Thankfully, `datasets` takes care of automatically loading and resampling the audio,
|
348 |
+
# so that we just need to set the correct target sampling rate and normalize the input
|
349 |
+
# via the `feature_extractor`
|
350 |
+
|
351 |
+
# derive max & min input length for sample rate & max duration
|
352 |
+
sampling_rate = feature_extractor.sampling_rate
|
353 |
+
max_target_length = int(data_args.max_duration_in_seconds * sampling_rate)
|
354 |
+
min_target_length = int(data_args.min_duration_in_seconds * sampling_rate)
|
355 |
+
target_audio_column_name = data_args.target_audio_column_name
|
356 |
+
description_column_name = data_args.description_column_name
|
357 |
+
prompt_column_name = data_args.prompt_column_name
|
358 |
+
feature_extractor_input_name = feature_extractor.model_input_names[0]
|
359 |
+
audio_encoder_pad_token_id = config.decoder.pad_token_id
|
360 |
+
audio_encoder_eos_token_id = config.decoder.eos_token_id
|
361 |
+
audio_encoder_bos_token_id = model.generation_config.decoder_start_token_id
|
362 |
+
max_length = model.generation_config.max_length
|
363 |
+
num_codebooks = model.decoder.config.num_codebooks
|
364 |
+
bandwidth = model_args.bandwidth
|
365 |
+
attn_implementation = model_args.attn_implementation
|
366 |
+
|
367 |
+
# Freeze Encoders
|
368 |
+
model.freeze_encoders(model_args.freeze_text_encoder)
|
369 |
+
|
370 |
+
# Test all gather - used for warmout and avoiding timeout
|
371 |
+
logger.debug(str(accelerator.process_index), main_process_only=False, in_order=True)
|
372 |
+
test_tensor = torch.tensor([accelerator.process_index], device=accelerator.device)
|
373 |
+
gathered_tensor = accelerator.gather(test_tensor)
|
374 |
+
print("gathered_tensor", gathered_tensor)
|
375 |
+
accelerator.wait_for_everyone()
|
376 |
+
|
377 |
+
if not dataset_was_precomputed:
|
378 |
+
# Filter on text length
|
379 |
+
if description_column_name is not None and data_args.max_text_length is not None:
|
380 |
+
with accelerator.local_main_process_first():
|
381 |
+
# filter description that is shorter than max_text_length
|
382 |
+
raw_datasets = raw_datasets.filter(
|
383 |
+
lambda x: len(x) < data_args.max_text_length,
|
384 |
+
num_proc=num_workers,
|
385 |
+
input_columns=[description_column_name],
|
386 |
+
)
|
387 |
+
|
388 |
+
# Preprocessing the dataset.
|
389 |
+
# We need to tokenize the texts.
|
390 |
+
def pass_through_processors(description, prompt):
|
391 |
+
batch = {}
|
392 |
+
|
393 |
+
batch["input_ids"] = description_tokenizer(description.strip())["input_ids"]
|
394 |
+
batch["prompt_input_ids"] = prompt_tokenizer(prompt.strip())["input_ids"]
|
395 |
+
|
396 |
+
return batch
|
397 |
+
|
398 |
+
with accelerator.local_main_process_first():
|
399 |
+
# this is a trick to avoid to rewrite the entire audio column which takes ages
|
400 |
+
vectorized_datasets = raw_datasets.map(
|
401 |
+
pass_through_processors,
|
402 |
+
remove_columns=next(iter(raw_datasets.values())).column_names,
|
403 |
+
input_columns=[description_column_name, prompt_column_name],
|
404 |
+
num_proc=num_workers,
|
405 |
+
desc="preprocess datasets",
|
406 |
+
)
|
407 |
+
|
408 |
+
# We use Accelerate to perform distributed inference
|
409 |
+
# T5 doesn't support fp16
|
410 |
+
autocast_kwargs = AutocastKwargs(enabled=(mixed_precision != "fp16"))
|
411 |
+
|
412 |
+
# Now we encode the audio labels with encodec.
|
413 |
+
####### B. Encode audio
|
414 |
+
|
415 |
+
logger.info("*** Encode target audio with encodec ***")
|
416 |
+
|
417 |
+
# no need to prepare audio_decoder because used for inference without mixed precision
|
418 |
+
# see: https://huggingface.co/docs/accelerate/main/en/package_reference/accelerator#accelerate.Accelerator.prepare
|
419 |
+
if training_args.torch_compile:
|
420 |
+
audio_decoder = accelerator.prepare_model(model.audio_encoder, evaluation_mode=True)
|
421 |
+
else:
|
422 |
+
audio_decoder = model.audio_encoder
|
423 |
+
|
424 |
+
encoder_data_collator = DataCollatorEncodecWithPadding(
|
425 |
+
feature_extractor,
|
426 |
+
audio_column_name=target_audio_column_name,
|
427 |
+
feature_extractor_input_name=feature_extractor_input_name,
|
428 |
+
max_length=max_target_length,
|
429 |
+
padding=padding,
|
430 |
+
)
|
431 |
+
encoder_signature = set(inspect.signature(audio_decoder.forward).parameters)
|
432 |
+
|
433 |
+
def apply_audio_decoder(batch):
|
434 |
+
len_audio = batch.pop("len_audio")
|
435 |
+
audio_decoder.to(batch["input_values"].device).eval()
|
436 |
+
if bandwidth is not None:
|
437 |
+
batch["bandwidth"] = bandwidth
|
438 |
+
elif "num_quantizers" in encoder_signature:
|
439 |
+
batch["num_quantizers"] = num_codebooks
|
440 |
+
elif "num_codebooks" in encoder_signature:
|
441 |
+
batch["num_codebooks"] = num_codebooks
|
442 |
+
elif "n_quantizers" in encoder_signature:
|
443 |
+
batch["n_quantizers"] = num_codebooks
|
444 |
+
|
445 |
+
with torch.no_grad():
|
446 |
+
labels = audio_decoder.encode(**batch)["audio_codes"]
|
447 |
+
output = {}
|
448 |
+
output["len_audio"] = len_audio
|
449 |
+
# (1, bsz, codebooks, seq_len) -> (bsz, seq_len, codebooks)
|
450 |
+
output["labels"] = labels.squeeze(0).transpose(1, 2)
|
451 |
+
|
452 |
+
# if `pad_to_max_length`, the maximum corresponding audio length of the current batch is max_duration*sampling_rate
|
453 |
+
max_length = len_audio.max() if padding != "max_length" else max_target_length
|
454 |
+
output["ratio"] = torch.ones_like(len_audio) * labels.shape[-1] / max_length
|
455 |
+
return output
|
456 |
+
|
457 |
+
# (1, codebooks, seq_len) where seq_len=1
|
458 |
+
bos_labels = torch.ones((1, num_codebooks, 1)) * audio_encoder_bos_token_id
|
459 |
+
|
460 |
+
def postprocess_dataset(labels):
|
461 |
+
# (1, codebooks, seq_len)
|
462 |
+
labels = torch.tensor(labels).unsqueeze(0)
|
463 |
+
# add bos
|
464 |
+
labels = torch.cat([bos_labels, labels], dim=-1)
|
465 |
+
|
466 |
+
labels, delay_pattern_mask = build_delay_pattern_mask(
|
467 |
+
labels,
|
468 |
+
bos_token_id=audio_encoder_bos_token_id,
|
469 |
+
pad_token_id=audio_encoder_eos_token_id,
|
470 |
+
max_length=labels.shape[-1] + num_codebooks,
|
471 |
+
num_codebooks=num_codebooks,
|
472 |
+
)
|
473 |
+
|
474 |
+
# the first ids of the delay pattern mask are precisely labels, we use the rest of the labels mask
|
475 |
+
# to take care of EOS
|
476 |
+
# we want labels to look like this:
|
477 |
+
# - [B, a, b, E, E, E, E]
|
478 |
+
# - [B, B, c, d, E, E, E]
|
479 |
+
# - [B, B, B, e, f, E, E]
|
480 |
+
# - [B, B, B, B, g, h, E]
|
481 |
+
labels = torch.where(delay_pattern_mask == -1, audio_encoder_eos_token_id, delay_pattern_mask)
|
482 |
+
|
483 |
+
# the first timestamp is associated to a row full of BOS, let's get rid of it
|
484 |
+
# we also remove the last timestampts (full of PAD)
|
485 |
+
output = {"labels": labels[:, 1:]}
|
486 |
+
return output
|
487 |
+
|
488 |
+
for split in vectorized_datasets:
|
489 |
+
data_loader = DataLoader(
|
490 |
+
raw_datasets[split],
|
491 |
+
batch_size=training_args.audio_encoder_per_device_batch_size,
|
492 |
+
collate_fn=encoder_data_collator,
|
493 |
+
num_workers=training_args.dataloader_num_workers,
|
494 |
+
pin_memory=True,
|
495 |
+
)
|
496 |
+
data_loader = accelerator.prepare(data_loader)
|
497 |
+
total_inference_steps = len(data_loader)
|
498 |
+
|
499 |
+
start_step = get_last_codec_checkpoint_step(os.path.join(data_args.temporary_save_to_disk, split))
|
500 |
+
accelerator.wait_for_everyone()
|
501 |
+
if start_step > 0:
|
502 |
+
logger.info(f"Resuming {split} from step {start_step}")
|
503 |
+
# efficiently skip the first n batches
|
504 |
+
start_step += 1
|
505 |
+
data_loader = skip_first_batches(data_loader, start_step)
|
506 |
+
|
507 |
+
all_generated_labels = []
|
508 |
+
all_lens = []
|
509 |
+
if start_step < total_inference_steps:
|
510 |
+
for i, batch in enumerate(tqdm(data_loader, disable=not accelerator.is_local_main_process)):
|
511 |
+
cur_step = start_step + i
|
512 |
+
generate_labels = apply_audio_decoder(batch)
|
513 |
+
generate_labels = accelerator.pad_across_processes(generate_labels, dim=1, pad_index=0)
|
514 |
+
generate_labels = accelerator.gather_for_metrics(generate_labels)
|
515 |
+
|
516 |
+
if accelerator.is_main_process:
|
517 |
+
lab = generate_labels["labels"].cpu().transpose(1, 2).to(torch.int16)
|
518 |
+
rat = generate_labels["ratio"].cpu().squeeze(1)
|
519 |
+
lens = generate_labels["len_audio"].cpu().squeeze(1)
|
520 |
+
lab = [l[:, : int(ratio * length)] for (l, ratio, length) in zip(lab, rat, lens)]
|
521 |
+
|
522 |
+
all_generated_labels.extend(lab)
|
523 |
+
all_lens.extend(lens)
|
524 |
+
|
525 |
+
if ((cur_step + 1) % data_args.save_codec_steps == 0) or (
|
526 |
+
cur_step == total_inference_steps - 1
|
527 |
+
):
|
528 |
+
tmp_labels = Dataset.from_dict({"labels": all_generated_labels, "target_length": all_lens})
|
529 |
+
tmp_labels = tmp_labels.map(
|
530 |
+
postprocess_dataset,
|
531 |
+
num_proc=data_args.preprocessing_num_workers, # this one is resource consuming if many processor.
|
532 |
+
input_columns=["labels"],
|
533 |
+
desc="Postprocessing labeling",
|
534 |
+
)
|
535 |
+
save_codec_checkpoint(
|
536 |
+
os.path.join(data_args.temporary_save_to_disk, split), tmp_labels, cur_step
|
537 |
+
)
|
538 |
+
all_generated_labels = []
|
539 |
+
all_lens = []
|
540 |
+
|
541 |
+
accelerator.wait_for_everyone()
|
542 |
+
|
543 |
+
if accelerator.is_main_process and len(all_generated_labels) > 0:
|
544 |
+
tmp_labels = Dataset.from_dict({"labels": all_generated_labels, "target_length": all_lens})
|
545 |
+
tmp_labels = tmp_labels.map(
|
546 |
+
postprocess_dataset,
|
547 |
+
num_proc=data_args.preprocessing_num_workers, # this one is resource consuming if many processor.
|
548 |
+
input_columns=["labels"],
|
549 |
+
desc="Postprocessing labeling",
|
550 |
+
)
|
551 |
+
save_codec_checkpoint(os.path.join(data_args.temporary_save_to_disk, split), tmp_labels, cur_step)
|
552 |
+
all_generated_labels = []
|
553 |
+
all_lens = []
|
554 |
+
accelerator.wait_for_everyone()
|
555 |
+
|
556 |
+
del all_generated_labels
|
557 |
+
accelerator.wait_for_everyone()
|
558 |
+
|
559 |
+
with accelerator.local_main_process_first():
|
560 |
+
tmp_labels = load_all_codec_checkpoints(os.path.join(data_args.temporary_save_to_disk, split)).select(
|
561 |
+
range(len(vectorized_datasets[split]))
|
562 |
+
)
|
563 |
+
logger.info(f"Concatenating {split}: {tmp_labels} with {vectorized_datasets[split]}")
|
564 |
+
vectorized_datasets[split] = concatenate_datasets([vectorized_datasets[split], tmp_labels], axis=1)
|
565 |
+
|
566 |
+
accelerator.free_memory()
|
567 |
+
del generate_labels, all_lens
|
568 |
+
|
569 |
+
with accelerator.local_main_process_first():
|
570 |
+
# NOTE: filtering is done at the end because in the `datasets` library, caching audio files is done after most operations
|
571 |
+
# caching audio files is time and disk-space consuming, so we want to avoid it at all costs, especially for large (>1Kh) audio datasets.
|
572 |
+
# That's also why we avoid to concat the processed datasets (vectorized_datasets) with the audio column present in raw_datasets.
|
573 |
+
|
574 |
+
def is_audio_in_length_range(length):
|
575 |
+
return length > min_target_length and length < max_target_length
|
576 |
+
|
577 |
+
# filter data that is shorter than min_target_length
|
578 |
+
vectorized_datasets = vectorized_datasets.filter(
|
579 |
+
is_audio_in_length_range,
|
580 |
+
num_proc=num_workers,
|
581 |
+
input_columns=["target_length"],
|
582 |
+
)
|
583 |
+
|
584 |
+
if description_column_name is not None and data_args.max_description_token_length is not None:
|
585 |
+
with accelerator.local_main_process_first():
|
586 |
+
# filter description that is shorter than max_text_length
|
587 |
+
vectorized_datasets = vectorized_datasets.filter(
|
588 |
+
lambda x: len(x) < data_args.max_description_token_length,
|
589 |
+
num_proc=num_workers,
|
590 |
+
input_columns=["input_ids"],
|
591 |
+
)
|
592 |
+
|
593 |
+
if data_args.max_prompt_token_length is not None:
|
594 |
+
with accelerator.local_main_process_first():
|
595 |
+
# filter description that is shorter than max_text_length
|
596 |
+
vectorized_datasets = vectorized_datasets.filter(
|
597 |
+
lambda x: len(x) < data_args.max_prompt_token_length,
|
598 |
+
num_proc=num_workers,
|
599 |
+
input_columns=["prompt_input_ids"],
|
600 |
+
)
|
601 |
+
|
602 |
+
if data_args.save_to_disk is not None and not dataset_was_precomputed:
|
603 |
+
if accelerator.is_main_process:
|
604 |
+
vectorized_datasets.save_to_disk(
|
605 |
+
data_args.save_to_disk,
|
606 |
+
num_proc=min(data_args.preprocessing_num_workers, len(vectorized_datasets["eval"]) - 1),
|
607 |
+
)
|
608 |
+
accelerator.wait_for_everyone()
|
609 |
+
logger.info(f"Dataset saved at {data_args.save_to_disk}")
|
610 |
+
|
611 |
+
audio_max_length = None
|
612 |
+
if padding == "max_length":
|
613 |
+
audio_max_length = max(vectorized_datasets["train"]["target_length"])
|
614 |
+
with accelerator.local_main_process_first():
|
615 |
+
max_sample = vectorized_datasets["train"].filter(
|
616 |
+
lambda x: x == audio_max_length,
|
617 |
+
num_proc=num_workers,
|
618 |
+
input_columns=["target_length"],
|
619 |
+
)
|
620 |
+
audio_max_length = max([len(l[0]) for l in max_sample["labels"]])
|
621 |
+
|
622 |
+
if description_column_name is not None and data_args.max_description_token_length is not None:
|
623 |
+
with accelerator.local_main_process_first():
|
624 |
+
# filter description that is shorter than max_text_length
|
625 |
+
vectorized_datasets = vectorized_datasets.filter(
|
626 |
+
lambda x: len(x) < data_args.max_description_token_length,
|
627 |
+
num_proc=num_workers,
|
628 |
+
input_columns=["input_ids"],
|
629 |
+
)
|
630 |
+
|
631 |
+
if data_args.max_prompt_token_length is not None:
|
632 |
+
with accelerator.local_main_process_first():
|
633 |
+
# filter description that is shorter than max_text_length
|
634 |
+
vectorized_datasets = vectorized_datasets.filter(
|
635 |
+
lambda x: len(x) < data_args.max_prompt_token_length,
|
636 |
+
num_proc=num_workers,
|
637 |
+
input_columns=["prompt_input_ids"],
|
638 |
+
)
|
639 |
+
|
640 |
+
if training_args.group_by_length:
|
641 |
+
# apply a simple heuristic to take into account audio and text lengths
|
642 |
+
def add_target_lengths(target_length, prompt, description):
|
643 |
+
return {"target_length": target_length + len(prompt) + len(description)}
|
644 |
+
|
645 |
+
with accelerator.local_main_process_first():
|
646 |
+
vectorized_datasets = vectorized_datasets.map(
|
647 |
+
add_target_lengths,
|
648 |
+
num_proc=num_workers,
|
649 |
+
input_columns=["target_length", "prompt_input_ids", "input_ids"],
|
650 |
+
)
|
651 |
+
|
652 |
+
# for large datasets it is advised to run the preprocessing on a
|
653 |
+
# single machine first with ``args.preprocessing_only`` since there will mostly likely
|
654 |
+
# be a timeout when running the script in distributed mode.
|
655 |
+
# In a second step ``args.preprocessing_only`` can then be set to `False` to load the
|
656 |
+
# cached dataset
|
657 |
+
if data_args.preprocessing_only and data_args.save_to_disk is None:
|
658 |
+
raise ValueError(
|
659 |
+
"`preprocessing_only=True` but `save_to_disk` is not set. The latter should indicates where to save the dataset locally."
|
660 |
+
)
|
661 |
+
elif data_args.preprocessing_only:
|
662 |
+
logger.info(f"Data preprocessing finished. Files save at {data_args.save_to_disk}")
|
663 |
+
return
|
664 |
+
|
665 |
+
# 6. Next, we can prepare the training.
|
666 |
+
|
667 |
+
# Let's use word CLAP similary and WER metrics as our evaluation metrics,
|
668 |
+
def compute_metrics(
|
669 |
+
audios,
|
670 |
+
descriptions,
|
671 |
+
prompts,
|
672 |
+
device="cpu",
|
673 |
+
compute_clap_similarity_metric=False,
|
674 |
+
compute_noise_level_metric=False,
|
675 |
+
noise_level_to_compute_clean_wer=None,
|
676 |
+
):
|
677 |
+
results = {}
|
678 |
+
input_ids = descriptions
|
679 |
+
texts = description_tokenizer.batch_decode(input_ids, skip_special_tokens=True)
|
680 |
+
prompts = prompt_tokenizer.batch_decode(prompts, skip_special_tokens=True)
|
681 |
+
audios = [a.float().cpu().numpy() for a in audios]
|
682 |
+
|
683 |
+
if compute_clap_similarity_metric:
|
684 |
+
clap_score = clap_similarity(
|
685 |
+
model_args.clap_model_name_or_path, texts, audios, device, input_sampling_rate=sampling_rate
|
686 |
+
)
|
687 |
+
results["clap"] = clap_score
|
688 |
+
|
689 |
+
si_sdr_measures = None
|
690 |
+
if compute_noise_level_metric:
|
691 |
+
si_sdr_measures = si_sdr(audios, device, input_sampling_rate=sampling_rate)
|
692 |
+
|
693 |
+
word_error, transcriptions, clean_word_error, noisy_word_error, percent_clean_samples = wer(
|
694 |
+
model_args.asr_model_name_or_path,
|
695 |
+
prompts,
|
696 |
+
audios,
|
697 |
+
device,
|
698 |
+
training_args.per_device_eval_batch_size,
|
699 |
+
sampling_rate,
|
700 |
+
noise_level_to_compute_clean_wer,
|
701 |
+
si_sdr_measures,
|
702 |
+
)
|
703 |
+
results["wer"] = word_error
|
704 |
+
if clean_word_error is not None:
|
705 |
+
results["clean_wer"] = clean_word_error
|
706 |
+
results["noisy_word_error"] = noisy_word_error
|
707 |
+
results["percent_clean_samples"] = percent_clean_samples
|
708 |
+
|
709 |
+
return results, texts, prompts, audios, transcriptions, si_sdr_measures
|
710 |
+
|
711 |
+
# Define Training Schedule
|
712 |
+
# Store some constants
|
713 |
+
per_device_train_batch_size = int(training_args.per_device_train_batch_size)
|
714 |
+
train_batch_size = per_device_train_batch_size * accelerator.num_processes
|
715 |
+
gradient_accumulation_steps = int(training_args.gradient_accumulation_steps)
|
716 |
+
per_device_eval_batch_size = int(training_args.per_device_eval_batch_size)
|
717 |
+
|
718 |
+
if training_args.max_steps < 0:
|
719 |
+
num_epochs = int(training_args.num_train_epochs)
|
720 |
+
steps_per_epoch = len(vectorized_datasets["train"]) // (train_batch_size * gradient_accumulation_steps)
|
721 |
+
total_train_steps = steps_per_epoch * num_epochs
|
722 |
+
elif training_args.max_steps > 0:
|
723 |
+
logger.info("max_steps is given, it will override any value given in num_train_epochs")
|
724 |
+
total_train_steps = int(training_args.max_steps)
|
725 |
+
# Setting a very large number of epochs so we go as many times as necessary over the iterator.
|
726 |
+
num_epochs = sys.maxsize
|
727 |
+
steps_per_epoch = total_train_steps
|
728 |
+
|
729 |
+
if training_args.eval_steps is None:
|
730 |
+
logger.info(f"eval_steps is not set, evaluating at the end of each epoch")
|
731 |
+
eval_steps = steps_per_epoch
|
732 |
+
else:
|
733 |
+
eval_steps = training_args.eval_steps
|
734 |
+
|
735 |
+
if training_args.eval_generation_steps is None:
|
736 |
+
eval_generation_steps = eval_steps
|
737 |
+
else:
|
738 |
+
eval_generation_steps = training_args.eval_generation_steps
|
739 |
+
|
740 |
+
# T5 doesn't support fp16
|
741 |
+
autocast_kwargs = AutocastKwargs(enabled=(mixed_precision != "fp16"))
|
742 |
+
|
743 |
+
# Define optimizer, LR scheduler, collator
|
744 |
+
optimizer = torch.optim.AdamW(
|
745 |
+
params=model.parameters(),
|
746 |
+
lr=training_args.learning_rate,
|
747 |
+
betas=(training_args.adam_beta1, training_args.adam_beta2),
|
748 |
+
eps=training_args.adam_epsilon,
|
749 |
+
weight_decay=training_args.weight_decay,
|
750 |
+
)
|
751 |
+
|
752 |
+
# LR scheduler gets stepped by `num_processes` each time -> account for this in warmup / total steps
|
753 |
+
lr_scheduler = get_scheduler(
|
754 |
+
name=training_args.lr_scheduler_type,
|
755 |
+
optimizer=optimizer,
|
756 |
+
num_warmup_steps=training_args.get_warmup_steps(total_train_steps) * accelerator.num_processes,
|
757 |
+
num_training_steps=total_train_steps * accelerator.num_processes,
|
758 |
+
)
|
759 |
+
|
760 |
+
# Instantiate custom data collator
|
761 |
+
data_collator = DataCollatorParlerTTSWithPadding(
|
762 |
+
prompt_tokenizer=prompt_tokenizer,
|
763 |
+
description_tokenizer=description_tokenizer,
|
764 |
+
pad_to_multiple_of=data_args.pad_to_multiple_of,
|
765 |
+
padding=padding,
|
766 |
+
prompt_max_length=data_args.max_prompt_token_length,
|
767 |
+
description_max_length=data_args.max_description_token_length,
|
768 |
+
audio_max_length=audio_max_length,
|
769 |
+
)
|
770 |
+
|
771 |
+
# Prepare everything with accelerate
|
772 |
+
model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
|
773 |
+
|
774 |
+
num_examples = total_train_steps * train_batch_size * gradient_accumulation_steps
|
775 |
+
logger.info("***** Running training *****")
|
776 |
+
logger.info(f" Num examples = {num_examples}")
|
777 |
+
logger.info(" Instantaneous batch size per device =" f" {per_device_train_batch_size}")
|
778 |
+
logger.info(" Gradient accumulation steps =" f" {gradient_accumulation_steps}")
|
779 |
+
logger.info(
|
780 |
+
f" Total train batch size (w. parallel & distributed) = {train_batch_size * gradient_accumulation_steps}"
|
781 |
+
)
|
782 |
+
logger.info(f" Total optimization steps = {total_train_steps}")
|
783 |
+
|
784 |
+
# ======================== Training ================================
|
785 |
+
train_time = 0
|
786 |
+
train_start = time.time()
|
787 |
+
steps_trained_progress_bar = tqdm(
|
788 |
+
range(total_train_steps), desc="Train steps ... ", position=0, disable=not accelerator.is_local_main_process
|
789 |
+
)
|
790 |
+
continue_training = True
|
791 |
+
epochs_trained = 0
|
792 |
+
cur_step = 0
|
793 |
+
|
794 |
+
checkpoint = None
|
795 |
+
if training_args.resume_from_checkpoint is not None:
|
796 |
+
checkpoint = training_args.resume_from_checkpoint
|
797 |
+
elif last_checkpoint is not None:
|
798 |
+
checkpoint = last_checkpoint
|
799 |
+
|
800 |
+
if accelerator.is_main_process:
|
801 |
+
if training_args.push_to_hub:
|
802 |
+
api = HfApi(token=training_args.hub_token)
|
803 |
+
|
804 |
+
# Create repo (repo_name from args or inferred)
|
805 |
+
repo_name = training_args.hub_model_id
|
806 |
+
if repo_name is None:
|
807 |
+
repo_name = Path(training_args.output_dir).absolute().name
|
808 |
+
repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
|
809 |
+
|
810 |
+
with open(os.path.join(training_args.output_dir, ".gitignore"), "w+") as gitignore:
|
811 |
+
if "wandb" not in gitignore:
|
812 |
+
gitignore.write("wandb\n")
|
813 |
+
elif training_args.output_dir is not None:
|
814 |
+
os.makedirs(training_args.output_dir, exist_ok=True)
|
815 |
+
accelerator.wait_for_everyone()
|
816 |
+
|
817 |
+
# Now save everything to be able to create a single processor later
|
818 |
+
# make sure all processes wait until data is saved
|
819 |
+
# only the main process saves them
|
820 |
+
if accelerator.is_main_process:
|
821 |
+
# save feature extractor, tokenizer and config
|
822 |
+
if (
|
823 |
+
model_args.prompt_tokenizer_name is None
|
824 |
+
and model_args.description_tokenizer_name
|
825 |
+
or (model_args.prompt_tokenizer_name == model_args.description_tokenizer_name)
|
826 |
+
):
|
827 |
+
prompt_tokenizer.save_pretrained(training_args.output_dir)
|
828 |
+
else:
|
829 |
+
logger.warning(
|
830 |
+
f"Prompt tokenizer ('{model_args.prompt_tokenizer_name}') and description tokenizer ('{model_args.description_tokenizer_name}') are not the same. Saving only the prompt tokenizer."
|
831 |
+
)
|
832 |
+
prompt_tokenizer.save_pretrained(training_args.output_dir)
|
833 |
+
|
834 |
+
feature_extractor.save_pretrained(training_args.output_dir)
|
835 |
+
config.save_pretrained(training_args.output_dir)
|
836 |
+
accelerator.wait_for_everyone()
|
837 |
+
|
838 |
+
if checkpoint is not None:
|
839 |
+
accelerator.load_state(checkpoint)
|
840 |
+
# Find num steps and epoch from saved state string pattern
|
841 |
+
pattern = r"checkpoint-(\d+)-epoch-(\d+)"
|
842 |
+
match = re.search(pattern, checkpoint)
|
843 |
+
cur_step = int(match.group(1))
|
844 |
+
epochs_trained = int(match.group(2))
|
845 |
+
|
846 |
+
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
|
847 |
+
logger.info(f" Continuing training from epoch {epochs_trained}")
|
848 |
+
logger.info(f" Continuing training from global step {cur_step}")
|
849 |
+
|
850 |
+
steps_trained_progress_bar.update(cur_step)
|
851 |
+
|
852 |
+
for epoch in range(0, epochs_trained):
|
853 |
+
with accelerator.local_main_process_first():
|
854 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(training_args.seed)
|
855 |
+
|
856 |
+
if training_args.max_steps < 0:
|
857 |
+
# we know exactly the number of steps per epoch, so can skip through the required number of batches
|
858 |
+
resume_step = (cur_step - epochs_trained * steps_per_epoch) * gradient_accumulation_steps
|
859 |
+
else:
|
860 |
+
# Currently we don't know how many steps we've taken in the current epoch
|
861 |
+
# So we just shuffle the dataset one extra time and start from a fresh epoch
|
862 |
+
# This is "good enough" for our purposes but not fully correct
|
863 |
+
resume_step = None
|
864 |
+
with accelerator.local_main_process_first():
|
865 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(training_args.seed)
|
866 |
+
else:
|
867 |
+
resume_step = None
|
868 |
+
|
869 |
+
gen_kwargs = {
|
870 |
+
"do_sample": model_args.do_sample,
|
871 |
+
"temperature": model_args.temperature,
|
872 |
+
"max_length": model_args.max_length,
|
873 |
+
# Because of the delayed pattern mask, generation might stop earlier because of unexpected behaviour
|
874 |
+
# on the first tokens of the codebooks that are delayed.
|
875 |
+
# This fix the issue.
|
876 |
+
"min_new_tokens": num_codebooks + 1,
|
877 |
+
}
|
878 |
+
|
879 |
+
# Define gradient update step fn
|
880 |
+
def train_step(
|
881 |
+
batch,
|
882 |
+
accelerator,
|
883 |
+
autocast_kwargs,
|
884 |
+
num_items_in_batch,
|
885 |
+
gradient_accumulation_steps,
|
886 |
+
):
|
887 |
+
if mixed_precision == "fp16":
|
888 |
+
# fp16 doesn't work with T5-like models
|
889 |
+
with accelerator.autocast(autocast_handler=autocast_kwargs):
|
890 |
+
if training_args.parallel_mode.value != "distributed":
|
891 |
+
encoder_outputs = model.text_encoder(
|
892 |
+
input_ids=batch.get("input_ids"), attention_mask=batch.get("attention_mask", None)
|
893 |
+
)
|
894 |
+
else:
|
895 |
+
encoder_outputs = model.module.text_encoder(
|
896 |
+
input_ids=batch.get("input_ids"), attention_mask=batch.get("attention_mask", None)
|
897 |
+
)
|
898 |
+
# we optionnally project last_hidden_state to avoid recomputing every time
|
899 |
+
encoder_hidden_states = encoder_outputs.last_hidden_state
|
900 |
+
if (
|
901 |
+
config.text_encoder.hidden_size != config.decoder.hidden_size
|
902 |
+
and config.decoder.cross_attention_hidden_size is None
|
903 |
+
):
|
904 |
+
encoder_hidden_states = (
|
905 |
+
model.enc_to_dec_proj(encoder_hidden_states)
|
906 |
+
if training_args.parallel_mode.value != "distributed"
|
907 |
+
else model.module.enc_to_dec_proj(encoder_hidden_states)
|
908 |
+
)
|
909 |
+
|
910 |
+
if batch.get("attention_mask", None) is not None:
|
911 |
+
encoder_hidden_states = encoder_hidden_states * batch.get("attention_mask", None)[..., None]
|
912 |
+
|
913 |
+
encoder_outputs.last_hidden_state = encoder_hidden_states
|
914 |
+
batch["encoder_outputs"] = encoder_outputs
|
915 |
+
|
916 |
+
outputs = model(**batch, loss_reduction="sum")
|
917 |
+
# CE (data) loss
|
918 |
+
ce_loss = (outputs.loss * gradient_accumulation_steps * accelerator.num_processes) / num_items_in_batch
|
919 |
+
|
920 |
+
metrics = {"loss": ce_loss}
|
921 |
+
|
922 |
+
# per CE loss
|
923 |
+
per_codebook_losses = outputs.per_codebook_losses
|
924 |
+
metrics.update({f"codebook_{i}_loss": ((l * gradient_accumulation_steps * accelerator.num_processes) / num_items_in_batch) for (i,l) in enumerate(per_codebook_losses)})
|
925 |
+
return ce_loss, metrics
|
926 |
+
|
927 |
+
# Define eval fn
|
928 |
+
def eval_step(
|
929 |
+
batch,
|
930 |
+
accelerator,
|
931 |
+
autocast_kwargs,
|
932 |
+
):
|
933 |
+
eval_model = model if not training_args.torch_compile else model._orig_mod
|
934 |
+
|
935 |
+
if mixed_precision == "fp16":
|
936 |
+
# fp16 doesn't work with T5-like models
|
937 |
+
with accelerator.autocast(autocast_handler=autocast_kwargs):
|
938 |
+
if training_args.parallel_mode.value != "distributed":
|
939 |
+
encoder_outputs = model.text_encoder(
|
940 |
+
input_ids=batch.get("input_ids"), attention_mask=batch.get("attention_mask", None)
|
941 |
+
)
|
942 |
+
else:
|
943 |
+
encoder_outputs = model.module.text_encoder(
|
944 |
+
input_ids=batch.get("input_ids"), attention_mask=batch.get("attention_mask", None)
|
945 |
+
)
|
946 |
+
# we optionnally project last_hidden_state to avoid recomputing every time
|
947 |
+
encoder_hidden_states = encoder_outputs.last_hidden_state
|
948 |
+
if (
|
949 |
+
config.text_encoder.hidden_size != config.decoder.hidden_size
|
950 |
+
and config.decoder.cross_attention_hidden_size is None
|
951 |
+
):
|
952 |
+
encoder_hidden_states = (
|
953 |
+
model.enc_to_dec_proj(encoder_hidden_states)
|
954 |
+
if training_args.parallel_mode.value != "distributed"
|
955 |
+
else model.module.enc_to_dec_proj(encoder_hidden_states)
|
956 |
+
)
|
957 |
+
|
958 |
+
if batch.get("attention_mask", None) is not None:
|
959 |
+
encoder_hidden_states = encoder_hidden_states * batch.get("attention_mask", None)[..., None]
|
960 |
+
|
961 |
+
encoder_outputs.last_hidden_state = encoder_hidden_states
|
962 |
+
batch["encoder_outputs"] = encoder_outputs
|
963 |
+
|
964 |
+
with torch.no_grad():
|
965 |
+
outputs = eval_model(**batch)
|
966 |
+
# CE (data) loss
|
967 |
+
ce_loss = outputs.loss
|
968 |
+
metrics = {"loss": ce_loss}
|
969 |
+
|
970 |
+
# per CE loss
|
971 |
+
per_codebook_losses = outputs.per_codebook_losses
|
972 |
+
metrics.update({f"codebook_{i}_loss": l for (i,l) in enumerate(per_codebook_losses)})
|
973 |
+
return metrics
|
974 |
+
|
975 |
+
def generate_step(batch, accelerator):
|
976 |
+
batch.pop("decoder_attention_mask", None)
|
977 |
+
eval_model = accelerator.unwrap_model(model, keep_fp32_wrapper=True)
|
978 |
+
if training_args.torch_compile:
|
979 |
+
# if the model is compiled, we use the original model bc compile is not compatible with .generate
|
980 |
+
eval_model = model._orig_mod
|
981 |
+
|
982 |
+
# since we've might have loaded the weights in fp32, we have to autocast to ensure FA2 weights are in half-precision.
|
983 |
+
# with accelerator.autocast(autocast_handler=AutocastKwargs(enabled=(attn_implementation=="flash_attention_2"))):
|
984 |
+
output_audios = eval_model.generate(**batch, **gen_kwargs)
|
985 |
+
output_audios = accelerator.pad_across_processes(output_audios, dim=1, pad_index=0)
|
986 |
+
return output_audios
|
987 |
+
|
988 |
+
model.train()
|
989 |
+
|
990 |
+
total_batched_samples = resume_step if resume_step is not None else 0
|
991 |
+
for epoch in range(epochs_trained, num_epochs):
|
992 |
+
with accelerator.local_main_process_first():
|
993 |
+
vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(training_args.seed)
|
994 |
+
sampler = None
|
995 |
+
if training_args.group_by_length:
|
996 |
+
sampler = LengthGroupedSampler(train_batch_size, lengths=vectorized_datasets["train"]["target_length"])
|
997 |
+
train_dataloader = DataLoader(
|
998 |
+
vectorized_datasets["train"],
|
999 |
+
collate_fn=data_collator,
|
1000 |
+
batch_size=per_device_train_batch_size,
|
1001 |
+
sampler=sampler,
|
1002 |
+
shuffle=not training_args.group_by_length,
|
1003 |
+
num_workers=training_args.dataloader_num_workers,
|
1004 |
+
pin_memory=training_args.dataloader_pin_memory,
|
1005 |
+
)
|
1006 |
+
train_dataloader = accelerator.prepare(train_dataloader)
|
1007 |
+
if hasattr(train_dataloader, "dataset") and isinstance(train_dataloader.dataset, IterableDataset):
|
1008 |
+
train_dataloader.dataset.set_epoch(epoch)
|
1009 |
+
|
1010 |
+
if resume_step is not None:
|
1011 |
+
# Skip the first N batches in the dataloader when resuming from a checkpoint
|
1012 |
+
logger.info(f" Skip first {resume_step} batches")
|
1013 |
+
train_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
|
1014 |
+
resume_step = None
|
1015 |
+
accelerator.wait_for_everyone()
|
1016 |
+
|
1017 |
+
# We chunkify the epoch iterator into gradient accumulation steps `n` batches
|
1018 |
+
train_iterator = iter(train_dataloader)
|
1019 |
+
num_steps_in_epoch = len(train_dataloader)
|
1020 |
+
remainder = num_steps_in_epoch % gradient_accumulation_steps
|
1021 |
+
remainder = remainder if remainder != 0 else gradient_accumulation_steps
|
1022 |
+
total_updates = math.ceil(num_steps_in_epoch / gradient_accumulation_steps)
|
1023 |
+
|
1024 |
+
update_step = -1
|
1025 |
+
for _ in range(total_updates):
|
1026 |
+
update_step += 1
|
1027 |
+
|
1028 |
+
# preload the total batch per step
|
1029 |
+
batch_samples = []
|
1030 |
+
num_batches_in_step = gradient_accumulation_steps if update_step != (total_updates - 1) else remainder
|
1031 |
+
for _ in range(num_batches_in_step):
|
1032 |
+
batch_samples += [next(train_iterator)]
|
1033 |
+
|
1034 |
+
# get num items in batch - if different than BOS and than -100
|
1035 |
+
num_items_in_batch = sum([(batch["labels"].ne(audio_encoder_bos_token_id) | batch["labels"].ne(-100) | batch["labels"].ne(audio_encoder_eos_token_id)).sum((0,1))[0] for batch in batch_samples])
|
1036 |
+
num_items_in_batch = accelerator.gather(num_items_in_batch).sum().item()
|
1037 |
+
|
1038 |
+
# losses = []
|
1039 |
+
for i,batch in enumerate(batch_samples):
|
1040 |
+
total_batched_samples += 1
|
1041 |
+
ctx = model.no_sync if (i < len(batch_samples) - 1 and accelerator.num_processes > 1) else contextlib.nullcontext
|
1042 |
+
|
1043 |
+
with ctx():
|
1044 |
+
loss, train_metric = train_step(batch, accelerator, autocast_kwargs, num_items_in_batch, gradient_accumulation_steps)
|
1045 |
+
accelerator.backward(loss)
|
1046 |
+
# losses.append(loss.detach())
|
1047 |
+
|
1048 |
+
grad_norm = accelerator.clip_grad_norm_(model.parameters(), training_args.max_grad_norm)
|
1049 |
+
optimizer.step()
|
1050 |
+
lr_scheduler.step()
|
1051 |
+
optimizer.zero_grad()
|
1052 |
+
|
1053 |
+
# The accelerator has performed an optimization step behind the scenes
|
1054 |
+
steps_trained_progress_bar.update(1)
|
1055 |
+
cur_step += 1
|
1056 |
+
|
1057 |
+
# losses = accelerator.gather(sum(losses)).sum().item() / (accelerator.num_processes * gradient_accumulation_steps)
|
1058 |
+
|
1059 |
+
if cur_step % training_args.logging_steps == 0:
|
1060 |
+
steps_trained_progress_bar.write(
|
1061 |
+
f"Step... ({cur_step} / {total_train_steps} | Loss:"
|
1062 |
+
f" {train_metric['loss']}, Learning Rate:"
|
1063 |
+
f" {lr_scheduler.get_last_lr()[0]})"
|
1064 |
+
)
|
1065 |
+
train_metric["grad_norm"] = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm
|
1066 |
+
log_metric(
|
1067 |
+
accelerator,
|
1068 |
+
metrics=train_metric,
|
1069 |
+
learning_rate=lr_scheduler.get_last_lr()[0],
|
1070 |
+
train_time=train_time + time.time() - train_start,
|
1071 |
+
step=cur_step,
|
1072 |
+
epoch=epoch,
|
1073 |
+
prefix="train",
|
1074 |
+
)
|
1075 |
+
|
1076 |
+
# save checkpoint and weights after each save_steps and at the end of training
|
1077 |
+
if (cur_step % training_args.save_steps == 0) or cur_step == total_train_steps:
|
1078 |
+
intermediate_dir = os.path.join(training_args.output_dir, f"checkpoint-{cur_step}-epoch-{epoch}")
|
1079 |
+
# safe_serialization=False to avoid shared tensors saving issue (TODO(YL): it's a temporary fix)
|
1080 |
+
# https://github.com/huggingface/transformers/issues/27293#issuecomment-1872560074
|
1081 |
+
accelerator.save_state(output_dir=intermediate_dir, safe_serialization=False)
|
1082 |
+
accelerator.wait_for_everyone()
|
1083 |
+
if accelerator.is_main_process:
|
1084 |
+
rotate_checkpoints(
|
1085 |
+
training_args.save_total_limit, output_dir=training_args.output_dir, logger=logger
|
1086 |
+
)
|
1087 |
+
|
1088 |
+
if cur_step == total_train_steps:
|
1089 |
+
# un-wrap student model for save
|
1090 |
+
unwrapped_model = accelerator.unwrap_model(model)
|
1091 |
+
unwrapped_model.save_pretrained(training_args.output_dir)
|
1092 |
+
|
1093 |
+
if training_args.push_to_hub:
|
1094 |
+
api.upload_folder(
|
1095 |
+
repo_id=repo_id,
|
1096 |
+
folder_path=training_args.output_dir,
|
1097 |
+
commit_message=f"Saving train state of step {cur_step}",
|
1098 |
+
run_as_future=True,
|
1099 |
+
)
|
1100 |
+
accelerator.wait_for_everyone()
|
1101 |
+
|
1102 |
+
if training_args.do_eval and (cur_step % eval_steps == 0 or cur_step == total_train_steps):
|
1103 |
+
train_time += time.time() - train_start
|
1104 |
+
# ======================== Evaluating ==============================
|
1105 |
+
model.eval()
|
1106 |
+
eval_metrics = []
|
1107 |
+
eval_preds = []
|
1108 |
+
eval_descriptions = []
|
1109 |
+
eval_prompts = []
|
1110 |
+
eval_start = time.time()
|
1111 |
+
|
1112 |
+
# release training input batch
|
1113 |
+
batch = release_memory(batch)
|
1114 |
+
|
1115 |
+
validation_dataloader = DataLoader(
|
1116 |
+
vectorized_datasets["eval"],
|
1117 |
+
collate_fn=data_collator,
|
1118 |
+
batch_size=per_device_eval_batch_size,
|
1119 |
+
drop_last=False,
|
1120 |
+
num_workers=training_args.eval_dataloader_num_workers,
|
1121 |
+
pin_memory=training_args.dataloader_pin_memory,
|
1122 |
+
)
|
1123 |
+
validation_dataloader = accelerator.prepare(validation_dataloader)
|
1124 |
+
|
1125 |
+
for batch in tqdm(
|
1126 |
+
validation_dataloader,
|
1127 |
+
desc=f"Evaluating - Inference ...",
|
1128 |
+
position=2,
|
1129 |
+
disable=not accelerator.is_local_main_process,
|
1130 |
+
):
|
1131 |
+
# Model forward
|
1132 |
+
eval_metric = eval_step(batch, accelerator, autocast_kwargs)
|
1133 |
+
eval_metric = accelerator.gather_for_metrics(eval_metric)
|
1134 |
+
eval_metric = {key: val.unsqueeze(0) if val.ndim == 0 else val for (key,val) in eval_metric.items()}
|
1135 |
+
eval_metrics.append(eval_metric)
|
1136 |
+
|
1137 |
+
if training_args.predict_with_generate and (cur_step % eval_generation_steps == 0 or cur_step == total_train_steps):
|
1138 |
+
validation_dataloader = DataLoader(
|
1139 |
+
vectorized_datasets["eval"],
|
1140 |
+
collate_fn=data_collator,
|
1141 |
+
batch_size=per_device_eval_batch_size,
|
1142 |
+
drop_last=False,
|
1143 |
+
num_workers=training_args.eval_dataloader_num_workers,
|
1144 |
+
pin_memory=training_args.dataloader_pin_memory,
|
1145 |
+
)
|
1146 |
+
validation_dataloader = accelerator.prepare(validation_dataloader)
|
1147 |
+
# generation
|
1148 |
+
for batch in tqdm(
|
1149 |
+
validation_dataloader,
|
1150 |
+
desc=f"Evaluating - Generation ...",
|
1151 |
+
position=2,
|
1152 |
+
disable=not accelerator.is_local_main_process,
|
1153 |
+
):
|
1154 |
+
generated_audios = generate_step(batch, accelerator)
|
1155 |
+
# Gather all predictions and targets
|
1156 |
+
generated_audios, input_ids, prompts = accelerator.pad_across_processes(
|
1157 |
+
(generated_audios, batch["input_ids"], batch["prompt_input_ids"]), dim=1, pad_index=0
|
1158 |
+
)
|
1159 |
+
generated_audios, input_ids, prompts = accelerator.gather_for_metrics(
|
1160 |
+
(generated_audios, input_ids, prompts)
|
1161 |
+
)
|
1162 |
+
eval_preds.extend(generated_audios.to("cpu"))
|
1163 |
+
eval_descriptions.extend(input_ids.to("cpu"))
|
1164 |
+
eval_prompts.extend(prompts.to("cpu"))
|
1165 |
+
|
1166 |
+
eval_time = time.time() - eval_start
|
1167 |
+
# normalize eval metrics
|
1168 |
+
eval_metrics = {
|
1169 |
+
key: torch.mean(torch.cat([d[key] for d in eval_metrics])).to("cpu") for key in eval_metrics[0]
|
1170 |
+
}
|
1171 |
+
|
1172 |
+
# compute metrics
|
1173 |
+
metrics_desc = ""
|
1174 |
+
if training_args.predict_with_generate and (cur_step % eval_generation_steps == 0 or cur_step == total_train_steps):
|
1175 |
+
if accelerator.is_local_main_process:
|
1176 |
+
(
|
1177 |
+
metric_values,
|
1178 |
+
pred_descriptions,
|
1179 |
+
pred_prompts,
|
1180 |
+
audios,
|
1181 |
+
transcriptions,
|
1182 |
+
si_sdr_measures,
|
1183 |
+
) = compute_metrics(
|
1184 |
+
eval_preds,
|
1185 |
+
eval_descriptions,
|
1186 |
+
eval_prompts,
|
1187 |
+
accelerator.device,
|
1188 |
+
training_args.compute_clap_similarity_metric,
|
1189 |
+
training_args.compute_noise_level_metric,
|
1190 |
+
training_args.noise_level_to_compute_clean_wer,
|
1191 |
+
)
|
1192 |
+
eval_metrics.update(metric_values)
|
1193 |
+
metrics_desc = " ".join([f"Eval {key}: {value} |" for key, value in metric_values.items()])
|
1194 |
+
if "wandb" in training_args.report_to:
|
1195 |
+
log_pred(
|
1196 |
+
accelerator,
|
1197 |
+
pred_descriptions,
|
1198 |
+
pred_prompts,
|
1199 |
+
transcriptions,
|
1200 |
+
audios,
|
1201 |
+
si_sdr_measures,
|
1202 |
+
sampling_rate=sampling_rate,
|
1203 |
+
step=cur_step,
|
1204 |
+
prefix="eval",
|
1205 |
+
)
|
1206 |
+
accelerator.wait_for_everyone()
|
1207 |
+
|
1208 |
+
# Print metrics and update progress bar
|
1209 |
+
if accelerator.is_local_main_process:
|
1210 |
+
steps_trained_progress_bar.write(
|
1211 |
+
f"Eval results for step ({cur_step} / {total_train_steps} | Eval Loss: {eval_metrics['loss']} |"
|
1212 |
+
f" {metrics_desc})"
|
1213 |
+
)
|
1214 |
+
|
1215 |
+
log_metric(
|
1216 |
+
accelerator,
|
1217 |
+
metrics=eval_metrics,
|
1218 |
+
train_time=eval_time,
|
1219 |
+
step=cur_step,
|
1220 |
+
epoch=epoch,
|
1221 |
+
prefix="eval",
|
1222 |
+
)
|
1223 |
+
|
1224 |
+
# release eval batch and relax metrics
|
1225 |
+
eval_metrics, eval_preds, eval_descriptions, eval_prompts, batch, eval_metric = release_memory(
|
1226 |
+
eval_metrics, eval_preds, eval_descriptions, eval_prompts, batch, eval_metric
|
1227 |
+
)
|
1228 |
+
if training_args.predict_with_generate and (cur_step % eval_generation_steps == 0 or cur_step == total_train_steps):
|
1229 |
+
generated_audios, input_ids, prompts = release_memory(generated_audios, input_ids, prompts)
|
1230 |
+
|
1231 |
+
# train mode
|
1232 |
+
model.train()
|
1233 |
+
|
1234 |
+
# flush the train metrics
|
1235 |
+
train_start = time.time()
|
1236 |
+
|
1237 |
+
# break condition
|
1238 |
+
if cur_step == total_train_steps:
|
1239 |
+
continue_training = False
|
1240 |
+
break
|
1241 |
+
|
1242 |
+
if not continue_training:
|
1243 |
+
break
|
1244 |
+
|
1245 |
+
accelerator.end_training()
|
1246 |
+
|
1247 |
+
|
1248 |
+
if __name__ == "__main__":
|
1249 |
+
main()
|
parler-tts/training/utils.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import shutil
|
4 |
+
from dataclasses import field
|
5 |
+
from pathlib import Path
|
6 |
+
from typing import Dict, List
|
7 |
+
|
8 |
+
import torch
|
9 |
+
from datasets import concatenate_datasets, load_from_disk
|
10 |
+
from wandb import Audio
|
11 |
+
from datasets import load_from_disk, concatenate_datasets
|
12 |
+
|
13 |
+
|
14 |
+
def list_field(default=None, metadata=None):
|
15 |
+
return field(default_factory=lambda: default, metadata=metadata)
|
16 |
+
|
17 |
+
|
18 |
+
_RE_CHECKPOINT = re.compile(r"^checkpoint-(\d+)-epoch-(\d+)$")
|
19 |
+
CHECKPOINT_CODEC_PREFIX = "checkpoint"
|
20 |
+
_RE_CODEC_CHECKPOINT = re.compile(r"^checkpoint-(\d+)$")
|
21 |
+
|
22 |
+
|
23 |
+
def get_last_checkpoint(folder):
|
24 |
+
content = os.listdir(folder)
|
25 |
+
checkpoints = [
|
26 |
+
path
|
27 |
+
for path in content
|
28 |
+
if _RE_CHECKPOINT.search(path) is not None and os.path.isdir(os.path.join(folder, path))
|
29 |
+
]
|
30 |
+
if len(checkpoints) == 0:
|
31 |
+
return
|
32 |
+
return os.path.join(folder, max(checkpoints, key=lambda x: int(_RE_CHECKPOINT.search(x).groups()[0])))
|
33 |
+
|
34 |
+
|
35 |
+
def sorted_checkpoints(output_dir=None, checkpoint_prefix="checkpoint") -> List[str]:
|
36 |
+
"""Helper function to sort saved checkpoints from oldest to newest."""
|
37 |
+
ordering_and_checkpoint_path = []
|
38 |
+
|
39 |
+
glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*") if os.path.isdir(x)]
|
40 |
+
|
41 |
+
for path in glob_checkpoints:
|
42 |
+
regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path)
|
43 |
+
if regex_match is not None and regex_match.groups() is not None:
|
44 |
+
ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
|
45 |
+
|
46 |
+
checkpoints_sorted = sorted(ordering_and_checkpoint_path)
|
47 |
+
checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
|
48 |
+
return checkpoints_sorted
|
49 |
+
|
50 |
+
|
51 |
+
def rotate_checkpoints(save_total_limit=None, output_dir=None, checkpoint_prefix="checkpoint", logger=None) -> None:
|
52 |
+
"""Helper function to delete old checkpoints."""
|
53 |
+
if save_total_limit is None or save_total_limit <= 0:
|
54 |
+
return
|
55 |
+
# Check if we should delete older checkpoint(s)
|
56 |
+
checkpoints_sorted = sorted_checkpoints(output_dir=output_dir, checkpoint_prefix=checkpoint_prefix)
|
57 |
+
if len(checkpoints_sorted) <= save_total_limit:
|
58 |
+
return
|
59 |
+
|
60 |
+
number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - save_total_limit)
|
61 |
+
checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
|
62 |
+
for checkpoint in checkpoints_to_be_deleted:
|
63 |
+
logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit")
|
64 |
+
shutil.rmtree(checkpoint, ignore_errors=True)
|
65 |
+
|
66 |
+
|
67 |
+
def save_codec_checkpoint(output_dir, dataset, step):
|
68 |
+
checkpoint_path = f"{CHECKPOINT_CODEC_PREFIX}-{step}"
|
69 |
+
output_path = os.path.join(output_dir, checkpoint_path)
|
70 |
+
dataset.save_to_disk(output_path)
|
71 |
+
|
72 |
+
|
73 |
+
def load_codec_checkpoint(checkpoint_path):
|
74 |
+
dataset = load_from_disk(checkpoint_path)
|
75 |
+
return dataset
|
76 |
+
|
77 |
+
|
78 |
+
def sorted_codec_checkpoints(output_dir=None) -> List[str]:
|
79 |
+
"""Helper function to sort saved checkpoints from oldest to newest."""
|
80 |
+
ordering_and_checkpoint_path = []
|
81 |
+
|
82 |
+
glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{CHECKPOINT_CODEC_PREFIX}-*")]
|
83 |
+
|
84 |
+
for path in glob_checkpoints:
|
85 |
+
regex_match = re.match(f".*{CHECKPOINT_CODEC_PREFIX}-([0-9]+)", path)
|
86 |
+
if regex_match is not None and regex_match.groups() is not None:
|
87 |
+
ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
|
88 |
+
|
89 |
+
checkpoints_sorted = sorted(ordering_and_checkpoint_path)
|
90 |
+
checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
|
91 |
+
return checkpoints_sorted
|
92 |
+
|
93 |
+
|
94 |
+
def load_all_codec_checkpoints(output_dir=None) -> List[str]:
|
95 |
+
"""Helper function to load and concat all checkpoints."""
|
96 |
+
checkpoints_sorted = sorted_codec_checkpoints(output_dir=output_dir)
|
97 |
+
datasets = [load_from_disk(checkpoint) for checkpoint in checkpoints_sorted]
|
98 |
+
datasets = concatenate_datasets(datasets, axis=0)
|
99 |
+
return datasets
|
100 |
+
|
101 |
+
|
102 |
+
def get_last_codec_checkpoint_step(folder) -> int:
|
103 |
+
if not os.path.exists(folder) or not os.path.isdir(folder):
|
104 |
+
os.makedirs(folder, exist_ok=True)
|
105 |
+
return 0
|
106 |
+
content = os.listdir(folder)
|
107 |
+
checkpoints = [path for path in content if _RE_CODEC_CHECKPOINT.search(path) is not None]
|
108 |
+
if len(checkpoints) == 0:
|
109 |
+
return 0
|
110 |
+
last_checkpoint = os.path.join(
|
111 |
+
folder, max(checkpoints, key=lambda x: int(_RE_CODEC_CHECKPOINT.search(x).groups()[0]))
|
112 |
+
)
|
113 |
+
# Find num steps saved state string pattern
|
114 |
+
pattern = r"checkpoint-(\d+)"
|
115 |
+
match = re.search(pattern, last_checkpoint)
|
116 |
+
cur_step = int(match.group(1))
|
117 |
+
return cur_step
|
118 |
+
|
119 |
+
|
120 |
+
def log_metric(
|
121 |
+
accelerator,
|
122 |
+
metrics: Dict,
|
123 |
+
train_time: float,
|
124 |
+
step: int,
|
125 |
+
epoch: int,
|
126 |
+
learning_rate: float = None,
|
127 |
+
prefix: str = "train",
|
128 |
+
):
|
129 |
+
"""Helper function to log all training/evaluation metrics with the correct prefixes and styling."""
|
130 |
+
log_metrics = {}
|
131 |
+
for k, v in metrics.items():
|
132 |
+
if "codebook" in k:
|
133 |
+
log_metrics[f"codebook_{prefix}/{k}"] = v
|
134 |
+
else:
|
135 |
+
log_metrics[f"{prefix}/{k}"] = v
|
136 |
+
log_metrics[f"{prefix}/time"] = train_time
|
137 |
+
log_metrics[f"{prefix}/epoch"] = epoch
|
138 |
+
if learning_rate is not None:
|
139 |
+
log_metrics[f"{prefix}/learning_rate"] = learning_rate
|
140 |
+
accelerator.log(log_metrics, step=step)
|
141 |
+
|
142 |
+
|
143 |
+
def log_pred(
|
144 |
+
accelerator,
|
145 |
+
pred_descriptions: List[str],
|
146 |
+
pred_prompts: List[str],
|
147 |
+
transcriptions: List[str],
|
148 |
+
audios: List[torch.Tensor],
|
149 |
+
si_sdr_measures: List[float],
|
150 |
+
sampling_rate: int,
|
151 |
+
step: int,
|
152 |
+
prefix: str = "eval",
|
153 |
+
num_lines: int = 200000,
|
154 |
+
):
|
155 |
+
"""Helper function to log target/predicted transcriptions to weights and biases (wandb)."""
|
156 |
+
if accelerator.is_main_process:
|
157 |
+
wandb_tracker = accelerator.get_tracker("wandb")
|
158 |
+
# pretty name for current step: step 50000 -> step 50k
|
159 |
+
cur_step_pretty = f"{int(step // 1000)}k" if step > 1000 else step
|
160 |
+
prefix_pretty = prefix.replace("/", "-")
|
161 |
+
|
162 |
+
if si_sdr_measures is None:
|
163 |
+
# convert str data to a wandb compatible format
|
164 |
+
str_data = [
|
165 |
+
[pred_descriptions[i], pred_prompts[i], transcriptions[i]] for i in range(len(pred_descriptions))
|
166 |
+
]
|
167 |
+
# log as a table with the appropriate headers
|
168 |
+
wandb_tracker.log_table(
|
169 |
+
table_name=f"predictions/{prefix_pretty}-step-{cur_step_pretty}",
|
170 |
+
columns=["Target descriptions", "Target prompts", "Predicted transcriptions"],
|
171 |
+
data=str_data[:num_lines],
|
172 |
+
step=step,
|
173 |
+
commit=False,
|
174 |
+
)
|
175 |
+
else:
|
176 |
+
# convert str data to a wandb compatible format
|
177 |
+
str_data = [
|
178 |
+
[pred_descriptions[i], pred_prompts[i], transcriptions[i], si_sdr_measures[i]]
|
179 |
+
for i in range(len(pred_descriptions))
|
180 |
+
]
|
181 |
+
# log as a table with the appropriate headers
|
182 |
+
wandb_tracker.log_table(
|
183 |
+
table_name=f"predictions/{prefix_pretty}-step-{cur_step_pretty}",
|
184 |
+
columns=["Target descriptions", "Target prompts", "Predicted transcriptions", "Noise estimation"],
|
185 |
+
data=str_data[:num_lines],
|
186 |
+
step=step,
|
187 |
+
commit=False,
|
188 |
+
)
|
189 |
+
|
190 |
+
# wandb can only loads 100 audios per step
|
191 |
+
wandb_tracker.log(
|
192 |
+
{
|
193 |
+
"Speech samples": [
|
194 |
+
Audio(
|
195 |
+
audio,
|
196 |
+
caption=f"{pred_prompts[i]} --- DESCRIPTION: {pred_descriptions[i]}",
|
197 |
+
sample_rate=sampling_rate,
|
198 |
+
)
|
199 |
+
for (i, audio) in enumerate(audios[: min(len(audios), 100)])
|
200 |
+
]
|
201 |
+
},
|
202 |
+
step=step,
|
203 |
+
)
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
transformers==4.37.2
|
2 |
+
torch==2.2.0
|
3 |
+
gradio==4.19.2
|
4 |
+
soundfile==0.12.1
|
5 |
+
git+https://github.com/huggingface/parler-tts.git
|
tts.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
3 |
+
from transformers import AutoTokenizer
|
4 |
+
import soundfile as sf
|
5 |
+
|
6 |
+
class TTSModel:
|
7 |
+
def __init__(self):
|
8 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
9 |
+
self.model_name = "ai4bharat/indic-parler-tts"
|
10 |
+
|
11 |
+
# Print cache directory and model files
|
12 |
+
print(f"Loading model on device: {self.device}")
|
13 |
+
|
14 |
+
# Initialize model and tokenizers exactly as in the documentation
|
15 |
+
self.model = ParlerTTSForConditionalGeneration.from_pretrained(self.model_name).to(self.device)
|
16 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
17 |
+
self.description_tokenizer = AutoTokenizer.from_pretrained(self.model.config.text_encoder._name_or_path)
|
18 |
+
|
19 |
+
print("Model loaded successfully")
|
20 |
+
|
21 |
+
def generate_audio(self, text, description):
|
22 |
+
try:
|
23 |
+
# Tokenize exactly as shown in the documentation
|
24 |
+
description_inputs = self.description_tokenizer(
|
25 |
+
description,
|
26 |
+
return_tensors="pt"
|
27 |
+
).to(self.device)
|
28 |
+
|
29 |
+
prompt_inputs = self.tokenizer(
|
30 |
+
text,
|
31 |
+
return_tensors="pt"
|
32 |
+
).to(self.device)
|
33 |
+
|
34 |
+
# Generate audio
|
35 |
+
with torch.no_grad():
|
36 |
+
generation = self.model.generate(
|
37 |
+
input_ids=description_inputs.input_ids,
|
38 |
+
attention_mask=description_inputs.attention_mask,
|
39 |
+
prompt_input_ids=prompt_inputs.input_ids,
|
40 |
+
prompt_attention_mask=prompt_inputs.attention_mask
|
41 |
+
)
|
42 |
+
|
43 |
+
# Convert to numpy array
|
44 |
+
audio_array = generation.cpu().numpy().squeeze()
|
45 |
+
|
46 |
+
return audio_array
|
47 |
+
|
48 |
+
except Exception as e:
|
49 |
+
print(f"Error in speech generation: {str(e)}")
|
50 |
+
raise
|