Prompt48 commited on
Commit
e09fff9
·
verified ·
1 Parent(s): d1ebcb6

Upload edit\Qwen3-TTS-test\finetuning\sft_12hz.py with huggingface_hub

Browse files
edit//Qwen3-TTS-test//finetuning//sft_12hz.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2026 The Alibaba Qwen team.
3
+ # SPDX-License-Identifier: Apache-2.0
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
+ import argparse
17
+ import json
18
+ import os
19
+ import shutil
20
+
21
+ import torch
22
+ from accelerate import Accelerator
23
+ from dataset import TTSDataset
24
+ from qwen_tts.inference.qwen3_tts_model import Qwen3TTSModel
25
+ from safetensors.torch import save_file
26
+ from torch.optim import AdamW
27
+ from torch.utils.data import DataLoader
28
+ from transformers import AutoConfig
29
+
30
+ target_speaker_embedding = None
31
+ def train():
32
+ global target_speaker_embedding
33
+
34
+ parser = argparse.ArgumentParser()
35
+ parser.add_argument("--init_model_path", type=str, default="Qwen/Qwen3-TTS-12Hz-1.7B-Base")
36
+ parser.add_argument("--output_model_path", type=str, default="output")
37
+ parser.add_argument("--train_jsonl", type=str, required=True)
38
+ parser.add_argument("--batch_size", type=int, default=2)
39
+ parser.add_argument("--lr", type=float, default=2e-5)
40
+ parser.add_argument("--num_epochs", type=int, default=3)
41
+ parser.add_argument("--speaker_name", type=str, default="speaker_test")
42
+ args = parser.parse_args()
43
+
44
+ accelerator = Accelerator(gradient_accumulation_steps=4, mixed_precision="bf16", log_with="tensorboard")
45
+
46
+ MODEL_PATH = args.init_model_path
47
+
48
+ qwen3tts = Qwen3TTSModel.from_pretrained(
49
+ MODEL_PATH,
50
+ torch_dtype=torch.bfloat16,
51
+ attn_implementation="flash_attention_2",
52
+ )
53
+ config = AutoConfig.from_pretrained(MODEL_PATH)
54
+
55
+ train_data = open(args.train_jsonl).readlines()
56
+ train_data = [json.loads(line) for line in train_data]
57
+ dataset = TTSDataset(train_data, qwen3tts.processor, config)
58
+ train_dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True, collate_fn=dataset.collate_fn)
59
+
60
+ optimizer = AdamW(qwen3tts.model.parameters(), lr=args.lr, weight_decay=0.01)
61
+
62
+ model, optimizer, train_dataloader = accelerator.prepare(
63
+ qwen3tts.model, optimizer, train_dataloader
64
+ )
65
+
66
+ num_epochs = args.num_epochs
67
+ model.train()
68
+
69
+ for epoch in range(num_epochs):
70
+ for step, batch in enumerate(train_dataloader):
71
+ with accelerator.accumulate(model):
72
+
73
+ input_ids = batch['input_ids']
74
+ codec_ids = batch['codec_ids']
75
+ ref_mels = batch['ref_mels']
76
+ text_embedding_mask = batch['text_embedding_mask']
77
+ codec_embedding_mask = batch['codec_embedding_mask']
78
+ attention_mask = batch['attention_mask']
79
+ codec_0_labels = batch['codec_0_labels']
80
+ codec_mask = batch['codec_mask']
81
+
82
+ speaker_embedding = model.speaker_encoder(ref_mels.to(model.device).to(model.dtype)).detach()
83
+ if target_speaker_embedding is None:
84
+ target_speaker_embedding = speaker_embedding
85
+
86
+ input_text_ids = input_ids[:, :, 0]
87
+ input_codec_ids = input_ids[:, :, 1]
88
+
89
+ input_text_embedding = model.talker.model.text_embedding(input_text_ids) * text_embedding_mask
90
+ input_codec_embedding = model.talker.model.codec_embedding(input_codec_ids) * codec_embedding_mask
91
+ input_codec_embedding[:, 6, :] = speaker_embedding
92
+
93
+ input_embeddings = input_text_embedding + input_codec_embedding
94
+
95
+ for i in range(1, 16):
96
+ codec_i_embedding = model.talker.code_predictor.get_input_embeddings()[i - 1](codec_ids[:, :, i])
97
+ codec_i_embedding = codec_i_embedding * codec_mask.unsqueeze(-1)
98
+ input_embeddings = input_embeddings + codec_i_embedding
99
+
100
+ outputs = model.talker(
101
+ inputs_embeds=input_embeddings[:, :-1, :],
102
+ attention_mask=attention_mask[:, :-1],
103
+ labels=codec_0_labels[:, 1:],
104
+ output_hidden_states=True
105
+ )
106
+
107
+ hidden_states = outputs.hidden_states[0][-1]
108
+ talker_hidden_states = hidden_states[codec_mask[:, :-1]]
109
+ talker_codec_ids = codec_ids[codec_mask]
110
+
111
+ sub_talker_logits, sub_talker_loss = model.talker.forward_sub_talker_finetune(talker_codec_ids, talker_hidden_states)
112
+
113
+ loss = outputs.loss + 0.3 * sub_talker_loss
114
+
115
+ accelerator.backward(loss)
116
+
117
+ if accelerator.sync_gradients:
118
+ accelerator.clip_grad_norm_(model.parameters(), 1.0)
119
+
120
+ optimizer.step()
121
+ optimizer.zero_grad()
122
+
123
+ if step % 10 == 0:
124
+ accelerator.print(f"Epoch {epoch} | Step {step} | Loss: {loss.item():.4f}")
125
+
126
+ if accelerator.is_main_process:
127
+ output_dir = os.path.join(args.output_model_path, f"checkpoint-epoch-{epoch}")
128
+ shutil.copytree(MODEL_PATH, output_dir, dirs_exist_ok=True)
129
+
130
+ input_config_file = os.path.join(MODEL_PATH, "config.json")
131
+ output_config_file = os.path.join(output_dir, "config.json")
132
+ with open(input_config_file, 'r', encoding='utf-8') as f:
133
+ config_dict = json.load(f)
134
+ config_dict["tts_model_type"] = "custom_voice"
135
+ talker_config = config_dict.get("talker_config", {})
136
+ talker_config["spk_id"] = {
137
+ args.speaker_name: 3000
138
+ }
139
+ talker_config["spk_is_dialect"] = {
140
+ args.speaker_name: False
141
+ }
142
+ config_dict["talker_config"] = talker_config
143
+
144
+ with open(output_config_file, 'w', encoding='utf-8') as f:
145
+ json.dump(config_dict, f, indent=2, ensure_ascii=False)
146
+
147
+ unwrapped_model = accelerator.unwrap_model(model)
148
+ state_dict = {k: v.detach().to("cpu") for k, v in unwrapped_model.state_dict().items()}
149
+
150
+ drop_prefix = "speaker_encoder"
151
+ keys_to_drop = [k for k in state_dict.keys() if k.startswith(drop_prefix)]
152
+ for k in keys_to_drop:
153
+ del state_dict[k]
154
+
155
+ weight = state_dict['talker.model.codec_embedding.weight']
156
+ state_dict['talker.model.codec_embedding.weight'][3000] = target_speaker_embedding[0].detach().to(weight.device).to(weight.dtype)
157
+ save_path = os.path.join(output_dir, "model.safetensors")
158
+ save_file(state_dict, save_path)
159
+
160
+ if __name__ == "__main__":
161
+ train()