tokensandcharms commited on
Commit
190b210
·
verified ·
1 Parent(s): 1569a17

Create gpt_train.py

Browse files
Files changed (1) hide show
  1. gpt_train.py +221 -0
gpt_train.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import gc
4
+ from pathlib import Path
5
+
6
+ from trainer import Trainer, TrainerArgs
7
+
8
+ from TTS.config.shared_configs import BaseDatasetConfig
9
+ from TTS.tts.datasets import load_tts_samples
10
+ from TTS.tts.layers.xtts.trainer.gpt_trainer import GPTArgs, GPTTrainer, GPTTrainerConfig, XttsAudioConfig
11
+ from TTS.utils.manage import ModelManager
12
+ import shutil
13
+
14
+
15
+ def train_gpt(custom_model,version, language, num_epochs, batch_size, grad_acumm, train_csv, eval_csv, output_path, max_audio_length=255995):
16
+ # Logging parameters
17
+ RUN_NAME = "GPT_XTTS_FT"
18
+ PROJECT_NAME = "XTTS_trainer"
19
+ DASHBOARD_LOGGER = "tensorboard"
20
+ LOGGER_URI = None
21
+
22
+ # print(f"XTTS version = {version}")
23
+
24
+ # Set here the path that the checkpoints will be saved. Default: ./run/training/
25
+ OUT_PATH = os.path.join(output_path, "run", "training")
26
+
27
+ # Training Parameters
28
+ OPTIMIZER_WD_ONLY_ON_WEIGHTS = True # for multi-gpu training please make it False
29
+ START_WITH_EVAL = False # if True it will star with evaluation
30
+ BATCH_SIZE = batch_size # set here the batch size
31
+ GRAD_ACUMM_STEPS = grad_acumm # set here the grad accumulation steps
32
+
33
+
34
+ # Define here the dataset that you want to use for the fine-tuning on.
35
+ config_dataset = BaseDatasetConfig(
36
+ formatter="coqui",
37
+ dataset_name="ft_dataset",
38
+ path=os.path.dirname(train_csv),
39
+ meta_file_train=train_csv,
40
+ meta_file_val=eval_csv,
41
+ language=language,
42
+ )
43
+
44
+ # Add here the configs of the datasets
45
+ DATASETS_CONFIG_LIST = [config_dataset]
46
+
47
+ # Define the path where XTTS v2.0.1 files will be downloaded
48
+ CHECKPOINTS_OUT_PATH = os.path.join(Path.cwd(), "base_models",f"{version}")
49
+ os.makedirs(CHECKPOINTS_OUT_PATH, exist_ok=True)
50
+
51
+
52
+ # DVAE files
53
+ DVAE_CHECKPOINT_LINK = "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/dvae.pth"
54
+ MEL_NORM_LINK = "https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/mel_stats.pth"
55
+
56
+ # Set the path to the downloaded files
57
+ DVAE_CHECKPOINT = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(DVAE_CHECKPOINT_LINK))
58
+ MEL_NORM_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(MEL_NORM_LINK))
59
+
60
+ # download DVAE files if needed
61
+ if not os.path.isfile(DVAE_CHECKPOINT) or not os.path.isfile(MEL_NORM_FILE):
62
+ print(" > Downloading DVAE files!")
63
+ ModelManager._download_model_files([MEL_NORM_LINK, DVAE_CHECKPOINT_LINK], CHECKPOINTS_OUT_PATH, progress_bar=True)
64
+
65
+
66
+ # Download XTTS v2.0 checkpoint if needed
67
+ TOKENIZER_FILE_LINK = f"https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/{version}/vocab.json"
68
+ XTTS_CHECKPOINT_LINK = f"https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/{version}/model.pth"
69
+ XTTS_CONFIG_LINK = f"https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/{version}/config.json"
70
+ XTTS_SPEAKER_LINK = f"https://coqui.gateway.scarf.sh/hf-coqui/XTTS-v2/main/speakers_xtts.pth"
71
+
72
+ # XTTS transfer learning parameters: You we need to provide the paths of XTTS model checkpoint that you want to do the fine tuning.
73
+ TOKENIZER_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(TOKENIZER_FILE_LINK)) # vocab.json file
74
+ XTTS_CHECKPOINT = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(XTTS_CHECKPOINT_LINK)) # model.pth file
75
+ XTTS_CONFIG_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(XTTS_CONFIG_LINK)) # config.json file
76
+ XTTS_SPEAKER_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(XTTS_SPEAKER_LINK)) # speakers_xtts.pth file
77
+
78
+ # download XTTS v2.0 files if needed
79
+ if not os.path.isfile(TOKENIZER_FILE) or not os.path.isfile(XTTS_CHECKPOINT):
80
+ print(f" > Downloading XTTS v{version} files!")
81
+ ModelManager._download_model_files(
82
+ [TOKENIZER_FILE_LINK, XTTS_CHECKPOINT_LINK, XTTS_CONFIG_LINK,XTTS_SPEAKER_LINK], CHECKPOINTS_OUT_PATH, progress_bar=True
83
+ )
84
+
85
+ # Transfer this files to ready folder
86
+ READY_MODEL_PATH = os.path.join(output_path,"ready")
87
+ if not os.path.exists(READY_MODEL_PATH):
88
+ os.makedirs(READY_MODEL_PATH)
89
+
90
+ NEW_TOKENIZER_FILE = os.path.join(READY_MODEL_PATH, "vocab.json")
91
+ # NEW_XTTS_CHECKPOINT = os.path.join(READY_MODEL_PATH, "model.pth")
92
+ NEW_XTTS_CONFIG_FILE = os.path.join(READY_MODEL_PATH, "config.json")
93
+ NEW_XTTS_SPEAKER_FILE = os.path.join(READY_MODEL_PATH, "speakers_xtts.pth")
94
+
95
+ shutil.copy(TOKENIZER_FILE, NEW_TOKENIZER_FILE)
96
+ # shutil.copy(XTTS_CHECKPOINT, os.path.join(READY_MODEL_PATH, "model.pth"))
97
+ shutil.copy(XTTS_CONFIG_FILE, NEW_XTTS_CONFIG_FILE)
98
+ shutil.copy(XTTS_SPEAKER_FILE, NEW_XTTS_SPEAKER_FILE)
99
+
100
+ # Use from ready folder
101
+ TOKENIZER_FILE = NEW_TOKENIZER_FILE # vocab.json file
102
+ # XTTS_CHECKPOINT = NEW_XTTS_CHECKPOINT # model.pth file
103
+ XTTS_CONFIG_FILE = NEW_XTTS_CONFIG_FILE # config.json file
104
+ XTTS_SPEAKER_FILE = NEW_XTTS_SPEAKER_FILE # speakers_xtts.pth file
105
+
106
+
107
+ if custom_model != "":
108
+ if os.path.exists(custom_model) and custom_model.endswith('.pth'):
109
+ XTTS_CHECKPOINT = custom_model
110
+ print(f" > Loading custom model: {XTTS_CHECKPOINT}")
111
+ else:
112
+ print(" > Error: The specified custom model is not a valid .pth file path.")
113
+
114
+ num_workers = 8
115
+ if language == "ja":
116
+ num_workers = 0
117
+ # init args and config
118
+ model_args = GPTArgs(
119
+ max_conditioning_length=132300, # 6 secs
120
+ min_conditioning_length=66150, # 3 secs
121
+ debug_loading_failures=False,
122
+ max_wav_length=max_audio_length, # ~11.6 seconds
123
+ max_text_length=200,
124
+ mel_norm_file=MEL_NORM_FILE,
125
+ dvae_checkpoint=DVAE_CHECKPOINT,
126
+ xtts_checkpoint=XTTS_CHECKPOINT, # checkpoint path of the model that you want to fine-tune
127
+ tokenizer_file=TOKENIZER_FILE,
128
+ gpt_num_audio_tokens=1026,
129
+ gpt_start_audio_token=1024,
130
+ gpt_stop_audio_token=1025,
131
+ gpt_use_masking_gt_prompt_approach=True,
132
+ gpt_use_perceiver_resampler=True,
133
+ )
134
+ # define audio config
135
+ audio_config = XttsAudioConfig(sample_rate=22050, dvae_sample_rate=22050, output_sample_rate=24000)
136
+ # training parameters config
137
+ config = GPTTrainerConfig(
138
+ epochs=num_epochs,
139
+ output_path=OUT_PATH,
140
+ model_args=model_args,
141
+ run_name=RUN_NAME,
142
+ project_name=PROJECT_NAME,
143
+ run_description="""
144
+ GPT XTTS training
145
+ """,
146
+ dashboard_logger=DASHBOARD_LOGGER,
147
+ logger_uri=LOGGER_URI,
148
+ audio=audio_config,
149
+ batch_size=BATCH_SIZE,
150
+ batch_group_size=48,
151
+ eval_batch_size=BATCH_SIZE,
152
+ num_loader_workers=num_workers,
153
+ eval_split_max_size=256,
154
+ print_step=50,
155
+ plot_step=100,
156
+ log_model_step=100,
157
+ save_step=1000,
158
+ save_n_checkpoints=1,
159
+ save_checkpoints=True,
160
+ # target_loss="loss",
161
+ print_eval=False,
162
+ # Optimizer values like tortoise, pytorch implementation with modifications to not apply WD to non-weight parameters.
163
+ optimizer="AdamW",
164
+ optimizer_wd_only_on_weights=OPTIMIZER_WD_ONLY_ON_WEIGHTS,
165
+ optimizer_params={"betas": [0.9, 0.96], "eps": 1e-8, "weight_decay": 1e-2},
166
+ lr=5e-06, # learning rate
167
+ lr_scheduler="MultiStepLR",
168
+ # it was adjusted accordly for the new step scheme
169
+ lr_scheduler_params={"milestones": [50000 * 18, 150000 * 18, 300000 * 18], "gamma": 0.5, "last_epoch": -1},
170
+ test_sentences=[],
171
+ )
172
+
173
+ # init the model from config
174
+ model = GPTTrainer.init_from_config(config)
175
+
176
+ # load training samples
177
+ train_samples, eval_samples = load_tts_samples(
178
+ DATASETS_CONFIG_LIST,
179
+ eval_split=True,
180
+ eval_split_max_size=config.eval_split_max_size,
181
+ eval_split_size=config.eval_split_size,
182
+ )
183
+
184
+ # init the trainer and 🚀
185
+ trainer = Trainer(
186
+ TrainerArgs(
187
+ restore_path=None, # xtts checkpoint is restored via xtts_checkpoint key so no need of restore it using Trainer restore_path parameter
188
+ skip_train_epoch=False,
189
+ start_with_eval=START_WITH_EVAL,
190
+ grad_accum_steps=GRAD_ACUMM_STEPS,
191
+ ),
192
+ config,
193
+ output_path=OUT_PATH,
194
+ model=model,
195
+ train_samples=train_samples,
196
+ eval_samples=eval_samples,
197
+ )
198
+ trainer.fit()
199
+
200
+ # get the longest text audio file to use as speaker reference
201
+ samples_len = [len(item["text"].split(" ")) for item in train_samples]
202
+ longest_text_idx = samples_len.index(max(samples_len))
203
+ speaker_ref = train_samples[longest_text_idx]["audio_file"]
204
+
205
+ trainer_out_path = trainer.output_path
206
+
207
+ # close file handlers and remove them from the logger
208
+ for handler in logging.getLogger('trainer').handlers:
209
+ if isinstance(handler, logging.FileHandler):
210
+ handler.close()
211
+ logging.getLogger('trainer').removeHandler(handler)
212
+
213
+ # now you should be able to delete the log file
214
+ log_file = os.path.join(trainer.output_path, f"trainer_{trainer.args.rank}_log.txt")
215
+ os.remove(log_file)
216
+
217
+ # deallocate VRAM and RAM
218
+ del model, trainer, train_samples, eval_samples
219
+ gc.collect()
220
+
221
+ return XTTS_SPEAKER_FILE,XTTS_CONFIG_FILE, XTTS_CHECKPOINT, TOKENIZER_FILE, trainer_out_path, speaker_ref