Mahiruoshi commited on
Commit
f8a0cc5
1 Parent(s): 14e5e89

Upload 68 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. README.md +10 -0
  3. app.py +251 -0
  4. attentions.py +392 -0
  5. checkpoints/Default/config.json +35 -0
  6. checkpoints/Default/model.onnx +3 -0
  7. checkpoints/info.json +221 -0
  8. cleaners/JapaneseCleaner.dll +3 -0
  9. cleaners/char.bin +3 -0
  10. cleaners/matrix.bin +3 -0
  11. cleaners/sys.dic +3 -0
  12. cleaners/unk.dic +0 -0
  13. commons.py +161 -0
  14. data_utils.py +307 -0
  15. export_onnx.py +140 -0
  16. losses.py +58 -0
  17. main.py +255 -0
  18. mel_processing.py +137 -0
  19. models.py +672 -0
  20. modules.py +469 -0
  21. moe/config.json +25 -0
  22. moe/configuration_chatglm.py +92 -0
  23. moe/modeling_chatglm.py +1157 -0
  24. moe/pytorch_model.bin.index.json +375 -0
  25. moe/quantization.py +187 -0
  26. moe/temp1.wav +0 -0
  27. moe/temp2.wav +0 -0
  28. moe/tokenization_chatglm.py +345 -0
  29. moe/tokenizer_config.json +19 -0
  30. output.wav +0 -0
  31. requirements.txt +24 -0
  32. text/LICENSE +19 -0
  33. text/__init__.py +56 -0
  34. text/__pycache__/__init__.cpython-37.pyc +0 -0
  35. text/__pycache__/__init__.cpython-38.pyc +0 -0
  36. text/__pycache__/__init__.cpython-39.pyc +0 -0
  37. text/__pycache__/cleaners.cpython-37.pyc +0 -0
  38. text/__pycache__/cleaners.cpython-38.pyc +0 -0
  39. text/__pycache__/cleaners.cpython-39.pyc +0 -0
  40. text/__pycache__/english.cpython-37.pyc +0 -0
  41. text/__pycache__/english.cpython-38.pyc +0 -0
  42. text/__pycache__/english.cpython-39.pyc +0 -0
  43. text/__pycache__/japanese.cpython-37.pyc +0 -0
  44. text/__pycache__/japanese.cpython-38.pyc +0 -0
  45. text/__pycache__/japanese.cpython-39.pyc +0 -0
  46. text/__pycache__/korean.cpython-37.pyc +0 -0
  47. text/__pycache__/mandarin.cpython-37.pyc +0 -0
  48. text/__pycache__/mandarin.cpython-38.pyc +0 -0
  49. text/__pycache__/mandarin.cpython-39.pyc +0 -0
  50. text/__pycache__/sanskrit.cpython-37.pyc +0 -0
.gitattributes CHANGED
@@ -32,3 +32,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ cleaners/JapaneseCleaner.dll filter=lfs diff=lfs merge=lfs -text
36
+ cleaners/sys.dic filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,13 @@
1
  ---
 
 
 
 
 
 
 
 
2
  license: mit
3
  ---
 
 
 
1
  ---
2
+ title: Chatbot With Vits
3
+ emoji: 🚀
4
+ colorFrom: purple
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 3.23.0
8
+ app_file: app.py
9
+ pinned: false
10
  license: mit
11
  ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ logging.getLogger('numba').setLevel(logging.WARNING)
3
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
4
+ logging.getLogger('urllib3').setLevel(logging.WARNING)
5
+ from text import text_to_sequence
6
+ import numpy as np
7
+ from scipy.io import wavfile
8
+ import torch
9
+ import json
10
+ import commons
11
+ import utils
12
+ import sys
13
+ import pathlib
14
+ import onnxruntime as ort
15
+ import gradio as gr
16
+ import argparse
17
+ import time
18
+ import os
19
+ import io
20
+ from scipy.io.wavfile import write
21
+ from flask import Flask, request
22
+ from threading import Thread
23
+ import openai
24
+ import requests
25
+ class VitsGradio:
26
+ def __init__(self):
27
+ self.lan = ["中文","日文","自动"]
28
+ self.chatapi = ["gpt-3.5-turbo","gpt3"]
29
+ self.modelPaths = []
30
+ for root,dirs,files in os.walk("checkpoints"):
31
+ for dir in dirs:
32
+ self.modelPaths.append(dir)
33
+ with gr.Blocks() as self.Vits:
34
+ with gr.Tab("调试用"):
35
+ with gr.Row():
36
+ with gr.Column():
37
+ with gr.Row():
38
+ with gr.Column():
39
+ self.text = gr.TextArea(label="Text", value="你好")
40
+ with gr.Accordion(label="测试api", open=False):
41
+ self.local_chat1 = gr.Checkbox(value=False, label="使用网址+文本进行模拟")
42
+ self.url_input = gr.TextArea(label="键入测试", value="http://127.0.0.1:8080/chat?Text=")
43
+ butto = gr.Button("测试从网页端获取文本")
44
+ btnVC = gr.Button("测试tts+对话程序")
45
+ with gr.Column():
46
+ output2 = gr.TextArea(label="回复")
47
+ output1 = gr.Audio(label="采样率22050")
48
+ output3 = gr.outputs.File(label="44100hz: output.wav")
49
+ butto.click(self.Simul, inputs=[self.text, self.url_input], outputs=[output2,output3])
50
+ btnVC.click(self.tts_fn, inputs=[self.text], outputs=[output1,output2])
51
+ with gr.Tab("控制面板"):
52
+ with gr.Row():
53
+ with gr.Column():
54
+ with gr.Row():
55
+ with gr.Column():
56
+ self.api_input1 = gr.TextArea(label="输入api-key或ChATGLM模型的路径", value="https://platform.openai.com/account/api-keys")
57
+ with gr.Accordion(label="chatbot选择", open=False):
58
+ self.api_input2 = gr.Checkbox(value=True, label="采用gpt3.5")
59
+ self.local_chat1 = gr.Checkbox(value=False, label="启动本地chatbot")
60
+ self.local_chat2 = gr.Checkbox(value=True, label="是否量化")
61
+ res = gr.TextArea()
62
+ Botselection = gr.Button("聊天机器人选择")
63
+ Botselection.click(self.check_bot, inputs=[self.api_input1,self.api_input2,self.local_chat1,self.local_chat2], outputs = [res])
64
+ self.input1 = gr.Dropdown(label = "vits模型加载", choices = self.modelPaths, value = self.modelPaths[0], type = "value")
65
+ self.input2 = gr.Dropdown(label="Language", choices=self.lan, value="自动", interactive=True)
66
+ with gr.Column():
67
+ btnVC = gr.Button("Submit")
68
+ self.input3 = gr.Dropdown(label="Speaker", choices=list(range(101)), value=0, interactive=True)
69
+ self.input4 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声比例(noise scale),以控制情感", value=0.267)
70
+ self.input5 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声偏差(noise scale w),以控制音素长短", value=0.7)
71
+ self.input6 = gr.Slider(minimum=0.1, maximum=10, label="duration", value=1)
72
+ statusa = gr.TextArea()
73
+ btnVC.click(self.create_tts_fn, inputs=[self.input1, self.input2, self.input3, self.input4, self.input5, self.input6], outputs = [statusa])
74
+
75
+ def Simul(self,text,url_input):
76
+ web = url_input + text
77
+ res = requests.get(web)
78
+ music = res.content
79
+ with open('output.wav', 'wb') as code:
80
+ code.write(music)
81
+ file_path = "output.wav"
82
+ return web,file_path
83
+
84
+
85
+ def chatgpt(self,text):
86
+ self.messages.append({"role": "user", "content": text},)
87
+ chat = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages= self.messages)
88
+ reply = chat.choices[0].message.content
89
+ return reply
90
+
91
+ def ChATGLM(self,text):
92
+ if text == 'clear':
93
+ self.history = []
94
+ response, new_history = self.model.chat(self.tokenizer, text, self.history)
95
+ response = response.replace(" ",'').replace("\n",'.')
96
+ self.history = new_history
97
+ return response
98
+
99
+ def gpt3_chat(self,text):
100
+ call_name = "Waifu"
101
+ openai.api_key = args.key
102
+ identity = ""
103
+ start_sequence = '\n'+str(call_name)+':'
104
+ restart_sequence = "\nYou: "
105
+ if 1 == 1:
106
+ prompt0 = text #当期prompt
107
+ if text == 'quit':
108
+ return prompt0
109
+ prompt = identity + prompt0 + start_sequence
110
+ response = openai.Completion.create(
111
+ model="text-davinci-003",
112
+ prompt=prompt,
113
+ temperature=0.5,
114
+ max_tokens=1000,
115
+ top_p=1.0,
116
+ frequency_penalty=0.5,
117
+ presence_penalty=0.0,
118
+ stop=["\nYou:"]
119
+ )
120
+ return response['choices'][0]['text'].strip()
121
+
122
+ def check_bot(self,api_input1,api_input2,local_chat1,local_chat2):
123
+ if local_chat1:
124
+ from transformers import AutoTokenizer, AutoModel
125
+ self.tokenizer = AutoTokenizer.from_pretrained(api_input1, trust_remote_code=True)
126
+ if local_chat2:
127
+ self.model = AutoModel.from_pretrained(api_input1, trust_remote_code=True).half().quantize(4).cuda()
128
+ else:
129
+ self.model = AutoModel.from_pretrained(api_input1, trust_remote_code=True)
130
+ self.history = []
131
+ else:
132
+ self.messages = []
133
+ openai.api_key = api_input1
134
+ return "Finished"
135
+
136
+ def is_japanese(self,string):
137
+ for ch in string:
138
+ if ord(ch) > 0x3040 and ord(ch) < 0x30FF:
139
+ return True
140
+ return False
141
+
142
+ def is_english(self,string):
143
+ import re
144
+ pattern = re.compile('^[A-Za-z0-9.,:;!?()_*"\' ]+$')
145
+ if pattern.fullmatch(string):
146
+ return True
147
+ else:
148
+ return False
149
+
150
+ def get_symbols_from_json(self,path):
151
+ assert os.path.isfile(path)
152
+ with open(path, 'r') as f:
153
+ data = json.load(f)
154
+ return data['symbols']
155
+
156
+ def sle(self,language,text):
157
+ text = text.replace('\n','。').replace(' ',',')
158
+ if language == "中文":
159
+ tts_input1 = "[ZH]" + text + "[ZH]"
160
+ return tts_input1
161
+ elif language == "自动":
162
+ tts_input1 = f"[JA]{text}[JA]" if self.is_japanese(text) else f"[ZH]{text}[ZH]"
163
+ return tts_input1
164
+ elif language == "日文":
165
+ tts_input1 = "[JA]" + text + "[JA]"
166
+ return tts_input1
167
+
168
+ def get_text(self,text,hps_ms):
169
+ text_norm = text_to_sequence(text,hps_ms.data.text_cleaners)
170
+ if hps_ms.data.add_blank:
171
+ text_norm = commons.intersperse(text_norm, 0)
172
+ text_norm = torch.LongTensor(text_norm)
173
+ return text_norm
174
+
175
+ def create_tts_fn(self,path, input2, input3, n_scale= 0.667,n_scale_w = 0.8, l_scale = 1 ):
176
+ self.symbols = self.get_symbols_from_json(f"checkpoints/{path}/config.json")
177
+ self.hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json")
178
+ phone_dict = {
179
+ symbol: i for i, symbol in enumerate(self.symbols)
180
+ }
181
+ self.ort_sess = ort.InferenceSession(f"checkpoints/{path}/model.onnx")
182
+ self.language = input2
183
+ self.speaker_id = input3
184
+ self.n_scale = n_scale
185
+ self.n_scale_w = n_scale_w
186
+ self.l_scale = l_scale
187
+ print(self.language,self.speaker_id,self.n_scale)
188
+ return 'success'
189
+
190
+ def tts_fn(self,text):
191
+ if self.local_chat1:
192
+ text = self.chatgpt(text)
193
+ elif self.api_input2:
194
+ text = self.ChATGLM(text)
195
+ else:
196
+ text = self.gpt3_chat(text)
197
+ print(text)
198
+ text =self.sle(self.language,text)
199
+ seq = text_to_sequence(text, cleaner_names=self.hps.data.text_cleaners)
200
+ if self.hps.data.add_blank:
201
+ seq = commons.intersperse(seq, 0)
202
+ with torch.no_grad():
203
+ x = np.array([seq], dtype=np.int64)
204
+ x_len = np.array([x.shape[1]], dtype=np.int64)
205
+ sid = np.array([self.speaker_id], dtype=np.int64)
206
+ scales = np.array([self.n_scale, self.n_scale_w, self.l_scale], dtype=np.float32)
207
+ scales.resize(1, 3)
208
+ ort_inputs = {
209
+ 'input': x,
210
+ 'input_lengths': x_len,
211
+ 'scales': scales,
212
+ 'sid': sid
213
+ }
214
+ t1 = time.time()
215
+ audio = np.squeeze(self.ort_sess.run(None, ort_inputs))
216
+ audio *= 32767.0 / max(0.01, np.max(np.abs(audio))) * 0.6
217
+ audio = np.clip(audio, -32767.0, 32767.0)
218
+ t2 = time.time()
219
+ spending_time = "推理时间:"+str(t2-t1)+"s"
220
+ print(spending_time)
221
+ bytes_wav = bytes()
222
+ byte_io = io.BytesIO(bytes_wav)
223
+ wavfile.write('moe/temp1.wav',self.hps.data.sampling_rate, audio.astype(np.int16))
224
+ cmd = 'ffmpeg -y -i ' + 'moe/temp1.wav' + ' -ar 44100 ' + 'moe/temp2.wav'
225
+ os.system(cmd)
226
+ return (self.hps.data.sampling_rate, audio),text.replace('[JA]','').replace('[ZH]','')
227
+
228
+ app = Flask(__name__)
229
+ print("开始部署")
230
+ grVits = VitsGradio()
231
+
232
+ @app.route('/chat')
233
+ def text_api():
234
+ message = request.args.get('Text','')
235
+ audio,text = grVits.tts_fn(message)
236
+ text = text.replace('[JA]','').replace('[ZH]','')
237
+ with open('moe/temp2.wav','rb') as bit:
238
+ wav_bytes = bit.read()
239
+ headers = {
240
+ 'Content-Type': 'audio/wav',
241
+ 'Text': text.encode('utf-8')}
242
+ return wav_bytes, 200, headers
243
+
244
+ def gradio_interface():
245
+ return grVits.Vits.launch()
246
+
247
+ if __name__ == '__main__':
248
+ api_thread = Thread(target=app.run, args=("0.0.0.0", 8080))
249
+ gradio_thread = Thread(target=gradio_interface)
250
+ api_thread.start()
251
+ gradio_thread.start()
attentions.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+
7
+ import commons
8
+ from modules import LayerNorm
9
+
10
+
11
+ class Encoder(nn.Module):
12
+ def __init__(self,
13
+ hidden_channels,
14
+ filter_channels,
15
+ n_heads,
16
+ n_layers,
17
+ kernel_size=1,
18
+ p_dropout=0.,
19
+ window_size=4,
20
+ **kwargs):
21
+ super().__init__()
22
+ self.hidden_channels = hidden_channels
23
+ self.filter_channels = filter_channels
24
+ self.n_heads = n_heads
25
+ self.n_layers = n_layers
26
+ self.kernel_size = kernel_size
27
+ self.p_dropout = p_dropout
28
+ self.window_size = window_size
29
+
30
+ self.drop = nn.Dropout(p_dropout)
31
+ self.attn_layers = nn.ModuleList()
32
+ self.norm_layers_1 = nn.ModuleList()
33
+ self.ffn_layers = nn.ModuleList()
34
+ self.norm_layers_2 = nn.ModuleList()
35
+ for i in range(self.n_layers):
36
+ self.attn_layers.append(
37
+ MultiHeadAttention(hidden_channels,
38
+ hidden_channels,
39
+ n_heads,
40
+ p_dropout=p_dropout,
41
+ window_size=window_size))
42
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
43
+ self.ffn_layers.append(
44
+ FFN(hidden_channels,
45
+ hidden_channels,
46
+ filter_channels,
47
+ kernel_size,
48
+ p_dropout=p_dropout))
49
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
50
+
51
+ def forward(self, x, x_mask):
52
+ attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
53
+ x = x * x_mask
54
+ for i in range(self.n_layers):
55
+ y = self.attn_layers[i](x, x, attn_mask)
56
+ y = self.drop(y)
57
+ x = self.norm_layers_1[i](x + y)
58
+
59
+ y = self.ffn_layers[i](x, x_mask)
60
+ y = self.drop(y)
61
+ x = self.norm_layers_2[i](x + y)
62
+ x = x * x_mask
63
+ return x
64
+
65
+
66
+ class Decoder(nn.Module):
67
+ def __init__(self,
68
+ hidden_channels,
69
+ filter_channels,
70
+ n_heads,
71
+ n_layers,
72
+ kernel_size=1,
73
+ p_dropout=0.,
74
+ proximal_bias=False,
75
+ proximal_init=True,
76
+ **kwargs):
77
+ super().__init__()
78
+ self.hidden_channels = hidden_channels
79
+ self.filter_channels = filter_channels
80
+ self.n_heads = n_heads
81
+ self.n_layers = n_layers
82
+ self.kernel_size = kernel_size
83
+ self.p_dropout = p_dropout
84
+ self.proximal_bias = proximal_bias
85
+ self.proximal_init = proximal_init
86
+
87
+ self.drop = nn.Dropout(p_dropout)
88
+ self.self_attn_layers = nn.ModuleList()
89
+ self.norm_layers_0 = nn.ModuleList()
90
+ self.encdec_attn_layers = nn.ModuleList()
91
+ self.norm_layers_1 = nn.ModuleList()
92
+ self.ffn_layers = nn.ModuleList()
93
+ self.norm_layers_2 = nn.ModuleList()
94
+ for i in range(self.n_layers):
95
+ self.self_attn_layers.append(
96
+ MultiHeadAttention(hidden_channels,
97
+ hidden_channels,
98
+ n_heads,
99
+ p_dropout=p_dropout,
100
+ proximal_bias=proximal_bias,
101
+ proximal_init=proximal_init))
102
+ self.norm_layers_0.append(LayerNorm(hidden_channels))
103
+ self.encdec_attn_layers.append(
104
+ MultiHeadAttention(hidden_channels,
105
+ hidden_channels,
106
+ n_heads,
107
+ p_dropout=p_dropout))
108
+ self.norm_layers_1.append(LayerNorm(hidden_channels))
109
+ self.ffn_layers.append(
110
+ FFN(hidden_channels,
111
+ hidden_channels,
112
+ filter_channels,
113
+ kernel_size,
114
+ p_dropout=p_dropout,
115
+ causal=True))
116
+ self.norm_layers_2.append(LayerNorm(hidden_channels))
117
+
118
+ def forward(self, x, x_mask, h, h_mask):
119
+ """
120
+ x: decoder input
121
+ h: encoder output
122
+ """
123
+ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
124
+ device=x.device, dtype=x.dtype)
125
+ encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
126
+ x = x * x_mask
127
+ for i in range(self.n_layers):
128
+ y = self.self_attn_layers[i](x, x, self_attn_mask)
129
+ y = self.drop(y)
130
+ x = self.norm_layers_0[i](x + y)
131
+
132
+ y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
133
+ y = self.drop(y)
134
+ x = self.norm_layers_1[i](x + y)
135
+
136
+ y = self.ffn_layers[i](x, x_mask)
137
+ y = self.drop(y)
138
+ x = self.norm_layers_2[i](x + y)
139
+ x = x * x_mask
140
+ return x
141
+
142
+
143
+ class MultiHeadAttention(nn.Module):
144
+ def __init__(self,
145
+ channels,
146
+ out_channels,
147
+ n_heads,
148
+ p_dropout=0.,
149
+ window_size=None,
150
+ heads_share=True,
151
+ block_length=None,
152
+ proximal_bias=False,
153
+ proximal_init=False):
154
+ super().__init__()
155
+ assert channels % n_heads == 0
156
+
157
+ self.channels = channels
158
+ self.out_channels = out_channels
159
+ self.n_heads = n_heads
160
+ self.p_dropout = p_dropout
161
+ self.window_size = window_size
162
+ self.heads_share = heads_share
163
+ self.block_length = block_length
164
+ self.proximal_bias = proximal_bias
165
+ self.proximal_init = proximal_init
166
+ self.attn = None
167
+
168
+ self.k_channels = channels // n_heads
169
+ self.conv_q = nn.Conv1d(channels, channels, 1)
170
+ self.conv_k = nn.Conv1d(channels, channels, 1)
171
+ self.conv_v = nn.Conv1d(channels, channels, 1)
172
+ self.conv_o = nn.Conv1d(channels, out_channels, 1)
173
+ self.drop = nn.Dropout(p_dropout)
174
+
175
+ if window_size is not None:
176
+ n_heads_rel = 1 if heads_share else n_heads
177
+ rel_stddev = self.k_channels**-0.5
178
+ self.emb_rel_k = nn.Parameter(
179
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
180
+ * rel_stddev)
181
+ self.emb_rel_v = nn.Parameter(
182
+ torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
183
+ * rel_stddev)
184
+
185
+ nn.init.xavier_uniform_(self.conv_q.weight)
186
+ nn.init.xavier_uniform_(self.conv_k.weight)
187
+ nn.init.xavier_uniform_(self.conv_v.weight)
188
+ if proximal_init:
189
+ with torch.no_grad():
190
+ self.conv_k.weight.copy_(self.conv_q.weight)
191
+ self.conv_k.bias.copy_(self.conv_q.bias)
192
+
193
+ def forward(self, x, c, attn_mask=None):
194
+ q = self.conv_q(x)
195
+ k = self.conv_k(c)
196
+ v = self.conv_v(c)
197
+
198
+ x, self.attn = self.attention(q, k, v, mask=attn_mask)
199
+
200
+ x = self.conv_o(x)
201
+ return x
202
+
203
+ def attention(self, query, key, value, mask=None):
204
+ # reshape [b, d, t] -> [b, n_h, t, d_k]
205
+ b, d, t_s, t_t = (*key.size(), query.size(2))
206
+ query = query.view(b, self.n_heads, self.k_channels,
207
+ t_t).transpose(2, 3)
208
+ key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
209
+ value = value.view(b, self.n_heads, self.k_channels,
210
+ t_s).transpose(2, 3)
211
+
212
+ scores = torch.matmul(query / math.sqrt(self.k_channels),
213
+ key.transpose(-2, -1))
214
+ if self.window_size is not None:
215
+ msg = "Relative attention is only available for self-attention."
216
+ assert t_s == t_t, msg
217
+ key_relative_embeddings = self._get_relative_embeddings(
218
+ self.emb_rel_k, t_s)
219
+ rel_logits = self._matmul_with_relative_keys(
220
+ query / math.sqrt(self.k_channels), key_relative_embeddings)
221
+ scores_local = self._relative_position_to_absolute_position(
222
+ rel_logits)
223
+ scores = scores + scores_local
224
+ if self.proximal_bias:
225
+ msg = "Proximal bias is only available for self-attention."
226
+ assert t_s == t_t, msg
227
+ scores = scores + self._attention_bias_proximal(t_s).to(
228
+ device=scores.device, dtype=scores.dtype)
229
+ if mask is not None:
230
+ scores = scores.masked_fill(mask == 0, -1e4)
231
+ if self.block_length is not None:
232
+ msg = "Local attention is only available for self-attention."
233
+ assert t_s == t_t, msg
234
+ block_mask = torch.ones_like(scores).triu(
235
+ -self.block_length).tril(self.block_length)
236
+ scores = scores.masked_fill(block_mask == 0, -1e4)
237
+ p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
238
+ p_attn = self.drop(p_attn)
239
+ output = torch.matmul(p_attn, value)
240
+ if self.window_size is not None:
241
+ relative_weights = self._absolute_position_to_relative_position(
242
+ p_attn)
243
+ value_relative_embeddings = self._get_relative_embeddings(
244
+ self.emb_rel_v, t_s)
245
+ output = output + self._matmul_with_relative_values(
246
+ relative_weights, value_relative_embeddings)
247
+ output = output.transpose(2, 3).contiguous().view(
248
+ b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
249
+ return output, p_attn
250
+
251
+ def _matmul_with_relative_values(self, x, y):
252
+ """
253
+ x: [b, h, l, m]
254
+ y: [h or 1, m, d]
255
+ ret: [b, h, l, d]
256
+ """
257
+ ret = torch.matmul(x, y.unsqueeze(0))
258
+ return ret
259
+
260
+ def _matmul_with_relative_keys(self, x, y):
261
+ """
262
+ x: [b, h, l, d]
263
+ y: [h or 1, m, d]
264
+ ret: [b, h, l, m]
265
+ """
266
+ ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
267
+ return ret
268
+
269
+ def _get_relative_embeddings(self, relative_embeddings, length):
270
+ max_relative_position = 2 * self.window_size + 1
271
+ # Pad first before slice to avoid using cond ops.
272
+ pad_length = max(length - (self.window_size + 1), 0)
273
+ slice_start_position = max((self.window_size + 1) - length, 0)
274
+ slice_end_position = slice_start_position + 2 * length - 1
275
+ if pad_length > 0:
276
+ padded_relative_embeddings = F.pad(
277
+ relative_embeddings,
278
+ commons.convert_pad_shape([[0, 0], [pad_length, pad_length],
279
+ [0, 0]]))
280
+ else:
281
+ padded_relative_embeddings = relative_embeddings
282
+ used_relative_embeddings = padded_relative_embeddings[:,
283
+ slice_start_position:
284
+ slice_end_position]
285
+ return used_relative_embeddings
286
+
287
+ def _relative_position_to_absolute_position(self, x):
288
+ """
289
+ x: [b, h, l, 2*l-1]
290
+ ret: [b, h, l, l]
291
+ """
292
+ batch, heads, length, _ = x.size()
293
+ # Concat columns of pad to shift from relative to absolute indexing.
294
+ x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0,
295
+ 1]]))
296
+
297
+ # Concat extra elements so to add up to shape (len+1, 2*len-1).
298
+ x_flat = x.view([batch, heads, length * 2 * length])
299
+ x_flat = F.pad(
300
+ x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0,
301
+ length - 1]]))
302
+
303
+ # Reshape and slice out the padded elements.
304
+ x_final = x_flat.view([batch, heads, length + 1,
305
+ 2 * length - 1])[:, :, :length, length - 1:]
306
+ return x_final
307
+
308
+ def _absolute_position_to_relative_position(self, x):
309
+ """
310
+ x: [b, h, l, l]
311
+ ret: [b, h, l, 2*l-1]
312
+ """
313
+ batch, heads, length, _ = x.size()
314
+ # padd along column
315
+ x = F.pad(
316
+ x,
317
+ commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0,
318
+ length - 1]]))
319
+ x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
320
+ # add 0's in the beginning that will skew the elements after reshape
321
+ x_flat = F.pad(
322
+ x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
323
+ x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
324
+ return x_final
325
+
326
+ def _attention_bias_proximal(self, length):
327
+ """Bias for self-attention to encourage attention to close positions.
328
+ Args:
329
+ length: an integer scalar.
330
+ Returns:
331
+ a Tensor with shape [1, 1, length, length]
332
+ """
333
+ r = torch.arange(length, dtype=torch.float32)
334
+ diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
335
+ return torch.unsqueeze(
336
+ torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
337
+
338
+
339
+ class FFN(nn.Module):
340
+ def __init__(self,
341
+ in_channels,
342
+ out_channels,
343
+ filter_channels,
344
+ kernel_size,
345
+ p_dropout=0.,
346
+ activation=None,
347
+ causal=False):
348
+ super().__init__()
349
+ self.in_channels = in_channels
350
+ self.out_channels = out_channels
351
+ self.filter_channels = filter_channels
352
+ self.kernel_size = kernel_size
353
+ self.p_dropout = p_dropout
354
+ self.activation = activation
355
+ self.causal = causal
356
+
357
+ if causal:
358
+ self.padding = self._causal_padding
359
+ else:
360
+ self.padding = self._same_padding
361
+
362
+ self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
363
+ self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
364
+ self.drop = nn.Dropout(p_dropout)
365
+
366
+ def forward(self, x, x_mask):
367
+ x = self.conv_1(self.padding(x * x_mask))
368
+ if self.activation == "gelu":
369
+ x = x * torch.sigmoid(1.702 * x)
370
+ else:
371
+ x = torch.relu(x)
372
+ x = self.drop(x)
373
+ x = self.conv_2(self.padding(x * x_mask))
374
+ return x * x_mask
375
+
376
+ def _causal_padding(self, x):
377
+ if self.kernel_size == 1:
378
+ return x
379
+ pad_l = self.kernel_size - 1
380
+ pad_r = 0
381
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
382
+ x = F.pad(x, commons.convert_pad_shape(padding))
383
+ return x
384
+
385
+ def _same_padding(self, x):
386
+ if self.kernel_size == 1:
387
+ return x
388
+ pad_l = (self.kernel_size - 1) // 2
389
+ pad_r = self.kernel_size // 2
390
+ padding = [[0, 0], [0, 0], [pad_l, pad_r]]
391
+ x = F.pad(x, commons.convert_pad_shape(padding))
392
+ return x
checkpoints/Default/config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": {
3
+ "segment_size": 8192
4
+ },
5
+ "data": {
6
+ "text_cleaners":["zh_ja_mixture_cleaners"],
7
+ "max_wav_value": 32768.0,
8
+ "sampling_rate": 22050,
9
+ "filter_length": 1024,
10
+ "hop_length": 256,
11
+ "win_length": 1024,
12
+ "add_blank": true,
13
+ "n_speakers": 5
14
+ },
15
+ "model": {
16
+ "inter_channels": 192,
17
+ "hidden_channels": 192,
18
+ "filter_channels": 768,
19
+ "n_heads": 2,
20
+ "n_layers": 6,
21
+ "kernel_size": 3,
22
+ "p_dropout": 0.1,
23
+ "resblock": "1",
24
+ "resblock_kernel_sizes": [3,7,11],
25
+ "resblock_dilation_sizes": [[1,3,5], [1,3,5], [1,3,5]],
26
+ "upsample_rates": [8,8,2,2],
27
+ "upsample_initial_channel": 512,
28
+ "upsample_kernel_sizes": [16,16,4,4],
29
+ "n_layers_q": 3,
30
+ "use_spectral_norm": false,
31
+ "gin_channels": 256
32
+ },
33
+ "speakers": ["\u7dbe\u5730\u5be7\u3005", "\u5728\u539f\u4e03\u6d77", "\u5c0f\u8338", "\u5510\u4e50\u541f"],
34
+ "symbols": ["_", ",", ".", "!", "?", "-", "~", "\u2026", "A", "E", "I", "N", "O", "Q", "U", "a", "b", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "v", "w", "y", "z", "\u0283", "\u02a7", "\u02a6", "\u026f", "\u0279", "\u0259", "\u0265", "\u207c", "\u02b0", "`", "\u2192", "\u2193", "\u2191", " "]
35
+ }
checkpoints/Default/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ac210365de160dd5db134f9333525e4ff38426a6a24fcb73e24375b09bef15e
3
+ size 121090654
checkpoints/info.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Nijigasaki High School":{
3
+ "speakers":{
4
+ "高咲侑":{
5
+ "sid": 0,
6
+ "setting": "只选一个做不到啊",
7
+ "name": "高咲侑"
8
+ },
9
+ "歩夢":{
10
+ "sid": 1,
11
+ "setting": "只选一个做不到啊",
12
+ "name": "歩夢"
13
+ },
14
+ "かすみ":{
15
+ "sid": 2,
16
+ "setting": "只选一个做不到啊",
17
+ "name": "かすみ"
18
+ },
19
+ "しずく":{
20
+ "sid": 3,
21
+ "setting": "只选一个做不到啊",
22
+ "name": "しずく"
23
+ },
24
+ "果林":{
25
+ "sid": 4,
26
+ "setting": "只选一个做不到啊",
27
+ "name": "果林"
28
+ },
29
+ "愛":{
30
+ "sid": 5,
31
+ "setting": "只选一个做不到啊",
32
+ "name": "愛"
33
+ },
34
+ "せつ菜":{
35
+ "sid": 7,
36
+ "setting": "只选一个做不到啊",
37
+ "name": "せつ菜"
38
+ },
39
+ "エマ":{
40
+ "sid": 8,
41
+ "setting": "只选一个做不到啊",
42
+ "name": "エマ"
43
+ },
44
+ "璃奈":{
45
+ "sid": 9,
46
+ "setting": "只选一个做不到啊",
47
+ "name": "璃奈"
48
+ },
49
+ "栞子":{
50
+ "sid": 10,
51
+ "setting": "只选一个做不到啊",
52
+ "name": "栞子"
53
+ },
54
+ "ランジュ":{
55
+ "sid": 11,
56
+ "setting": "只选一个做不到啊",
57
+ "name": "ランジュ"
58
+ },
59
+ "ミア":{
60
+ "sid": 12,
61
+ "setting": "只选一个做不到啊",
62
+ "name": "ミア"
63
+ }
64
+ },
65
+ "checkpoint": "checkpoints/Nijigasaki/model.onnx"
66
+ },
67
+ "Seisho Music Academy":{
68
+ "speakers":{
69
+ "華恋":{
70
+ "sid": 21,
71
+ "setting": "只选一个做不到啊",
72
+ "name": "華恋"
73
+ },
74
+ "まひる":{
75
+ "sid": 22,
76
+ "setting": "只选一个做不到啊",
77
+ "name": "まひる"
78
+ },
79
+ "なな":{
80
+ "sid": 23,
81
+ "setting": "只选一个做不到啊",
82
+ "name": "なな"
83
+ },
84
+ "クロディーヌ":{
85
+ "sid": 24,
86
+ "setting": "只选一个做不到啊",
87
+ "name": "クロディーヌ"
88
+ },
89
+ "ひかり":{
90
+ "sid": 25,
91
+ "setting": "只选一个做不到啊",
92
+ "name": "ひかり"
93
+ },
94
+ "純那":{
95
+ "sid": 26,
96
+ "setting": "只选一个做不到啊",
97
+ "name": "純那"
98
+ },
99
+ "香子":{
100
+ "sid": 27,
101
+ "setting": "只选一个做不到啊",
102
+ "name": "香子"
103
+ },
104
+ "真矢":{
105
+ "sid": 28,
106
+ "setting": "只选一个做不到啊",
107
+ "name": "真矢"
108
+ },
109
+ "双葉":{
110
+ "sid": 29,
111
+ "setting": "只选一个做不到啊",
112
+ "name": "双葉"
113
+ }
114
+ },
115
+ "checkpoint": "checkpoints/Starlight/model.onnx"
116
+ },
117
+ "Rinmeikan Girls School":{
118
+ "speakers":{
119
+ "珠緒":{
120
+ "sid": 37,
121
+ "setting": "只选一个做不到啊",
122
+ "name": "珠緒"
123
+ },
124
+ "塁":{
125
+ "sid": 36,
126
+ "setting": "只选一个做不到啊",
127
+ "name": "塁"
128
+ },
129
+ "ゆゆ子":{
130
+ "sid": 35,
131
+ "setting": "只选一个做不到啊",
132
+ "name": "ゆゆ子"
133
+ },
134
+ "いちえ":{
135
+ "sid": 34,
136
+ "setting": "只选一个做不到啊",
137
+ "name": "いちえ"
138
+ }
139
+ },
140
+ "checkpoint": "checkpoints/Starlight/model.onnx"
141
+
142
+ },
143
+ "Frontier School of Arts":{
144
+ "speakers":{
145
+ "あるる":{
146
+ "sid": 38,
147
+ "setting": "只选一个做不到啊",
148
+ "name": "あるる"
149
+ },
150
+ "ララフィン":{
151
+ "sid": 39,
152
+ "setting": "只选一个做不到啊",
153
+ "name": "ララフィン"
154
+ },
155
+ "美空":{
156
+ "sid": 40,
157
+ "setting": "只选一个做不到啊",
158
+ "name": "美空"
159
+ },
160
+ "静羽":{
161
+ "sid": 41,
162
+ "setting": "只选一个做不到啊",
163
+ "name": "静羽"
164
+ }
165
+ },
166
+ "checkpoint": "checkpoints/Nijigasaki/model.onnx"
167
+
168
+ },
169
+ "Siegfeld Institute of Music":{
170
+ "speakers":{
171
+ "ミチル":{
172
+ "sid": 30,
173
+ "setting": "只选一个做不到啊",
174
+ "name": "ミチル"
175
+ },
176
+ "メイファン":{
177
+ "sid": 31,
178
+ "setting": "只选一个做不到啊",
179
+ "name": "メイファン"
180
+ },
181
+ "やちよ":{
182
+ "sid": 32,
183
+ "setting": "只选一个做不到啊",
184
+ "name": "やちよ"
185
+ },
186
+ "晶":{
187
+ "sid": 33,
188
+ "setting": "只选一个做不到啊",
189
+ "name": "晶"
190
+ }
191
+ },
192
+ "checkpoint": "checkpoints/Starlight/model.onnx"
193
+
194
+ },
195
+ "Youzusoft":{
196
+ "speakers":{
197
+ "宁宁":{
198
+ "sid": 0,
199
+ "setting": "只选一个做不到啊",
200
+ "name": "宁宁"
201
+ },
202
+ "在原七海":{
203
+ "sid": 1,
204
+ "setting": "只选一个做不到啊",
205
+ "name": "在原七海"
206
+ },
207
+ "小茸":{
208
+ "sid": 2,
209
+ "setting": "只选一个做不到啊",
210
+ "name": "小茸"
211
+ },
212
+ "唐乐吟":{
213
+ "sid": 3,
214
+ "setting": "只选一个做不到啊",
215
+ "name": "唐乐吟"
216
+ }
217
+ },
218
+ "checkpoint": "checkpoints/Default/model.onnx"
219
+
220
+ }
221
+ }
cleaners/JapaneseCleaner.dll ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a659eb68d12d4a88ef7dfde6086b9974cd4d43634f7e4bfe710d5537cdd61a75
3
+ size 3097600
cleaners/char.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:888ee94c5a8a7a26d24ab3f1b7155441351954fd51ea06b4a2f78bd742492b2f
3
+ size 262496
cleaners/matrix.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:62fd16b4f64c851d5dc352ef0d5740c5fc83ddc7c203b2b0b1fc5271969a14ce
3
+ size 3792262
cleaners/sys.dic ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca57d9029691a70a5dfb99afc2844180256161d7130da65b1a867510e129b9a6
3
+ size 103073776
cleaners/unk.dic ADDED
Binary file (5.69 kB). View file
 
commons.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch.nn import functional as F
5
+
6
+
7
+ def init_weights(m, mean=0.0, std=0.01):
8
+ classname = m.__class__.__name__
9
+ if classname.find("Conv") != -1:
10
+ m.weight.data.normal_(mean, std)
11
+
12
+
13
+ def get_padding(kernel_size, dilation=1):
14
+ return int((kernel_size * dilation - dilation) / 2)
15
+
16
+
17
+ def convert_pad_shape(pad_shape):
18
+ pad_shape = [item for sublist in reversed(pad_shape) for item in sublist]
19
+ return pad_shape
20
+
21
+
22
+ def intersperse(lst, item):
23
+ result = [item] * (len(lst) * 2 + 1)
24
+ result[1::2] = lst
25
+ return result
26
+
27
+
28
+ def kl_divergence(m_p, logs_p, m_q, logs_q):
29
+ """KL(P||Q)"""
30
+ kl = (logs_q - logs_p) - 0.5
31
+ kl += 0.5 * (torch.exp(2. * logs_p) +
32
+ ((m_p - m_q)**2)) * torch.exp(-2. * logs_q)
33
+ return kl
34
+
35
+
36
+ def rand_gumbel(shape):
37
+ """Sample from the Gumbel distribution, protect from overflows."""
38
+ uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
39
+ return -torch.log(-torch.log(uniform_samples))
40
+
41
+
42
+ def rand_gumbel_like(x):
43
+ g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
44
+ return g
45
+
46
+
47
+ def slice_segments(x, ids_str, segment_size=4):
48
+ ret = torch.zeros_like(x[:, :, :segment_size])
49
+ for i in range(x.size(0)):
50
+ idx_str = ids_str[i]
51
+ idx_end = idx_str + segment_size
52
+ ret[i] = x[i, :, idx_str:idx_end]
53
+ return ret
54
+
55
+
56
+ def rand_slice_segments(x, x_lengths=None, segment_size=4):
57
+ b, d, t = x.size()
58
+ if x_lengths is None:
59
+ x_lengths = t
60
+ ids_str_max = x_lengths - segment_size + 1
61
+ ids_str = (torch.rand([b]).to(device=x.device) *
62
+ ids_str_max).to(dtype=torch.long)
63
+ ret = slice_segments(x, ids_str, segment_size)
64
+ return ret, ids_str
65
+
66
+
67
+ def get_timing_signal_1d(length,
68
+ channels,
69
+ min_timescale=1.0,
70
+ max_timescale=1.0e4):
71
+ position = torch.arange(length, dtype=torch.float)
72
+ num_timescales = channels // 2
73
+ log_timescale_increment = (
74
+ math.log(float(max_timescale) / float(min_timescale)) /
75
+ (num_timescales - 1))
76
+ inv_timescales = min_timescale * torch.exp(
77
+ torch.arange(num_timescales, dtype=torch.float) *
78
+ -log_timescale_increment)
79
+ scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
80
+ signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
81
+ signal = F.pad(signal, [0, 0, 0, channels % 2])
82
+ signal = signal.view(1, channels, length)
83
+ return signal
84
+
85
+
86
+ def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
87
+ b, channels, length = x.size()
88
+ signal = get_timing_signal_1d(length, channels, min_timescale,
89
+ max_timescale)
90
+ return x + signal.to(dtype=x.dtype, device=x.device)
91
+
92
+
93
+ def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
94
+ b, channels, length = x.size()
95
+ signal = get_timing_signal_1d(length, channels, min_timescale,
96
+ max_timescale)
97
+ return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
98
+
99
+
100
+ def subsequent_mask(length):
101
+ mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
102
+ return mask
103
+
104
+
105
+ @torch.jit.script
106
+ def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
107
+ n_channels_int = n_channels[0]
108
+ in_act = input_a + input_b
109
+ t_act = torch.tanh(in_act[:, :n_channels_int, :])
110
+ s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
111
+ acts = t_act * s_act
112
+ return acts
113
+
114
+
115
+ def shift_1d(x):
116
+ x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
117
+ return x
118
+
119
+
120
+ def sequence_mask(length, max_length=None):
121
+ if max_length is None:
122
+ max_length = length.max()
123
+ x = torch.arange(max_length, dtype=length.dtype, device=length.device)
124
+ return x.unsqueeze(0) < length.unsqueeze(1)
125
+
126
+
127
+ def generate_path(duration, mask):
128
+ """
129
+ duration: [b, 1, t_x]
130
+ mask: [b, 1, t_y, t_x]
131
+ """
132
+ device = duration.device
133
+
134
+ b, _, t_y, t_x = mask.shape
135
+ cum_duration = torch.cumsum(duration, -1)
136
+
137
+ cum_duration_flat = cum_duration.view(b * t_x)
138
+ path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
139
+ path = path.view(b, t_x, t_y)
140
+ path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]
141
+ ]))[:, :-1]
142
+ path = path.unsqueeze(1).transpose(2, 3) * mask
143
+ return path
144
+
145
+
146
+ def clip_grad_value_(parameters, clip_value, norm_type=2):
147
+ if isinstance(parameters, torch.Tensor):
148
+ parameters = [parameters]
149
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
150
+ norm_type = float(norm_type)
151
+ if clip_value is not None:
152
+ clip_value = float(clip_value)
153
+
154
+ total_norm = 0
155
+ for p in parameters:
156
+ param_norm = p.grad.data.norm(norm_type)
157
+ total_norm += param_norm.item()**norm_type
158
+ if clip_value is not None:
159
+ p.grad.data.clamp_(min=-clip_value, max=clip_value)
160
+ total_norm = total_norm**(1. / norm_type)
161
+ return total_norm
data_utils.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+
4
+ import torch
5
+ import torchaudio
6
+ import torch.utils.data
7
+
8
+ import commons
9
+ from mel_processing import spectrogram_torch
10
+ from utils import load_filepaths_and_text
11
+
12
+
13
+ class TextAudioSpeakerLoader(torch.utils.data.Dataset):
14
+ """
15
+ 1) loads audio, speaker_id, text pairs
16
+ 2) normalizes text and converts them to sequences of integers
17
+ 3) computes spectrograms from audio files.
18
+ """
19
+ def __init__(self, audiopaths_sid_text, hparams):
20
+ self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
21
+ # self.text_cleaners = hparams.text_cleaners
22
+ self.max_wav_value = hparams.max_wav_value
23
+ self.sampling_rate = hparams.sampling_rate
24
+ self.filter_length = hparams.filter_length
25
+ self.hop_length = hparams.hop_length
26
+ self.win_length = hparams.win_length
27
+ self.sampling_rate = hparams.sampling_rate
28
+ self.src_sampling_rate = getattr(hparams, "src_sampling_rate",
29
+ self.sampling_rate)
30
+
31
+ self.cleaned_text = getattr(hparams, "cleaned_text", False)
32
+
33
+ self.add_blank = hparams.add_blank
34
+ self.min_text_len = getattr(hparams, "min_text_len", 1)
35
+ self.max_text_len = getattr(hparams, "max_text_len", 190)
36
+
37
+ phone_file = getattr(hparams, "phone_table", None)
38
+ self.phone_dict = None
39
+ if phone_file is not None:
40
+ self.phone_dict = {}
41
+ with open(phone_file) as fin:
42
+ for line in fin:
43
+ arr = line.strip().split()
44
+ self.phone_dict[arr[0]] = int(arr[1])
45
+
46
+ speaker_file = getattr(hparams, "speaker_table", None)
47
+ self.speaker_dict = None
48
+ if speaker_file is not None:
49
+ self.speaker_dict = {}
50
+ with open(speaker_file) as fin:
51
+ for line in fin:
52
+ arr = line.strip().split()
53
+ self.speaker_dict[arr[0]] = int(arr[1])
54
+
55
+ random.seed(1234)
56
+ random.shuffle(self.audiopaths_sid_text)
57
+ self._filter()
58
+
59
+ def _filter(self):
60
+ """
61
+ Filter text & store spec lengths
62
+ """
63
+ # Store spectrogram lengths for Bucketing
64
+ # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
65
+ # spec_length = wav_length // hop_length
66
+
67
+ audiopaths_sid_text_new = []
68
+ lengths = []
69
+ for item in self.audiopaths_sid_text:
70
+ audiopath = item[0]
71
+ # filename|text or filename|speaker|text
72
+ text = item[1] if len(item) == 2 else item[2]
73
+ if self.min_text_len <= len(text) and len(
74
+ text) <= self.max_text_len:
75
+ audiopaths_sid_text_new.append(item)
76
+ lengths.append(
77
+ int(
78
+ os.path.getsize(audiopath) * self.sampling_rate /
79
+ self.src_sampling_rate) // (2 * self.hop_length))
80
+ self.audiopaths_sid_text = audiopaths_sid_text_new
81
+ self.lengths = lengths
82
+
83
+ def get_audio_text_speaker_pair(self, audiopath_sid_text):
84
+ audiopath = audiopath_sid_text[0]
85
+ if len(audiopath_sid_text) == 2: # filename|text
86
+ sid = 0
87
+ text = audiopath_sid_text[1]
88
+ else: # filename|speaker|text
89
+ sid = self.speaker_dict[audiopath_sid_text[1]]
90
+ text = audiopath_sid_text[2]
91
+ text = self.get_text(text)
92
+ spec, wav = self.get_audio(audiopath)
93
+ sid = self.get_sid(sid)
94
+ return (text, spec, wav, sid)
95
+
96
+ def get_audio(self, filename):
97
+ audio, sampling_rate = torchaudio.load(filename, normalize=False)
98
+ if sampling_rate != self.sampling_rate:
99
+ audio = audio.to(torch.float)
100
+ audio = torchaudio.transforms.Resample(sampling_rate,
101
+ self.sampling_rate)(audio)
102
+ audio = audio.to(torch.int16)
103
+ audio = audio[0] # Get the first channel
104
+ audio_norm = audio / self.max_wav_value
105
+ audio_norm = audio_norm.unsqueeze(0)
106
+ spec = spectrogram_torch(audio_norm,
107
+ self.filter_length,
108
+ self.sampling_rate,
109
+ self.hop_length,
110
+ self.win_length,
111
+ center=False)
112
+ spec = torch.squeeze(spec, 0)
113
+ return spec, audio_norm
114
+
115
+ def get_text(self, text):
116
+ text_norm = [self.phone_dict[phone] for phone in text.split()]
117
+ if self.add_blank:
118
+ text_norm = commons.intersperse(text_norm, 0)
119
+ text_norm = torch.LongTensor(text_norm)
120
+ return text_norm
121
+
122
+ def get_sid(self, sid):
123
+ sid = torch.LongTensor([int(sid)])
124
+ return sid
125
+
126
+ def __getitem__(self, index):
127
+ return self.get_audio_text_speaker_pair(
128
+ self.audiopaths_sid_text[index])
129
+
130
+ def __len__(self):
131
+ return len(self.audiopaths_sid_text)
132
+
133
+
134
+ class TextAudioSpeakerCollate():
135
+ """ Zero-pads model inputs and targets
136
+ """
137
+ def __init__(self, return_ids=False):
138
+ self.return_ids = return_ids
139
+
140
+ def __call__(self, batch):
141
+ """Collate's training batch from normalized text, audio and speaker identities
142
+ PARAMS
143
+ ------
144
+ batch: [text_normalized, spec_normalized, wav_normalized, sid]
145
+ """
146
+ # Right zero-pad all one-hot text sequences to max input length
147
+ _, ids_sorted_decreasing = torch.sort(torch.LongTensor(
148
+ [x[1].size(1) for x in batch]),
149
+ dim=0,
150
+ descending=True)
151
+
152
+ max_text_len = max([len(x[0]) for x in batch])
153
+ max_spec_len = max([x[1].size(1) for x in batch])
154
+ max_wav_len = max([x[2].size(1) for x in batch])
155
+
156
+ text_lengths = torch.LongTensor(len(batch))
157
+ spec_lengths = torch.LongTensor(len(batch))
158
+ wav_lengths = torch.LongTensor(len(batch))
159
+ sid = torch.LongTensor(len(batch))
160
+
161
+ text_padded = torch.LongTensor(len(batch), max_text_len)
162
+ spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0),
163
+ max_spec_len)
164
+ wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
165
+ text_padded.zero_()
166
+ spec_padded.zero_()
167
+ wav_padded.zero_()
168
+ for i in range(len(ids_sorted_decreasing)):
169
+ row = batch[ids_sorted_decreasing[i]]
170
+
171
+ text = row[0]
172
+ text_padded[i, :text.size(0)] = text
173
+ text_lengths[i] = text.size(0)
174
+
175
+ spec = row[1]
176
+ spec_padded[i, :, :spec.size(1)] = spec
177
+ spec_lengths[i] = spec.size(1)
178
+
179
+ wav = row[2]
180
+ wav_padded[i, :, :wav.size(1)] = wav
181
+ wav_lengths[i] = wav.size(1)
182
+
183
+ sid[i] = row[3]
184
+
185
+ if self.return_ids:
186
+ return (text_padded, text_lengths, spec_padded, spec_lengths,
187
+ wav_padded, wav_lengths, sid, ids_sorted_decreasing)
188
+ return (text_padded, text_lengths, spec_padded, spec_lengths,
189
+ wav_padded, wav_lengths, sid)
190
+
191
+
192
+ class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler
193
+ ):
194
+ """
195
+ Maintain similar input lengths in a batch.
196
+ Length groups are specified by boundaries.
197
+ Ex) boundaries = [b1, b2, b3] -> any batch is included either
198
+ {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
199
+
200
+ It removes samples which are not included in the boundaries.
201
+ Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1
202
+ or length(x) > b3 are discarded.
203
+ """
204
+ def __init__(self,
205
+ dataset,
206
+ batch_size,
207
+ boundaries,
208
+ num_replicas=None,
209
+ rank=None,
210
+ shuffle=True):
211
+ super().__init__(dataset,
212
+ num_replicas=num_replicas,
213
+ rank=rank,
214
+ shuffle=shuffle)
215
+ self.lengths = dataset.lengths
216
+ self.batch_size = batch_size
217
+ self.boundaries = boundaries
218
+
219
+ self.buckets, self.num_samples_per_bucket = self._create_buckets()
220
+ self.total_size = sum(self.num_samples_per_bucket)
221
+ self.num_samples = self.total_size // self.num_replicas
222
+
223
+ def _create_buckets(self):
224
+ buckets = [[] for _ in range(len(self.boundaries) - 1)]
225
+ for i in range(len(self.lengths)):
226
+ length = self.lengths[i]
227
+ idx_bucket = self._bisect(length)
228
+ if idx_bucket != -1:
229
+ buckets[idx_bucket].append(i)
230
+
231
+ for i in range(len(buckets) - 1, 0, -1):
232
+ if len(buckets[i]) == 0:
233
+ buckets.pop(i)
234
+ self.boundaries.pop(i + 1)
235
+
236
+ num_samples_per_bucket = []
237
+ for i in range(len(buckets)):
238
+ len_bucket = len(buckets[i])
239
+ total_batch_size = self.num_replicas * self.batch_size
240
+ rem = (total_batch_size -
241
+ (len_bucket % total_batch_size)) % total_batch_size
242
+ num_samples_per_bucket.append(len_bucket + rem)
243
+ return buckets, num_samples_per_bucket
244
+
245
+ def __iter__(self):
246
+ # deterministically shuffle based on epoch
247
+ g = torch.Generator()
248
+ g.manual_seed(self.epoch)
249
+
250
+ indices = []
251
+ if self.shuffle:
252
+ for bucket in self.buckets:
253
+ indices.append(
254
+ torch.randperm(len(bucket), generator=g).tolist())
255
+ else:
256
+ for bucket in self.buckets:
257
+ indices.append(list(range(len(bucket))))
258
+
259
+ batches = []
260
+ for i in range(len(self.buckets)):
261
+ bucket = self.buckets[i]
262
+ len_bucket = len(bucket)
263
+ ids_bucket = indices[i]
264
+ num_samples_bucket = self.num_samples_per_bucket[i]
265
+
266
+ # add extra samples to make it evenly divisible
267
+ rem = num_samples_bucket - len_bucket
268
+ ids_bucket = ids_bucket + ids_bucket * (
269
+ rem // len_bucket) + ids_bucket[:(rem % len_bucket)]
270
+
271
+ # subsample
272
+ ids_bucket = ids_bucket[self.rank::self.num_replicas]
273
+
274
+ # batching
275
+ for j in range(len(ids_bucket) // self.batch_size):
276
+ batch = [
277
+ bucket[idx]
278
+ for idx in ids_bucket[j * self.batch_size:(j + 1) *
279
+ self.batch_size]
280
+ ]
281
+ batches.append(batch)
282
+
283
+ if self.shuffle:
284
+ batch_ids = torch.randperm(len(batches), generator=g).tolist()
285
+ batches = [batches[i] for i in batch_ids]
286
+ self.batches = batches
287
+
288
+ assert len(self.batches) * self.batch_size == self.num_samples
289
+ return iter(self.batches)
290
+
291
+ def _bisect(self, x, lo=0, hi=None):
292
+ if hi is None:
293
+ hi = len(self.boundaries) - 1
294
+
295
+ if hi > lo:
296
+ mid = (hi + lo) // 2
297
+ if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
298
+ return mid
299
+ elif x <= self.boundaries[mid]:
300
+ return self._bisect(x, lo, mid)
301
+ else:
302
+ return self._bisect(x, mid + 1, hi)
303
+ else:
304
+ return -1
305
+
306
+ def __len__(self):
307
+ return self.num_samples // self.batch_size
export_onnx.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022, Yongqiang Li ([email protected])
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 argparse
16
+ import json
17
+ import os
18
+ import sys
19
+
20
+ import torch
21
+
22
+ from models import SynthesizerTrn
23
+ import utils
24
+
25
+ try:
26
+ import onnxruntime as ort
27
+ except ImportError:
28
+ print('Please install onnxruntime!')
29
+ sys.exit(1)
30
+
31
+
32
+ def to_numpy(tensor):
33
+ return tensor.detach().cpu().numpy() if tensor.requires_grad \
34
+ else tensor.detach().numpy()
35
+
36
+
37
+ def get_args():
38
+ parser = argparse.ArgumentParser(description='export onnx model')
39
+ parser.add_argument('--checkpoint', required=True, help='checkpoint')
40
+ parser.add_argument('--cfg', required=True, help='config file')
41
+ parser.add_argument('--onnx_model', required=True, help='onnx model name')
42
+ # parser.add_argument('--phone_table',
43
+ # required=True,
44
+ # help='input phone dict')
45
+ # parser.add_argument('--speaker_table', default=None, help='speaker table')
46
+ # parser.add_argument("--speaker_num", required=True,
47
+ # type=int, help="speaker num")
48
+ parser.add_argument(
49
+ '--providers',
50
+ required=False,
51
+ default='CPUExecutionProvider',
52
+ choices=['CUDAExecutionProvider', 'CPUExecutionProvider'],
53
+ help='the model to send request to')
54
+ args = parser.parse_args()
55
+ return args
56
+
57
+
58
+ def get_data_from_cfg(cfg_path: str):
59
+ assert os.path.isfile(cfg_path)
60
+ with open(cfg_path, 'r') as f:
61
+ data = json.load(f)
62
+ symbols = data["symbols"]
63
+ speaker_num = data["data"]["n_speakers"]
64
+ return len(symbols), speaker_num
65
+
66
+
67
+ def main():
68
+ args = get_args()
69
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
70
+
71
+ hps = utils.get_hparams_from_file(args.cfg)
72
+ # with open(args.phone_table) as p_f:
73
+ # phone_num = len(p_f.readlines()) + 1
74
+ # num_speakers = 1
75
+ # if args.speaker_table is not None:
76
+ # num_speakers = len(open(args.speaker_table).readlines()) + 1
77
+ phone_num, num_speakers = get_data_from_cfg(args.cfg)
78
+ net_g = SynthesizerTrn(phone_num,
79
+ hps.data.filter_length // 2 + 1,
80
+ hps.train.segment_size // hps.data.hop_length,
81
+ n_speakers=num_speakers,
82
+ **hps.model)
83
+ utils.load_checkpoint(args.checkpoint, net_g, None)
84
+ net_g.forward = net_g.export_forward
85
+ net_g.eval()
86
+
87
+ seq = torch.randint(low=0, high=phone_num, size=(1, 10), dtype=torch.long)
88
+ seq_len = torch.IntTensor([seq.size(1)]).long()
89
+
90
+ # noise(可用于控制感情等变化程度) lenth(可用于控制整体语速) noisew(控制音素发音长度变化程度)
91
+ # 参考 https://github.com/gbxh/genshinTTS
92
+ scales = torch.FloatTensor([0.667, 1.0, 0.8])
93
+ # make triton dynamic shape happy
94
+ scales = scales.unsqueeze(0)
95
+ sid = torch.IntTensor([0]).long()
96
+
97
+ dummy_input = (seq, seq_len, scales, sid)
98
+ torch.onnx.export(model=net_g,
99
+ args=dummy_input,
100
+ f=args.onnx_model,
101
+ input_names=['input', 'input_lengths', 'scales', 'sid'],
102
+ output_names=['output'],
103
+ dynamic_axes={
104
+ 'input': {
105
+ 0: 'batch',
106
+ 1: 'phonemes'
107
+ },
108
+ 'input_lengths': {
109
+ 0: 'batch'
110
+ },
111
+ 'scales': {
112
+ 0: 'batch'
113
+ },
114
+ 'sid': {
115
+ 0: 'batch'
116
+ },
117
+ 'output': {
118
+ 0: 'batch',
119
+ 1: 'audio',
120
+ 2: 'audio_length'
121
+ }
122
+ },
123
+ opset_version=13,
124
+ verbose=False)
125
+
126
+ # Verify onnx precision
127
+ torch_output = net_g(seq, seq_len, scales, sid)
128
+ providers = [args.providers]
129
+ ort_sess = ort.InferenceSession(args.onnx_model, providers=providers)
130
+ ort_inputs = {
131
+ 'input': to_numpy(seq),
132
+ 'input_lengths': to_numpy(seq_len),
133
+ 'scales': to_numpy(scales),
134
+ 'sid': to_numpy(sid),
135
+ }
136
+ onnx_output = ort_sess.run(None, ort_inputs)
137
+
138
+
139
+ if __name__ == '__main__':
140
+ main()
losses.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def feature_loss(fmap_r, fmap_g):
5
+ loss = 0
6
+ for dr, dg in zip(fmap_r, fmap_g):
7
+ for rl, gl in zip(dr, dg):
8
+ rl = rl.float().detach()
9
+ gl = gl.float()
10
+ loss += torch.mean(torch.abs(rl - gl))
11
+
12
+ return loss * 2
13
+
14
+
15
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
16
+ loss = 0
17
+ r_losses = []
18
+ g_losses = []
19
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
20
+ dr = dr.float()
21
+ dg = dg.float()
22
+ r_loss = torch.mean((1 - dr)**2)
23
+ g_loss = torch.mean(dg**2)
24
+ loss += (r_loss + g_loss)
25
+ r_losses.append(r_loss.item())
26
+ g_losses.append(g_loss.item())
27
+
28
+ return loss, r_losses, g_losses
29
+
30
+
31
+ def generator_loss(disc_outputs):
32
+ loss = 0
33
+ gen_losses = []
34
+ for dg in disc_outputs:
35
+ dg = dg.float()
36
+ l = torch.mean((1 - dg)**2)
37
+ gen_losses.append(l)
38
+ loss += l
39
+
40
+ return loss, gen_losses
41
+
42
+
43
+ def kl_loss(z_p, logs_q, m_p, logs_p, z_mask):
44
+ """
45
+ z_p, logs_q: [b, h, t_t]
46
+ m_p, logs_p: [b, h, t_t]
47
+ """
48
+ z_p = z_p.float()
49
+ logs_q = logs_q.float()
50
+ m_p = m_p.float()
51
+ logs_p = logs_p.float()
52
+ z_mask = z_mask.float()
53
+
54
+ kl = logs_p - logs_q - 0.5
55
+ kl += 0.5 * ((z_p - m_p)**2) * torch.exp(-2. * logs_p)
56
+ kl = torch.sum(kl * z_mask)
57
+ l = kl / torch.sum(z_mask)
58
+ return l
main.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ logging.getLogger('numba').setLevel(logging.WARNING)
3
+ logging.getLogger('matplotlib').setLevel(logging.WARNING)
4
+ logging.getLogger('urllib3').setLevel(logging.WARNING)
5
+ opj = input("是否启用pyopenjtalk?封装版无法保证非japanese cleaners推理日语时的质量(Y/N)")
6
+ if opj == "N":
7
+ from TEXTS import text_to_sequence
8
+ else:
9
+ from text import text_to_sequence
10
+ import numpy as np
11
+ from scipy.io import wavfile
12
+ import torch
13
+ import json
14
+ import commons
15
+ import utils
16
+ import sys
17
+ import pathlib
18
+ import onnxruntime as ort
19
+ import gradio as gr
20
+ import argparse
21
+ import time
22
+ import os
23
+ import io
24
+ from scipy.io.wavfile import write
25
+ from flask import Flask, request
26
+ from threading import Thread
27
+ import openai
28
+ import requests
29
+ class VitsGradio:
30
+ def __init__(self):
31
+ self.lan = ["中文","日文","自动"]
32
+ self.chatapi = ["gpt-3.5-turbo","gpt3"]
33
+ self.modelPaths = []
34
+ for root,dirs,files in os.walk("checkpoints"):
35
+ for dir in dirs:
36
+ self.modelPaths.append(dir)
37
+ with gr.Blocks() as self.Vits:
38
+ with gr.Tab("调试用"):
39
+ with gr.Row():
40
+ with gr.Column():
41
+ with gr.Row():
42
+ with gr.Column():
43
+ self.text = gr.TextArea(label="Text", value="你好")
44
+ with gr.Accordion(label="测试api", open=False):
45
+ self.local_chat1 = gr.Checkbox(value=False, label="使用网址+文本进行模拟")
46
+ self.url_input = gr.TextArea(label="键入测试", value="http://127.0.0.1:8080/chat?Text=")
47
+ butto = gr.Button("测试从网页端获取文本")
48
+ btnVC = gr.Button("测试tts+对话程序")
49
+ with gr.Column():
50
+ output2 = gr.TextArea(label="回复")
51
+ output1 = gr.Audio(label="采样率22050")
52
+ output3 = gr.outputs.File(label="44100hz: output.wav")
53
+ butto.click(self.Simul, inputs=[self.text, self.url_input], outputs=[output2,output3])
54
+ btnVC.click(self.tts_fn, inputs=[self.text], outputs=[output1,output2])
55
+ with gr.Tab("控制面板"):
56
+ with gr.Row():
57
+ with gr.Column():
58
+ with gr.Row():
59
+ with gr.Column():
60
+ self.api_input1 = gr.TextArea(label="输入api-key或本地存储说话模型的路径", value="https://platform.openai.com/account/api-keys")
61
+ with gr.Accordion(label="chatbot选择", open=False):
62
+ self.api_input2 = gr.Checkbox(value=True, label="采用gpt3.5")
63
+ self.local_chat1 = gr.Checkbox(value=False, label="启动本地chatbot")
64
+ self.local_chat2 = gr.Checkbox(value=True, label="是否量化")
65
+ res = gr.TextArea()
66
+ Botselection = gr.Button("确认模型")
67
+ Botselection.click(self.check_bot, inputs=[self.api_input1,self.api_input2,self.local_chat1,self.local_chat2], outputs = [res])
68
+ self.input1 = gr.Dropdown(label = "模型", choices = self.modelPaths, value = self.modelPaths[0], type = "value")
69
+ self.input2 = gr.Dropdown(label="Language", choices=self.lan, value="自动", interactive=True)
70
+ with gr.Column():
71
+ btnVC = gr.Button("Submit")
72
+ self.input3 = gr.Dropdown(label="Speaker", choices=list(range(101)), value=0, interactive=True)
73
+ self.input4 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声比例(noise scale),以控制情感", value=0.267)
74
+ self.input5 = gr.Slider(minimum=0, maximum=1.0, label="更改噪声偏差(noise scale w),以控制音素长短", value=0.7)
75
+ self.input6 = gr.Slider(minimum=0.1, maximum=10, label="duration", value=1)
76
+ statusa = gr.TextArea()
77
+ btnVC.click(self.create_tts_fn, inputs=[self.input1, self.input2, self.input3, self.input4, self.input5, self.input6], outputs = [statusa])
78
+
79
+ def Simul(self,text,url_input):
80
+ web = url_input + text
81
+ res = requests.get(web)
82
+ music = res.content
83
+ with open('output.wav', 'wb') as code:
84
+ code.write(music)
85
+ file_path = "output.wav"
86
+ return web,file_path
87
+
88
+
89
+ def chatgpt(self,text):
90
+ self.messages.append({"role": "user", "content": text},)
91
+ chat = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages= self.messages)
92
+ reply = chat.choices[0].message.content
93
+ return reply
94
+
95
+ def ChATGLM(self,text):
96
+ if text == 'clear':
97
+ self.history = []
98
+ response, new_history = self.model.chat(self.tokenizer, text, self.history)
99
+ response = response.replace(" ",'').replace("\n",'.')
100
+ self.history = new_history
101
+ return response
102
+
103
+ def gpt3_chat(self,text):
104
+ call_name = "Waifu"
105
+ openai.api_key = args.key
106
+ identity = ""
107
+ start_sequence = '\n'+str(call_name)+':'
108
+ restart_sequence = "\nYou: "
109
+ if 1 == 1:
110
+ prompt0 = text #当期prompt
111
+ if text == 'quit':
112
+ return prompt0
113
+ prompt = identity + prompt0 + start_sequence
114
+ response = openai.Completion.create(
115
+ model="text-davinci-003",
116
+ prompt=prompt,
117
+ temperature=0.5,
118
+ max_tokens=1000,
119
+ top_p=1.0,
120
+ frequency_penalty=0.5,
121
+ presence_penalty=0.0,
122
+ stop=["\nYou:"]
123
+ )
124
+ return response['choices'][0]['text'].strip()
125
+
126
+ def check_bot(self,api_input1,api_input2,local_chat1,local_chat2):
127
+ if local_chat1:
128
+ from transformers import AutoTokenizer, AutoModel
129
+ self.tokenizer = AutoTokenizer.from_pretrained(api_input1, trust_remote_code=True)
130
+ if local_chat2:
131
+ self.model = AutoModel.from_pretrained(api_input1, trust_remote_code=True).half().quantize(4).cuda()
132
+ else:
133
+ self.model = AutoModel.from_pretrained(api_input1, trust_remote_code=True)
134
+ self.history = []
135
+ else:
136
+ self.messages = []
137
+ openai.api_key = api_input1
138
+ return "Finished"
139
+
140
+ def is_japanese(self,string):
141
+ for ch in string:
142
+ if ord(ch) > 0x3040 and ord(ch) < 0x30FF:
143
+ return True
144
+ return False
145
+
146
+ def is_english(self,string):
147
+ import re
148
+ pattern = re.compile('^[A-Za-z0-9.,:;!?()_*"\' ]+$')
149
+ if pattern.fullmatch(string):
150
+ return True
151
+ else:
152
+ return False
153
+
154
+ def get_symbols_from_json(self,path):
155
+ assert os.path.isfile(path)
156
+ with open(path, 'r') as f:
157
+ data = json.load(f)
158
+ return data['symbols']
159
+
160
+ def sle(self,language,text):
161
+ text = text.replace('\n','。').replace(' ',',')
162
+ if language == "中文":
163
+ tts_input1 = "[ZH]" + text + "[ZH]"
164
+ return tts_input1
165
+ elif language == "自动":
166
+ tts_input1 = f"[JA]{text}[JA]" if self.is_japanese(text) else f"[ZH]{text}[ZH]"
167
+ return tts_input1
168
+ elif language == "日文":
169
+ tts_input1 = "[JA]" + text + "[JA]"
170
+ return tts_input1
171
+
172
+ def get_text(self,text,hps_ms):
173
+ text_norm = text_to_sequence(text,hps_ms.data.text_cleaners)
174
+ if hps_ms.data.add_blank:
175
+ text_norm = commons.intersperse(text_norm, 0)
176
+ text_norm = torch.LongTensor(text_norm)
177
+ return text_norm
178
+
179
+ def create_tts_fn(self,path, input2, input3, n_scale= 0.667,n_scale_w = 0.8, l_scale = 1 ):
180
+ self.symbols = self.get_symbols_from_json(f"checkpoints/{path}/config.json")
181
+ self.hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json")
182
+ phone_dict = {
183
+ symbol: i for i, symbol in enumerate(self.symbols)
184
+ }
185
+ self.ort_sess = ort.InferenceSession(f"checkpoints/{path}/model.onnx")
186
+ self.language = input2
187
+ self.speaker_id = input3
188
+ self.n_scale = n_scale
189
+ self.n_scale_w = n_scale_w
190
+ self.l_scale = l_scale
191
+ print(self.language,self.speaker_id,self.n_scale)
192
+ return 'success'
193
+
194
+ def tts_fn(self,text):
195
+ if self.local_chat1:
196
+ text = self.chatgpt(text)
197
+ elif self.api_input2:
198
+ text = self.ChATGLM(text)
199
+ else:
200
+ text = self.gpt3_chat(text)
201
+ print(text)
202
+ text =self.sle(self.language,text)
203
+ seq = text_to_sequence(text, cleaner_names=self.hps.data.text_cleaners)
204
+ if self.hps.data.add_blank:
205
+ seq = commons.intersperse(seq, 0)
206
+ with torch.no_grad():
207
+ x = np.array([seq], dtype=np.int64)
208
+ x_len = np.array([x.shape[1]], dtype=np.int64)
209
+ sid = np.array([self.speaker_id], dtype=np.int64)
210
+ scales = np.array([self.n_scale, self.n_scale_w, self.l_scale], dtype=np.float32)
211
+ scales.resize(1, 3)
212
+ ort_inputs = {
213
+ 'input': x,
214
+ 'input_lengths': x_len,
215
+ 'scales': scales,
216
+ 'sid': sid
217
+ }
218
+ t1 = time.time()
219
+ audio = np.squeeze(self.ort_sess.run(None, ort_inputs))
220
+ audio *= 32767.0 / max(0.01, np.max(np.abs(audio))) * 0.6
221
+ audio = np.clip(audio, -32767.0, 32767.0)
222
+ t2 = time.time()
223
+ spending_time = "推理时间:"+str(t2-t1)+"s"
224
+ print(spending_time)
225
+ bytes_wav = bytes()
226
+ byte_io = io.BytesIO(bytes_wav)
227
+ wavfile.write('moe/temp1.wav',self.hps.data.sampling_rate, audio.astype(np.int16))
228
+ cmd = 'ffmpeg -y -i ' + 'moe/temp1.wav' + ' -ar 44100 ' + 'moe/temp2.wav'
229
+ os.system(cmd)
230
+ return (self.hps.data.sampling_rate, audio),text.replace('[JA]','').replace('[ZH]','')
231
+
232
+ app = Flask(__name__)
233
+ print("开始部署")
234
+ grVits = VitsGradio()
235
+
236
+ @app.route('/chat')
237
+ def text_api():
238
+ message = request.args.get('Text','')
239
+ audio,text = grVits.tts_fn(message)
240
+ text = text.replace('[JA]','').replace('[ZH]','')
241
+ with open('moe/temp2.wav','rb') as bit:
242
+ wav_bytes = bit.read()
243
+ headers = {
244
+ 'Content-Type': 'audio/wav',
245
+ 'Text': text.encode('utf-8')}
246
+ return wav_bytes, 200, headers
247
+
248
+ def gradio_interface():
249
+ return grVits.Vits.launch()
250
+
251
+ if __name__ == '__main__':
252
+ api_thread = Thread(target=app.run, args=("0.0.0.0", 8080))
253
+ gradio_thread = Thread(target=gradio_interface)
254
+ api_thread.start()
255
+ gradio_thread.start()
mel_processing.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import torch.utils.data
4
+ from librosa.filters import mel as librosa_mel_fn
5
+
6
+ MAX_WAV_VALUE = 32768.0
7
+
8
+
9
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
10
+ """
11
+ PARAMS
12
+ ------
13
+ C: compression factor
14
+ """
15
+ return torch.log(torch.clamp(x, min=clip_val) * C)
16
+
17
+
18
+ def dynamic_range_decompression_torch(x, C=1):
19
+ """
20
+ PARAMS
21
+ ------
22
+ C: compression factor used to compress
23
+ """
24
+ return torch.exp(x) / C
25
+
26
+
27
+ def spectral_normalize_torch(magnitudes):
28
+ output = dynamic_range_compression_torch(magnitudes)
29
+ return output
30
+
31
+
32
+ def spectral_de_normalize_torch(magnitudes):
33
+ output = dynamic_range_decompression_torch(magnitudes)
34
+ return output
35
+
36
+
37
+ mel_basis = {}
38
+ hann_window = {}
39
+
40
+
41
+ def spectrogram_torch(y,
42
+ n_fft,
43
+ sampling_rate,
44
+ hop_size,
45
+ win_size,
46
+ center=False):
47
+ if torch.min(y) < -1.:
48
+ print('min value is ', torch.min(y))
49
+ if torch.max(y) > 1.:
50
+ print('max value is ', torch.max(y))
51
+
52
+ global hann_window
53
+ dtype_device = str(y.dtype) + '_' + str(y.device)
54
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
55
+ if wnsize_dtype_device not in hann_window:
56
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
57
+ dtype=y.dtype, device=y.device)
58
+
59
+ y = F.pad(y.unsqueeze(1),
60
+ (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
61
+ mode='reflect')
62
+ y = y.squeeze(1)
63
+
64
+ spec = torch.stft(y,
65
+ n_fft,
66
+ hop_length=hop_size,
67
+ win_length=win_size,
68
+ window=hann_window[wnsize_dtype_device],
69
+ center=center,
70
+ pad_mode='reflect',
71
+ normalized=False,
72
+ onesided=True)
73
+
74
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
75
+ return spec
76
+
77
+
78
+ def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
79
+ global mel_basis
80
+ dtype_device = str(spec.dtype) + '_' + str(spec.device)
81
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
82
+ if fmax_dtype_device not in mel_basis:
83
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
84
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
85
+ dtype=spec.dtype, device=spec.device)
86
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
87
+ spec = spectral_normalize_torch(spec)
88
+ return spec
89
+
90
+
91
+ def mel_spectrogram_torch(y,
92
+ n_fft,
93
+ num_mels,
94
+ sampling_rate,
95
+ hop_size,
96
+ win_size,
97
+ fmin,
98
+ fmax,
99
+ center=False):
100
+ if torch.min(y) < -1.:
101
+ print('min value is ', torch.min(y))
102
+ if torch.max(y) > 1.:
103
+ print('max value is ', torch.max(y))
104
+
105
+ global mel_basis, hann_window
106
+ dtype_device = str(y.dtype) + '_' + str(y.device)
107
+ fmax_dtype_device = str(fmax) + '_' + dtype_device
108
+ wnsize_dtype_device = str(win_size) + '_' + dtype_device
109
+ if fmax_dtype_device not in mel_basis:
110
+ mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
111
+ mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
112
+ dtype=y.dtype, device=y.device)
113
+ if wnsize_dtype_device not in hann_window:
114
+ hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
115
+ dtype=y.dtype, device=y.device)
116
+
117
+ y = F.pad(y.unsqueeze(1),
118
+ (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
119
+ mode='reflect')
120
+ y = y.squeeze(1)
121
+
122
+ spec = torch.stft(y,
123
+ n_fft,
124
+ hop_length=hop_size,
125
+ win_length=win_size,
126
+ window=hann_window[wnsize_dtype_device],
127
+ center=center,
128
+ pad_mode='reflect',
129
+ normalized=False,
130
+ onesided=True)
131
+
132
+ spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
133
+
134
+ spec = torch.matmul(mel_basis[fmax_dtype_device], spec)
135
+ spec = spectral_normalize_torch(spec)
136
+
137
+ return spec
models.py ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+ from torch.nn import Conv1d, ConvTranspose1d, Conv2d
7
+ from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
8
+ import monotonic_align
9
+
10
+ import commons
11
+ import modules
12
+ import attentions
13
+ from commons import init_weights, get_padding
14
+
15
+
16
+ class StochasticDurationPredictor(nn.Module):
17
+ def __init__(self,
18
+ in_channels,
19
+ filter_channels,
20
+ kernel_size,
21
+ p_dropout,
22
+ n_flows=4,
23
+ gin_channels=0):
24
+ super().__init__()
25
+ filter_channels = in_channels # it needs to be removed from future version.
26
+ self.in_channels = in_channels
27
+ self.filter_channels = filter_channels
28
+ self.kernel_size = kernel_size
29
+ self.p_dropout = p_dropout
30
+ self.n_flows = n_flows
31
+ self.gin_channels = gin_channels
32
+
33
+ self.log_flow = modules.Log()
34
+ self.flows = nn.ModuleList()
35
+ self.flows.append(modules.ElementwiseAffine(2))
36
+ for i in range(n_flows):
37
+ self.flows.append(
38
+ modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
39
+ self.flows.append(modules.Flip())
40
+
41
+ self.post_pre = nn.Conv1d(1, filter_channels, 1)
42
+ self.post_proj = nn.Conv1d(filter_channels, filter_channels, 1)
43
+ self.post_convs = modules.DDSConv(filter_channels,
44
+ kernel_size,
45
+ n_layers=3,
46
+ p_dropout=p_dropout)
47
+ self.post_flows = nn.ModuleList()
48
+ self.post_flows.append(modules.ElementwiseAffine(2))
49
+ for i in range(4):
50
+ self.post_flows.append(
51
+ modules.ConvFlow(2, filter_channels, kernel_size, n_layers=3))
52
+ self.post_flows.append(modules.Flip())
53
+
54
+ self.pre = nn.Conv1d(in_channels, filter_channels, 1)
55
+ self.proj = nn.Conv1d(filter_channels, filter_channels, 1)
56
+ self.convs = modules.DDSConv(filter_channels,
57
+ kernel_size,
58
+ n_layers=3,
59
+ p_dropout=p_dropout)
60
+ if gin_channels != 0:
61
+ self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
62
+
63
+ def forward(self,
64
+ x,
65
+ x_mask,
66
+ w=None,
67
+ g=None,
68
+ reverse=False,
69
+ noise_scale=1.0):
70
+ x = torch.detach(x)
71
+ x = self.pre(x)
72
+ if g is not None:
73
+ g = torch.detach(g)
74
+ x = x + self.cond(g)
75
+ x = self.convs(x, x_mask)
76
+ x = self.proj(x) * x_mask
77
+
78
+ if not reverse:
79
+ flows = self.flows
80
+ assert w is not None
81
+
82
+ logdet_tot_q = 0
83
+ h_w = self.post_pre(w)
84
+ h_w = self.post_convs(h_w, x_mask)
85
+ h_w = self.post_proj(h_w) * x_mask
86
+ e_q = torch.randn(w.size(0), 2, w.size(2)).to(
87
+ device=x.device, dtype=x.dtype) * x_mask
88
+ z_q = e_q
89
+ for flow in self.post_flows:
90
+ z_q, logdet_q = flow(z_q, x_mask, g=(x + h_w))
91
+ logdet_tot_q += logdet_q
92
+ z_u, z1 = torch.split(z_q, [1, 1], 1)
93
+ u = torch.sigmoid(z_u) * x_mask
94
+ z0 = (w - u) * x_mask
95
+ logdet_tot_q += torch.sum(
96
+ (F.logsigmoid(z_u) + F.logsigmoid(-z_u)) * x_mask, [1, 2])
97
+ logq = torch.sum(
98
+ -0.5 * (math.log(2 * math.pi) +
99
+ (e_q**2)) * x_mask, [1, 2]) - logdet_tot_q
100
+
101
+ logdet_tot = 0
102
+ z0, logdet = self.log_flow(z0, x_mask)
103
+ logdet_tot += logdet
104
+ z = torch.cat([z0, z1], 1)
105
+ for flow in flows:
106
+ z, logdet = flow(z, x_mask, g=x, reverse=reverse)
107
+ logdet_tot = logdet_tot + logdet
108
+ nll = torch.sum(0.5 * (math.log(2 * math.pi) +
109
+ (z**2)) * x_mask, [1, 2]) - logdet_tot
110
+ return nll + logq # [b]
111
+ else:
112
+ flows = list(reversed(self.flows))
113
+ flows = flows[:-2] + [flows[-1]] # remove a useless vflow
114
+ z = torch.randn(x.size(0), 2, x.size(2)).to(
115
+ device=x.device, dtype=x.dtype) * noise_scale
116
+ for flow in flows:
117
+ z = flow(z, x_mask, g=x, reverse=reverse)
118
+ z0, z1 = torch.split(z, [1, 1], 1)
119
+ logw = z0
120
+ return logw
121
+
122
+
123
+ class DurationPredictor(nn.Module):
124
+ def __init__(self,
125
+ in_channels,
126
+ filter_channels,
127
+ kernel_size,
128
+ p_dropout,
129
+ gin_channels=0):
130
+ super().__init__()
131
+
132
+ self.in_channels = in_channels
133
+ self.filter_channels = filter_channels
134
+ self.kernel_size = kernel_size
135
+ self.p_dropout = p_dropout
136
+ self.gin_channels = gin_channels
137
+
138
+ self.drop = nn.Dropout(p_dropout)
139
+ self.conv_1 = nn.Conv1d(in_channels,
140
+ filter_channels,
141
+ kernel_size,
142
+ padding=kernel_size // 2)
143
+ self.norm_1 = modules.LayerNorm(filter_channels)
144
+ self.conv_2 = nn.Conv1d(filter_channels,
145
+ filter_channels,
146
+ kernel_size,
147
+ padding=kernel_size // 2)
148
+ self.norm_2 = modules.LayerNorm(filter_channels)
149
+ self.proj = nn.Conv1d(filter_channels, 1, 1)
150
+
151
+ if gin_channels != 0:
152
+ self.cond = nn.Conv1d(gin_channels, in_channels, 1)
153
+
154
+ def forward(self, x, x_mask, g=None):
155
+ x = torch.detach(x)
156
+ if g is not None:
157
+ g = torch.detach(g)
158
+ x = x + self.cond(g)
159
+ x = self.conv_1(x * x_mask)
160
+ x = torch.relu(x)
161
+ x = self.norm_1(x)
162
+ x = self.drop(x)
163
+ x = self.conv_2(x * x_mask)
164
+ x = torch.relu(x)
165
+ x = self.norm_2(x)
166
+ x = self.drop(x)
167
+ x = self.proj(x * x_mask)
168
+ return x * x_mask
169
+
170
+
171
+ class TextEncoder(nn.Module):
172
+ def __init__(self, n_vocab, out_channels, hidden_channels, filter_channels,
173
+ n_heads, n_layers, kernel_size, p_dropout):
174
+ super().__init__()
175
+ self.n_vocab = n_vocab
176
+ self.out_channels = out_channels
177
+ self.hidden_channels = hidden_channels
178
+ self.filter_channels = filter_channels
179
+ self.n_heads = n_heads
180
+ self.n_layers = n_layers
181
+ self.kernel_size = kernel_size
182
+ self.p_dropout = p_dropout
183
+
184
+ self.emb = nn.Embedding(n_vocab, hidden_channels)
185
+ nn.init.normal_(self.emb.weight, 0.0, hidden_channels**-0.5)
186
+
187
+ self.encoder = attentions.Encoder(hidden_channels, filter_channels,
188
+ n_heads, n_layers, kernel_size,
189
+ p_dropout)
190
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
191
+
192
+ def forward(self, x, x_lengths):
193
+ x = self.emb(x) * math.sqrt(self.hidden_channels) # [b, t, h]
194
+ x = torch.transpose(x, 1, -1) # [b, h, t]
195
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)),
196
+ 1).to(x.dtype)
197
+
198
+ x = self.encoder(x * x_mask, x_mask)
199
+ stats = self.proj(x) * x_mask
200
+
201
+ m, logs = torch.split(stats, self.out_channels, dim=1)
202
+ return x, m, logs, x_mask
203
+
204
+
205
+ class ResidualCouplingBlock(nn.Module):
206
+ def __init__(self,
207
+ channels,
208
+ hidden_channels,
209
+ kernel_size,
210
+ dilation_rate,
211
+ n_layers,
212
+ n_flows=4,
213
+ gin_channels=0):
214
+ super().__init__()
215
+ self.channels = channels
216
+ self.hidden_channels = hidden_channels
217
+ self.kernel_size = kernel_size
218
+ self.dilation_rate = dilation_rate
219
+ self.n_layers = n_layers
220
+ self.n_flows = n_flows
221
+ self.gin_channels = gin_channels
222
+
223
+ self.flows = nn.ModuleList()
224
+ for i in range(n_flows):
225
+ self.flows.append(
226
+ modules.ResidualCouplingLayer(channels,
227
+ hidden_channels,
228
+ kernel_size,
229
+ dilation_rate,
230
+ n_layers,
231
+ gin_channels=gin_channels,
232
+ mean_only=True))
233
+ self.flows.append(modules.Flip())
234
+
235
+ def forward(self, x, x_mask, g=None, reverse=False):
236
+ if not reverse:
237
+ for flow in self.flows:
238
+ x, _ = flow(x, x_mask, g=g, reverse=reverse)
239
+ else:
240
+ for flow in reversed(self.flows):
241
+ x = flow(x, x_mask, g=g, reverse=reverse)
242
+ return x
243
+
244
+
245
+ class PosteriorEncoder(nn.Module):
246
+ def __init__(self,
247
+ in_channels,
248
+ out_channels,
249
+ hidden_channels,
250
+ kernel_size,
251
+ dilation_rate,
252
+ n_layers,
253
+ gin_channels=0):
254
+ super().__init__()
255
+ self.in_channels = in_channels
256
+ self.out_channels = out_channels
257
+ self.hidden_channels = hidden_channels
258
+ self.kernel_size = kernel_size
259
+ self.dilation_rate = dilation_rate
260
+ self.n_layers = n_layers
261
+ self.gin_channels = gin_channels
262
+
263
+ self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
264
+ self.enc = modules.WN(hidden_channels,
265
+ kernel_size,
266
+ dilation_rate,
267
+ n_layers,
268
+ gin_channels=gin_channels)
269
+ self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
270
+
271
+ def forward(self, x, x_lengths, g=None):
272
+ x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)),
273
+ 1).to(x.dtype)
274
+ x = self.pre(x) * x_mask
275
+ x = self.enc(x, x_mask, g=g)
276
+ stats = self.proj(x) * x_mask
277
+ m, logs = torch.split(stats, self.out_channels, dim=1)
278
+ z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
279
+ return z, m, logs, x_mask
280
+
281
+
282
+ class Generator(torch.nn.Module):
283
+ def __init__(self,
284
+ initial_channel,
285
+ resblock,
286
+ resblock_kernel_sizes,
287
+ resblock_dilation_sizes,
288
+ upsample_rates,
289
+ upsample_initial_channel,
290
+ upsample_kernel_sizes,
291
+ gin_channels=0):
292
+ super(Generator, self).__init__()
293
+ self.num_kernels = len(resblock_kernel_sizes)
294
+ self.num_upsamples = len(upsample_rates)
295
+ self.conv_pre = Conv1d(initial_channel,
296
+ upsample_initial_channel,
297
+ 7,
298
+ 1,
299
+ padding=3)
300
+ resblock = modules.ResBlock1 if resblock == '1' else modules.ResBlock2
301
+
302
+ self.ups = nn.ModuleList()
303
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
304
+ self.ups.append(
305
+ weight_norm(
306
+ ConvTranspose1d(upsample_initial_channel // (2**i),
307
+ upsample_initial_channel // (2**(i + 1)),
308
+ k,
309
+ u,
310
+ padding=(k - u) // 2)))
311
+
312
+ self.resblocks = nn.ModuleList()
313
+ for i in range(len(self.ups)):
314
+ ch = upsample_initial_channel // (2**(i + 1))
315
+ for j, (k, d) in enumerate(
316
+ zip(resblock_kernel_sizes, resblock_dilation_sizes)):
317
+ self.resblocks.append(resblock(ch, k, d))
318
+
319
+ self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
320
+ self.ups.apply(init_weights)
321
+
322
+ if gin_channels != 0:
323
+ self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
324
+
325
+ def forward(self, x, g=None):
326
+ x = self.conv_pre(x)
327
+ if g is not None:
328
+ x = x + self.cond(g)
329
+
330
+ for i in range(self.num_upsamples):
331
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
332
+ x = self.ups[i](x)
333
+ xs = None
334
+ for j in range(self.num_kernels):
335
+ if xs is None:
336
+ xs = self.resblocks[i * self.num_kernels + j](x)
337
+ else:
338
+ xs += self.resblocks[i * self.num_kernels + j](x)
339
+ x = xs / self.num_kernels
340
+ x = F.leaky_relu(x)
341
+ x = self.conv_post(x)
342
+ x = torch.tanh(x)
343
+
344
+ return x
345
+
346
+ def remove_weight_norm(self):
347
+ print('Removing weight norm...')
348
+ for l in self.ups:
349
+ remove_weight_norm(l)
350
+ for l in self.resblocks:
351
+ l.remove_weight_norm()
352
+
353
+
354
+ class DiscriminatorP(torch.nn.Module):
355
+ def __init__(self,
356
+ period,
357
+ kernel_size=5,
358
+ stride=3,
359
+ use_spectral_norm=False):
360
+ super(DiscriminatorP, self).__init__()
361
+ self.period = period
362
+ self.use_spectral_norm = use_spectral_norm
363
+ norm_f = weight_norm if use_spectral_norm is False else spectral_norm
364
+ self.convs = nn.ModuleList([
365
+ norm_f(
366
+ Conv2d(1,
367
+ 32, (kernel_size, 1), (stride, 1),
368
+ padding=(get_padding(kernel_size, 1), 0))),
369
+ norm_f(
370
+ Conv2d(32,
371
+ 128, (kernel_size, 1), (stride, 1),
372
+ padding=(get_padding(kernel_size, 1), 0))),
373
+ norm_f(
374
+ Conv2d(128,
375
+ 512, (kernel_size, 1), (stride, 1),
376
+ padding=(get_padding(kernel_size, 1), 0))),
377
+ norm_f(
378
+ Conv2d(512,
379
+ 1024, (kernel_size, 1), (stride, 1),
380
+ padding=(get_padding(kernel_size, 1), 0))),
381
+ norm_f(
382
+ Conv2d(1024,
383
+ 1024, (kernel_size, 1),
384
+ 1,
385
+ padding=(get_padding(kernel_size, 1), 0))),
386
+ ])
387
+ self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
388
+
389
+ def forward(self, x):
390
+ fmap = []
391
+
392
+ # 1d to 2d
393
+ b, c, t = x.shape
394
+ if t % self.period != 0: # pad first
395
+ n_pad = self.period - (t % self.period)
396
+ x = F.pad(x, (0, n_pad), "reflect")
397
+ t = t + n_pad
398
+ x = x.view(b, c, t // self.period, self.period)
399
+
400
+ for l in self.convs:
401
+ x = l(x)
402
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
403
+ fmap.append(x)
404
+ x = self.conv_post(x)
405
+ fmap.append(x)
406
+ x = torch.flatten(x, 1, -1)
407
+
408
+ return x, fmap
409
+
410
+
411
+ class DiscriminatorS(torch.nn.Module):
412
+ def __init__(self, use_spectral_norm=False):
413
+ super(DiscriminatorS, self).__init__()
414
+ norm_f = weight_norm if use_spectral_norm is False else spectral_norm
415
+ self.convs = nn.ModuleList([
416
+ norm_f(Conv1d(1, 16, 15, 1, padding=7)),
417
+ norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
418
+ norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
419
+ norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
420
+ norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
421
+ norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
422
+ ])
423
+ self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
424
+
425
+ def forward(self, x):
426
+ fmap = []
427
+
428
+ for l in self.convs:
429
+ x = l(x)
430
+ x = F.leaky_relu(x, modules.LRELU_SLOPE)
431
+ fmap.append(x)
432
+ x = self.conv_post(x)
433
+ fmap.append(x)
434
+ x = torch.flatten(x, 1, -1)
435
+
436
+ return x, fmap
437
+
438
+
439
+ class MultiPeriodDiscriminator(torch.nn.Module):
440
+ def __init__(self, use_spectral_norm=False):
441
+ super(MultiPeriodDiscriminator, self).__init__()
442
+ periods = [2, 3, 5, 7, 11]
443
+
444
+ discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
445
+ discs = discs + [
446
+ DiscriminatorP(i, use_spectral_norm=use_spectral_norm)
447
+ for i in periods
448
+ ]
449
+ self.discriminators = nn.ModuleList(discs)
450
+
451
+ def forward(self, y, y_hat):
452
+ y_d_rs = []
453
+ y_d_gs = []
454
+ fmap_rs = []
455
+ fmap_gs = []
456
+ for i, d in enumerate(self.discriminators):
457
+ y_d_r, fmap_r = d(y)
458
+ y_d_g, fmap_g = d(y_hat)
459
+ y_d_rs.append(y_d_r)
460
+ y_d_gs.append(y_d_g)
461
+ fmap_rs.append(fmap_r)
462
+ fmap_gs.append(fmap_g)
463
+
464
+ return y_d_rs, y_d_gs, fmap_rs, fmap_gs
465
+
466
+
467
+ class SynthesizerTrn(nn.Module):
468
+ """
469
+ Synthesizer for Training
470
+ """
471
+ def __init__(self,
472
+ n_vocab,
473
+ spec_channels,
474
+ segment_size,
475
+ inter_channels,
476
+ hidden_channels,
477
+ filter_channels,
478
+ n_heads,
479
+ n_layers,
480
+ kernel_size,
481
+ p_dropout,
482
+ resblock,
483
+ resblock_kernel_sizes,
484
+ resblock_dilation_sizes,
485
+ upsample_rates,
486
+ upsample_initial_channel,
487
+ upsample_kernel_sizes,
488
+ n_speakers=0,
489
+ gin_channels=0,
490
+ use_sdp=True,
491
+ **kwargs):
492
+
493
+ super().__init__()
494
+ self.n_vocab = n_vocab
495
+ self.spec_channels = spec_channels
496
+ self.inter_channels = inter_channels
497
+ self.hidden_channels = hidden_channels
498
+ self.filter_channels = filter_channels
499
+ self.n_heads = n_heads
500
+ self.n_layers = n_layers
501
+ self.kernel_size = kernel_size
502
+ self.p_dropout = p_dropout
503
+ self.resblock = resblock
504
+ self.resblock_kernel_sizes = resblock_kernel_sizes
505
+ self.resblock_dilation_sizes = resblock_dilation_sizes
506
+ self.upsample_rates = upsample_rates
507
+ self.upsample_initial_channel = upsample_initial_channel
508
+ self.upsample_kernel_sizes = upsample_kernel_sizes
509
+ self.segment_size = segment_size
510
+ self.n_speakers = n_speakers
511
+ self.gin_channels = gin_channels
512
+ if self.n_speakers != 0:
513
+ message = "gin_channels must be none zero for multiple speakers"
514
+ assert gin_channels != 0, message
515
+
516
+ self.use_sdp = use_sdp
517
+
518
+ self.enc_p = TextEncoder(n_vocab, inter_channels, hidden_channels,
519
+ filter_channels, n_heads, n_layers,
520
+ kernel_size, p_dropout)
521
+ self.dec = Generator(inter_channels,
522
+ resblock,
523
+ resblock_kernel_sizes,
524
+ resblock_dilation_sizes,
525
+ upsample_rates,
526
+ upsample_initial_channel,
527
+ upsample_kernel_sizes,
528
+ gin_channels=gin_channels)
529
+ self.enc_q = PosteriorEncoder(spec_channels,
530
+ inter_channels,
531
+ hidden_channels,
532
+ 5,
533
+ 1,
534
+ 16,
535
+ gin_channels=gin_channels)
536
+ self.flow = ResidualCouplingBlock(inter_channels,
537
+ hidden_channels,
538
+ 5,
539
+ 1,
540
+ 4,
541
+ gin_channels=gin_channels)
542
+
543
+ if use_sdp:
544
+ self.dp = StochasticDurationPredictor(hidden_channels,
545
+ 192,
546
+ 3,
547
+ 0.5,
548
+ 4,
549
+ gin_channels=gin_channels)
550
+ else:
551
+ self.dp = DurationPredictor(hidden_channels,
552
+ 256,
553
+ 3,
554
+ 0.5,
555
+ gin_channels=gin_channels)
556
+
557
+ if n_speakers > 1:
558
+ self.emb_g = nn.Embedding(n_speakers, gin_channels)
559
+
560
+ def forward(self, x, x_lengths, y, y_lengths, sid=None):
561
+
562
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
563
+ if self.n_speakers > 0:
564
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
565
+ else:
566
+ g = None
567
+
568
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
569
+ z_p = self.flow(z, y_mask, g=g)
570
+
571
+ with torch.no_grad():
572
+ # negative cross-entropy
573
+ s_p_sq_r = torch.exp(-2 * logs_p) # [b, d, t]
574
+ neg_cent1 = torch.sum(-0.5 * math.log(2 * math.pi) - logs_p, [1],
575
+ keepdim=True) # [b, 1, t_s]
576
+ neg_cent2 = torch.matmul(
577
+ -0.5 * (z_p**2).transpose(1, 2),
578
+ s_p_sq_r) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
579
+ neg_cent3 = torch.matmul(
580
+ z_p.transpose(1, 2),
581
+ (m_p * s_p_sq_r)) # [b, t_t, d] x [b, d, t_s] = [b, t_t, t_s]
582
+ neg_cent4 = torch.sum(-0.5 * (m_p**2) * s_p_sq_r, [1],
583
+ keepdim=True) # [b, 1, t_s]
584
+ neg_cent = neg_cent1 + neg_cent2 + neg_cent3 + neg_cent4
585
+
586
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(
587
+ y_mask, -1)
588
+ attn = monotonic_align.maximum_path(
589
+ neg_cent, attn_mask.squeeze(1)).unsqueeze(1).detach()
590
+
591
+ w = attn.sum(2)
592
+ if self.use_sdp:
593
+ l_length = self.dp(x, x_mask, w, g=g)
594
+ l_length = l_length / torch.sum(x_mask)
595
+ else:
596
+ logw_ = torch.log(w + 1e-6) * x_mask
597
+ logw = self.dp(x, x_mask, g=g)
598
+ l_length = torch.sum(
599
+ (logw - logw_)**2, [1, 2]) / torch.sum(x_mask) # for averaging
600
+
601
+ # expand prior
602
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1,
603
+ 2)).transpose(1, 2)
604
+ logs_p = torch.matmul(attn.squeeze(1),
605
+ logs_p.transpose(1, 2)).transpose(1, 2)
606
+
607
+ z_slice, ids_slice = commons.rand_slice_segments(
608
+ z, y_lengths, self.segment_size)
609
+ o = self.dec(z_slice, g=g)
610
+ return o, l_length, attn, ids_slice, x_mask, y_mask, (z, z_p, m_p,
611
+ logs_p, m_q,
612
+ logs_q)
613
+
614
+ def infer(self,
615
+ x,
616
+ x_lengths,
617
+ sid=None,
618
+ noise_scale=1,
619
+ length_scale=1,
620
+ noise_scale_w=1.,
621
+ max_len=None):
622
+ x, m_p, logs_p, x_mask = self.enc_p(x, x_lengths)
623
+ if self.n_speakers > 0:
624
+ g = self.emb_g(sid).unsqueeze(-1) # [b, h, 1]
625
+ else:
626
+ g = None
627
+
628
+ if self.use_sdp:
629
+ logw = self.dp(x,
630
+ x_mask,
631
+ g=g,
632
+ reverse=True,
633
+ noise_scale=noise_scale_w)
634
+ else:
635
+ logw = self.dp(x, x_mask, g=g)
636
+ w = torch.exp(logw) * x_mask * length_scale
637
+ w_ceil = torch.ceil(w)
638
+ y_lengths = torch.clamp_min(torch.sum(w_ceil, [1, 2]), 1).long()
639
+ y_mask = torch.unsqueeze(commons.sequence_mask(y_lengths, None),
640
+ 1).to(x_mask.dtype)
641
+ attn_mask = torch.unsqueeze(x_mask, 2) * torch.unsqueeze(y_mask, -1)
642
+ attn = commons.generate_path(w_ceil, attn_mask)
643
+
644
+ m_p = torch.matmul(attn.squeeze(1), m_p.transpose(1, 2)).transpose(
645
+ 1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
646
+ logs_p = torch.matmul(attn.squeeze(1), logs_p.transpose(
647
+ 1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
648
+
649
+ z_p = m_p + torch.randn_like(m_p) * torch.exp(logs_p) * noise_scale
650
+ z = self.flow(z_p, y_mask, g=g, reverse=True)
651
+ o = self.dec((z * y_mask)[:, :, :max_len], g=g)
652
+ return o, attn, y_mask, (z, z_p, m_p, logs_p)
653
+
654
+ def export_forward(self, x, x_lengths, scales, sid):
655
+ # shape of scales: Bx3, make triton happy
656
+ audio, *_ = self.infer(x,
657
+ x_lengths,
658
+ sid,
659
+ noise_scale=scales[0][0],
660
+ length_scale=scales[0][1],
661
+ noise_scale_w=scales[0][2])
662
+ return audio
663
+
664
+ def voice_conversion(self, y, y_lengths, sid_src, sid_tgt):
665
+ assert self.n_speakers > 0, "n_speakers have to be larger than 0."
666
+ g_src = self.emb_g(sid_src).unsqueeze(-1)
667
+ g_tgt = self.emb_g(sid_tgt).unsqueeze(-1)
668
+ z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g_src)
669
+ z_p = self.flow(z, y_mask, g=g_src)
670
+ z_hat = self.flow(z_p, y_mask, g=g_tgt, reverse=True)
671
+ o_hat = self.dec(z_hat * y_mask, g=g_tgt)
672
+ return o_hat, y_mask, (z, z_p, z_hat)
modules.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn import functional as F
6
+ from torch.nn import Conv1d
7
+ from torch.nn.utils import weight_norm, remove_weight_norm
8
+
9
+ import commons
10
+ from commons import init_weights, get_padding
11
+ from transforms import piecewise_rational_quadratic_transform
12
+
13
+ LRELU_SLOPE = 0.1
14
+
15
+
16
+ class LayerNorm(nn.Module):
17
+ def __init__(self, channels, eps=1e-5):
18
+ super().__init__()
19
+ self.channels = channels
20
+ self.eps = eps
21
+
22
+ self.gamma = nn.Parameter(torch.ones(channels))
23
+ self.beta = nn.Parameter(torch.zeros(channels))
24
+
25
+ def forward(self, x):
26
+ x = x.transpose(1, -1)
27
+ x = F.layer_norm(x, (self.channels, ), self.gamma, self.beta, self.eps)
28
+ return x.transpose(1, -1)
29
+
30
+
31
+ class ConvReluNorm(nn.Module):
32
+ def __init__(self, in_channels, hidden_channels, out_channels, kernel_size,
33
+ n_layers, p_dropout):
34
+ super().__init__()
35
+ self.in_channels = in_channels
36
+ self.hidden_channels = hidden_channels
37
+ self.out_channels = out_channels
38
+ self.kernel_size = kernel_size
39
+ self.n_layers = n_layers
40
+ self.p_dropout = p_dropout
41
+ assert n_layers > 1, "Number of layers should be larger than 0."
42
+
43
+ self.conv_layers = nn.ModuleList()
44
+ self.norm_layers = nn.ModuleList()
45
+ self.conv_layers.append(
46
+ nn.Conv1d(in_channels,
47
+ hidden_channels,
48
+ kernel_size,
49
+ padding=kernel_size // 2))
50
+ self.norm_layers.append(LayerNorm(hidden_channels))
51
+ self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
52
+ for _ in range(n_layers - 1):
53
+ self.conv_layers.append(
54
+ nn.Conv1d(hidden_channels,
55
+ hidden_channels,
56
+ kernel_size,
57
+ padding=kernel_size // 2))
58
+ self.norm_layers.append(LayerNorm(hidden_channels))
59
+ self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
60
+ self.proj.weight.data.zero_()
61
+ self.proj.bias.data.zero_()
62
+
63
+ def forward(self, x, x_mask):
64
+ x_org = x
65
+ for i in range(self.n_layers):
66
+ x = self.conv_layers[i](x * x_mask)
67
+ x = self.norm_layers[i](x)
68
+ x = self.relu_drop(x)
69
+ x = x_org + self.proj(x)
70
+ return x * x_mask
71
+
72
+
73
+ class DDSConv(nn.Module):
74
+ """
75
+ Dialted and Depth-Separable Convolution
76
+ """
77
+ def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
78
+ super().__init__()
79
+ self.channels = channels
80
+ self.kernel_size = kernel_size
81
+ self.n_layers = n_layers
82
+ self.p_dropout = p_dropout
83
+
84
+ self.drop = nn.Dropout(p_dropout)
85
+ self.convs_sep = nn.ModuleList()
86
+ self.convs_1x1 = nn.ModuleList()
87
+ self.norms_1 = nn.ModuleList()
88
+ self.norms_2 = nn.ModuleList()
89
+ for i in range(n_layers):
90
+ dilation = kernel_size**i
91
+ padding = (kernel_size * dilation - dilation) // 2
92
+ self.convs_sep.append(
93
+ nn.Conv1d(channels,
94
+ channels,
95
+ kernel_size,
96
+ groups=channels,
97
+ dilation=dilation,
98
+ padding=padding))
99
+ self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
100
+ self.norms_1.append(LayerNorm(channels))
101
+ self.norms_2.append(LayerNorm(channels))
102
+
103
+ def forward(self, x, x_mask, g=None):
104
+ if g is not None:
105
+ x = x + g
106
+ for i in range(self.n_layers):
107
+ y = self.convs_sep[i](x * x_mask)
108
+ y = self.norms_1[i](y)
109
+ y = F.gelu(y)
110
+ y = self.convs_1x1[i](y)
111
+ y = self.norms_2[i](y)
112
+ y = F.gelu(y)
113
+ y = self.drop(y)
114
+ x = x + y
115
+ return x * x_mask
116
+
117
+
118
+ class WN(torch.nn.Module):
119
+ def __init__(self,
120
+ hidden_channels,
121
+ kernel_size,
122
+ dilation_rate,
123
+ n_layers,
124
+ gin_channels=0,
125
+ p_dropout=0):
126
+ super(WN, self).__init__()
127
+ assert (kernel_size % 2 == 1)
128
+ self.hidden_channels = hidden_channels
129
+ self.kernel_size = kernel_size,
130
+ self.dilation_rate = dilation_rate
131
+ self.n_layers = n_layers
132
+ self.gin_channels = gin_channels
133
+ self.p_dropout = p_dropout
134
+
135
+ self.in_layers = torch.nn.ModuleList()
136
+ self.res_skip_layers = torch.nn.ModuleList()
137
+ self.drop = nn.Dropout(p_dropout)
138
+
139
+ if gin_channels != 0:
140
+ cond_layer = torch.nn.Conv1d(gin_channels,
141
+ 2 * hidden_channels * n_layers, 1)
142
+ self.cond_layer = torch.nn.utils.weight_norm(cond_layer,
143
+ name='weight')
144
+
145
+ for i in range(n_layers):
146
+ dilation = dilation_rate**i
147
+ padding = int((kernel_size * dilation - dilation) / 2)
148
+ in_layer = torch.nn.Conv1d(hidden_channels,
149
+ 2 * hidden_channels,
150
+ kernel_size,
151
+ dilation=dilation,
152
+ padding=padding)
153
+ in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
154
+ self.in_layers.append(in_layer)
155
+
156
+ # last one is not necessary
157
+ if i < n_layers - 1:
158
+ res_skip_channels = 2 * hidden_channels
159
+ else:
160
+ res_skip_channels = hidden_channels
161
+
162
+ res_skip_layer = torch.nn.Conv1d(hidden_channels,
163
+ res_skip_channels, 1)
164
+ res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer,
165
+ name='weight')
166
+ self.res_skip_layers.append(res_skip_layer)
167
+
168
+ def forward(self, x, x_mask, g=None, **kwargs):
169
+ output = torch.zeros_like(x)
170
+ n_channels_tensor = torch.IntTensor([self.hidden_channels])
171
+
172
+ if g is not None:
173
+ g = self.cond_layer(g)
174
+
175
+ for i in range(self.n_layers):
176
+ x_in = self.in_layers[i](x)
177
+ if g is not None:
178
+ cond_offset = i * 2 * self.hidden_channels
179
+ g_l = g[:,
180
+ cond_offset:cond_offset + 2 * self.hidden_channels, :]
181
+ else:
182
+ g_l = torch.zeros_like(x_in)
183
+
184
+ acts = commons.fused_add_tanh_sigmoid_multiply(
185
+ x_in, g_l, n_channels_tensor)
186
+ acts = self.drop(acts)
187
+
188
+ res_skip_acts = self.res_skip_layers[i](acts)
189
+ if i < self.n_layers - 1:
190
+ res_acts = res_skip_acts[:, :self.hidden_channels, :]
191
+ x = (x + res_acts) * x_mask
192
+ output = output + res_skip_acts[:, self.hidden_channels:, :]
193
+ else:
194
+ output = output + res_skip_acts
195
+ return output * x_mask
196
+
197
+ def remove_weight_norm(self):
198
+ if self.gin_channels != 0:
199
+ torch.nn.utils.remove_weight_norm(self.cond_layer)
200
+ for l in self.in_layers:
201
+ torch.nn.utils.remove_weight_norm(l)
202
+ for l in self.res_skip_layers:
203
+ torch.nn.utils.remove_weight_norm(l)
204
+
205
+
206
+ class ResBlock1(torch.nn.Module):
207
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
208
+ super(ResBlock1, self).__init__()
209
+ self.convs1 = nn.ModuleList([
210
+ weight_norm(
211
+ Conv1d(channels,
212
+ channels,
213
+ kernel_size,
214
+ 1,
215
+ dilation=dilation[0],
216
+ padding=get_padding(kernel_size, dilation[0]))),
217
+ weight_norm(
218
+ Conv1d(channels,
219
+ channels,
220
+ kernel_size,
221
+ 1,
222
+ dilation=dilation[1],
223
+ padding=get_padding(kernel_size, dilation[1]))),
224
+ weight_norm(
225
+ Conv1d(channels,
226
+ channels,
227
+ kernel_size,
228
+ 1,
229
+ dilation=dilation[2],
230
+ padding=get_padding(kernel_size, dilation[2])))
231
+ ])
232
+ self.convs1.apply(init_weights)
233
+
234
+ self.convs2 = nn.ModuleList([
235
+ weight_norm(
236
+ Conv1d(channels,
237
+ channels,
238
+ kernel_size,
239
+ 1,
240
+ dilation=1,
241
+ padding=get_padding(kernel_size, 1))),
242
+ weight_norm(
243
+ Conv1d(channels,
244
+ channels,
245
+ kernel_size,
246
+ 1,
247
+ dilation=1,
248
+ padding=get_padding(kernel_size, 1))),
249
+ weight_norm(
250
+ Conv1d(channels,
251
+ channels,
252
+ kernel_size,
253
+ 1,
254
+ dilation=1,
255
+ padding=get_padding(kernel_size, 1)))
256
+ ])
257
+ self.convs2.apply(init_weights)
258
+
259
+ def forward(self, x, x_mask=None):
260
+ for c1, c2 in zip(self.convs1, self.convs2):
261
+ xt = F.leaky_relu(x, LRELU_SLOPE)
262
+ if x_mask is not None:
263
+ xt = xt * x_mask
264
+ xt = c1(xt)
265
+ xt = F.leaky_relu(xt, LRELU_SLOPE)
266
+ if x_mask is not None:
267
+ xt = xt * x_mask
268
+ xt = c2(xt)
269
+ x = xt + x
270
+ if x_mask is not None:
271
+ x = x * x_mask
272
+ return x
273
+
274
+ def remove_weight_norm(self):
275
+ for l in self.convs1:
276
+ remove_weight_norm(l)
277
+ for l in self.convs2:
278
+ remove_weight_norm(l)
279
+
280
+
281
+ class ResBlock2(torch.nn.Module):
282
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
283
+ super(ResBlock2, self).__init__()
284
+ self.convs = nn.ModuleList([
285
+ weight_norm(
286
+ Conv1d(channels,
287
+ channels,
288
+ kernel_size,
289
+ 1,
290
+ dilation=dilation[0],
291
+ padding=get_padding(kernel_size, dilation[0]))),
292
+ weight_norm(
293
+ Conv1d(channels,
294
+ channels,
295
+ kernel_size,
296
+ 1,
297
+ dilation=dilation[1],
298
+ padding=get_padding(kernel_size, dilation[1])))
299
+ ])
300
+ self.convs.apply(init_weights)
301
+
302
+ def forward(self, x, x_mask=None):
303
+ for c in self.convs:
304
+ xt = F.leaky_relu(x, LRELU_SLOPE)
305
+ if x_mask is not None:
306
+ xt = xt * x_mask
307
+ xt = c(xt)
308
+ x = xt + x
309
+ if x_mask is not None:
310
+ x = x * x_mask
311
+ return x
312
+
313
+ def remove_weight_norm(self):
314
+ for l in self.convs:
315
+ remove_weight_norm(l)
316
+
317
+
318
+ class Log(nn.Module):
319
+ def forward(self, x, x_mask, reverse=False, **kwargs):
320
+ if not reverse:
321
+ y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
322
+ logdet = torch.sum(-y, [1, 2])
323
+ return y, logdet
324
+ else:
325
+ x = torch.exp(x) * x_mask
326
+ return x
327
+
328
+
329
+ class Flip(nn.Module):
330
+ def forward(self, x, *args, reverse=False, **kwargs):
331
+ x = torch.flip(x, [1])
332
+ if not reverse:
333
+ logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
334
+ return x, logdet
335
+ else:
336
+ return x
337
+
338
+
339
+ class ElementwiseAffine(nn.Module):
340
+ def __init__(self, channels):
341
+ super().__init__()
342
+ self.channels = channels
343
+ self.m = nn.Parameter(torch.zeros(channels, 1))
344
+ self.logs = nn.Parameter(torch.zeros(channels, 1))
345
+
346
+ def forward(self, x, x_mask, reverse=False, **kwargs):
347
+ if not reverse:
348
+ y = self.m + torch.exp(self.logs) * x
349
+ y = y * x_mask
350
+ logdet = torch.sum(self.logs * x_mask, [1, 2])
351
+ return y, logdet
352
+ else:
353
+ x = (x - self.m) * torch.exp(-self.logs) * x_mask
354
+ return x
355
+
356
+
357
+ class ResidualCouplingLayer(nn.Module):
358
+ def __init__(self,
359
+ channels,
360
+ hidden_channels,
361
+ kernel_size,
362
+ dilation_rate,
363
+ n_layers,
364
+ p_dropout=0,
365
+ gin_channels=0,
366
+ mean_only=False):
367
+ assert channels % 2 == 0, "channels should be divisible by 2"
368
+ super().__init__()
369
+ self.channels = channels
370
+ self.hidden_channels = hidden_channels
371
+ self.kernel_size = kernel_size
372
+ self.dilation_rate = dilation_rate
373
+ self.n_layers = n_layers
374
+ self.half_channels = channels // 2
375
+ self.mean_only = mean_only
376
+
377
+ self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
378
+ self.enc = WN(hidden_channels,
379
+ kernel_size,
380
+ dilation_rate,
381
+ n_layers,
382
+ p_dropout=p_dropout,
383
+ gin_channels=gin_channels)
384
+ self.post = nn.Conv1d(hidden_channels,
385
+ self.half_channels * (2 - mean_only), 1)
386
+ self.post.weight.data.zero_()
387
+ self.post.bias.data.zero_()
388
+
389
+ def forward(self, x, x_mask, g=None, reverse=False):
390
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
391
+ h = self.pre(x0) * x_mask
392
+ h = self.enc(h, x_mask, g=g)
393
+ stats = self.post(h) * x_mask
394
+ if not self.mean_only:
395
+ m, logs = torch.split(stats, [self.half_channels] * 2, 1)
396
+ else:
397
+ m = stats
398
+ logs = torch.zeros_like(m)
399
+
400
+ if not reverse:
401
+ x1 = m + x1 * torch.exp(logs) * x_mask
402
+ x = torch.cat([x0, x1], 1)
403
+ logdet = torch.sum(logs, [1, 2])
404
+ return x, logdet
405
+ else:
406
+ x1 = (x1 - m) * torch.exp(-logs) * x_mask
407
+ x = torch.cat([x0, x1], 1)
408
+ return x
409
+
410
+
411
+ class ConvFlow(nn.Module):
412
+ def __init__(self,
413
+ in_channels,
414
+ filter_channels,
415
+ kernel_size,
416
+ n_layers,
417
+ num_bins=10,
418
+ tail_bound=5.0):
419
+ super().__init__()
420
+ self.in_channels = in_channels
421
+ self.filter_channels = filter_channels
422
+ self.kernel_size = kernel_size
423
+ self.n_layers = n_layers
424
+ self.num_bins = num_bins
425
+ self.tail_bound = tail_bound
426
+ self.half_channels = in_channels // 2
427
+
428
+ self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
429
+ self.convs = DDSConv(filter_channels,
430
+ kernel_size,
431
+ n_layers,
432
+ p_dropout=0.)
433
+ self.proj = nn.Conv1d(filter_channels,
434
+ self.half_channels * (num_bins * 3 - 1), 1)
435
+ self.proj.weight.data.zero_()
436
+ self.proj.bias.data.zero_()
437
+
438
+ def forward(self, x, x_mask, g=None, reverse=False):
439
+ x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
440
+ h = self.pre(x0)
441
+ h = self.convs(h, x_mask, g=g)
442
+ h = self.proj(h) * x_mask
443
+
444
+ b, c, t = x0.shape
445
+ h = h.reshape(b, c, -1, t).permute(0, 1, 3,
446
+ 2) # [b, cx?, t] -> [b, c, t, ?]
447
+
448
+ unnormalized_widths = h[..., :self.num_bins] / math.sqrt(
449
+ self.filter_channels)
450
+ unnormalized_heights = h[...,
451
+ self.num_bins:2 * self.num_bins] / math.sqrt(
452
+ self.filter_channels)
453
+ unnormalized_derivatives = h[..., 2 * self.num_bins:]
454
+
455
+ x1, logabsdet = piecewise_rational_quadratic_transform(
456
+ x1,
457
+ unnormalized_widths,
458
+ unnormalized_heights,
459
+ unnormalized_derivatives,
460
+ inverse=reverse,
461
+ tails='linear',
462
+ tail_bound=self.tail_bound)
463
+
464
+ x = torch.cat([x0, x1], 1) * x_mask
465
+ logdet = torch.sum(logabsdet * x_mask, [1, 2])
466
+ if not reverse:
467
+ return x, logdet
468
+ else:
469
+ return x
moe/config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "THUDM/chatglm-6b",
3
+ "architectures": [
4
+ "ChatGLMModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_chatglm.ChatGLMConfig",
8
+ "AutoModel": "modeling_chatglm.ChatGLMForConditionalGeneration",
9
+ "AutoModelForSeq2SeqLM": "modeling_chatglm.ChatGLMForConditionalGeneration"
10
+ },
11
+ "bos_token_id": 150004,
12
+ "eos_token_id": 150005,
13
+ "hidden_size": 4096,
14
+ "inner_hidden_size": 16384,
15
+ "layernorm_epsilon": 1e-05,
16
+ "max_sequence_length": 2048,
17
+ "model_type": "chatglm",
18
+ "num_attention_heads": 32,
19
+ "num_layers": 28,
20
+ "position_encoding_2d": true,
21
+ "torch_dtype": "float16",
22
+ "transformers_version": "4.23.1",
23
+ "use_cache": true,
24
+ "vocab_size": 150528
25
+ }
moe/configuration_chatglm.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ ChatGLM model configuration """
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+
9
+ class ChatGLMConfig(PretrainedConfig):
10
+ r"""
11
+ This is the configuration class to store the configuration of a [`~ChatGLMModel`].
12
+ It is used to instantiate an ChatGLM model according to the specified arguments, defining the model
13
+ architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
14
+ the ChatGLM-6B [THUDM/ChatGLM-6B](https://huggingface.co/THUDM/chatglm-6b) architecture.
15
+
16
+ Configuration objects inherit from [`PretrainedConfig`] and can be used
17
+ to control the model outputs. Read the documentation from [`PretrainedConfig`]
18
+ for more information.
19
+
20
+
21
+ Args:
22
+ vocab_size (`int`, *optional*, defaults to 150528):
23
+ Vocabulary size of the ChatGLM-6B model. Defines the number of different tokens that can be represented by the
24
+ `inputs_ids` passed when calling [`~ChatGLMModel`] or
25
+ [`~TFChatGLMModel`].
26
+ hidden_size (`int`, *optional*, defaults to 4096):
27
+ Dimension of the encoder layers and the pooler layer.
28
+ num_hidden_layers (`int`, *optional*, defaults to 28):
29
+ Number of hidden layers in the Transformer encoder.
30
+ num_attention_heads (`int`, *optional*, defaults to 32):
31
+ Number of attention heads for each attention layer in the Transformer encoder.
32
+ inner_hidden_size (`int`, *optional*, defaults to 16384):
33
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
34
+ max_sequence_length (`int`, *optional*, defaults to 512):
35
+ The maximum sequence length that this model might ever be used with.
36
+ Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
37
+ layernorm_epsilon (`float`, *optional*, defaults to 1e-5):
38
+ The epsilon used by the layer normalization layers.
39
+ use_cache (`bool`, *optional*, defaults to `True`):
40
+ Whether the model should return the last key/values attentions (not used by all models).
41
+ Example:
42
+
43
+ ```python
44
+ >>> from configuration_chatglm import ChatGLMConfig
45
+ >>> from modeling_chatglm import ChatGLMModel
46
+
47
+ >>> # Initializing a ChatGLM-6B THUDM/ChatGLM-6B style configuration
48
+ >>> configuration = ChatGLMConfig()
49
+
50
+ >>> # Initializing a model from the THUDM/ChatGLM-6B style configuration
51
+ >>> model = ChatGLMModel(configuration)
52
+
53
+ >>> # Accessing the model configuration
54
+ >>> configuration = model.config
55
+ ```
56
+ """
57
+ model_type = "chatglm"
58
+
59
+ def __init__(
60
+ self,
61
+ vocab_size=150528,
62
+ hidden_size=4096,
63
+ num_layers=28,
64
+ num_attention_heads=32,
65
+ layernorm_epsilon=1e-5,
66
+ use_cache=False,
67
+ bos_token_id=150004,
68
+ eos_token_id=150005,
69
+ pad_token_id=0,
70
+ max_sequence_length=2048,
71
+ inner_hidden_size=16384,
72
+ position_encoding_2d=True,
73
+ **kwargs
74
+ ):
75
+ self.num_layers = num_layers
76
+ self.vocab_size = vocab_size
77
+ self.hidden_size = hidden_size
78
+ self.num_attention_heads = num_attention_heads
79
+ self.max_sequence_length = max_sequence_length
80
+ self.layernorm_epsilon = layernorm_epsilon
81
+ self.inner_hidden_size = inner_hidden_size
82
+ self.use_cache = use_cache
83
+ self.bos_token_id = bos_token_id
84
+ self.eos_token_id = eos_token_id
85
+ self.pad_token_id = pad_token_id
86
+ self.position_encoding_2d = position_encoding_2d
87
+ super().__init__(
88
+ pad_token_id=pad_token_id,
89
+ bos_token_id=bos_token_id,
90
+ eos_token_id=eos_token_id,
91
+ **kwargs
92
+ )
moe/modeling_chatglm.py ADDED
@@ -0,0 +1,1157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch ChatGLM model. """
2
+
3
+ import math
4
+ import copy
5
+ import os
6
+
7
+ import torch
8
+ import torch.utils.checkpoint
9
+ import torch.nn.functional as F
10
+ from torch import nn
11
+ from torch.nn import CrossEntropyLoss, LayerNorm
12
+ from torch.nn.utils import skip_init
13
+ from typing import Optional, Tuple, Union, List
14
+
15
+ from transformers.utils import (
16
+ add_code_sample_docstrings,
17
+ add_start_docstrings,
18
+ add_start_docstrings_to_model_forward,
19
+ )
20
+ from transformers.modeling_outputs import (
21
+ BaseModelOutputWithPast,
22
+ CausalLMOutputWithPast,
23
+ BaseModelOutputWithPastAndCrossAttentions,
24
+ )
25
+ from transformers.modeling_utils import PreTrainedModel
26
+
27
+ from transformers.utils import logging
28
+ from .configuration_chatglm import ChatGLMConfig
29
+
30
+ # flags required to enable jit fusion kernels
31
+ torch._C._jit_set_profiling_mode(False)
32
+ torch._C._jit_set_profiling_executor(False)
33
+ torch._C._jit_override_can_fuse_on_cpu(True)
34
+ torch._C._jit_override_can_fuse_on_gpu(True)
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ _CHECKPOINT_FOR_DOC = "THUDM/ChatGLM-6B"
39
+ _CONFIG_FOR_DOC = "ChatGLM6BConfig"
40
+
41
+ CHATGLM_6B_PRETRAINED_MODEL_ARCHIVE_LIST = [
42
+ "THUDM/chatglm-6b",
43
+ # See all ChatGLM-6B models at https://huggingface.co/models?filter=chatglm
44
+ ]
45
+
46
+
47
+ def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path):
48
+ """Load tf checkpoints in a pytorch model."""
49
+ try:
50
+ import re
51
+
52
+ import numpy as np
53
+ import tensorflow as tf
54
+ except ImportError:
55
+ logger.error(
56
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
57
+ "https://www.tensorflow.org/install/ for installation instructions."
58
+ )
59
+ raise
60
+ tf_path = os.path.abspath(tf_checkpoint_path)
61
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
62
+ # Load weights from TF model
63
+ init_vars = tf.train.list_variables(tf_path)
64
+ names = []
65
+ arrays = []
66
+ for name, shape in init_vars:
67
+ logger.info(f"Loading TF weight {name} with shape {shape}")
68
+ array = tf.train.load_variable(tf_path, name)
69
+ names.append(name)
70
+ arrays.append(array)
71
+
72
+ for name, array in zip(names, arrays):
73
+ name = name.split("/")
74
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
75
+ # which are not required for using pretrained model
76
+ if any(
77
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
78
+ for n in name
79
+ ):
80
+ logger.info(f"Skipping {'/'.join(name)}")
81
+ continue
82
+ pointer = model
83
+ for m_name in name:
84
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
85
+ scope_names = re.split(r"_(\d+)", m_name)
86
+ else:
87
+ scope_names = [m_name]
88
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
89
+ pointer = getattr(pointer, "weight")
90
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
91
+ pointer = getattr(pointer, "bias")
92
+ elif scope_names[0] == "output_weights":
93
+ pointer = getattr(pointer, "weight")
94
+ elif scope_names[0] == "squad":
95
+ pointer = getattr(pointer, "classifier")
96
+ else:
97
+ try:
98
+ pointer = getattr(pointer, scope_names[0])
99
+ except AttributeError:
100
+ logger.info(f"Skipping {'/'.join(name)}")
101
+ continue
102
+ if len(scope_names) >= 2:
103
+ num = int(scope_names[1])
104
+ pointer = pointer[num]
105
+ if m_name[-11:] == "_embeddings":
106
+ pointer = getattr(pointer, "weight")
107
+ elif m_name == "kernel":
108
+ array = np.transpose(array)
109
+ try:
110
+ assert (
111
+ pointer.shape == array.shape
112
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
113
+ except AssertionError as e:
114
+ e.args += (pointer.shape, array.shape)
115
+ raise
116
+ logger.info(f"Initialize PyTorch weight {name}")
117
+ pointer.data = torch.from_numpy(array)
118
+ return model
119
+
120
+
121
+ @torch.jit.script
122
+ def gelu_impl(x):
123
+ """OpenAI's gelu implementation."""
124
+ return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
125
+ (1.0 + 0.044715 * x * x)))
126
+
127
+
128
+ def gelu(x):
129
+ return gelu_impl(x)
130
+
131
+
132
+ class RotaryEmbedding(torch.nn.Module):
133
+ def __init__(self, dim, base=10000, precision=torch.half, learnable=False):
134
+ super().__init__()
135
+ inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
136
+ inv_freq = inv_freq.half()
137
+ self.learnable = learnable
138
+ if learnable:
139
+ self.inv_freq = torch.nn.Parameter(inv_freq)
140
+ self.max_seq_len_cached = None
141
+ else:
142
+ self.register_buffer('inv_freq', inv_freq)
143
+ self.max_seq_len_cached = None
144
+ self.cos_cached = None
145
+ self.sin_cached = None
146
+ self.precision = precision
147
+
148
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
149
+ error_msgs):
150
+ pass
151
+
152
+ def forward(self, x, seq_dim=1, seq_len=None):
153
+ if seq_len is None:
154
+ seq_len = x.shape[seq_dim]
155
+ if self.max_seq_len_cached is None or (seq_len > self.max_seq_len_cached):
156
+ self.max_seq_len_cached = None if self.learnable else seq_len
157
+ t = torch.arange(seq_len, device=x.device, dtype=self.inv_freq.dtype)
158
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
159
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
160
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
161
+ if self.precision == torch.bfloat16:
162
+ emb = emb.float()
163
+
164
+ # [sx, 1 (b * np), hn]
165
+ cos_cached = emb.cos()[:, None, :]
166
+ sin_cached = emb.sin()[:, None, :]
167
+ if self.precision == torch.bfloat16:
168
+ cos_cached = cos_cached.bfloat16()
169
+ sin_cached = sin_cached.bfloat16()
170
+ if self.learnable:
171
+ return cos_cached, sin_cached
172
+ self.cos_cached, self.sin_cached = cos_cached, sin_cached
173
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
174
+
175
+
176
+ def rotate_half(x):
177
+ x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
178
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
179
+
180
+
181
+ @torch.jit.script
182
+ def apply_rotary_pos_emb_index(q, k, cos, sin, position_id):
183
+ # position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn]
184
+ cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \
185
+ F.embedding(position_id, sin.squeeze(1)).unsqueeze(2)
186
+ q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
187
+ return q, k
188
+
189
+
190
+ def attention_fn(
191
+ self,
192
+ query_layer,
193
+ key_layer,
194
+ value_layer,
195
+ attention_mask,
196
+ hidden_size_per_partition,
197
+ layer_id,
198
+ layer_past=None,
199
+ scaling_attention_score=True,
200
+ use_cache=False,
201
+ ):
202
+ if layer_past is not None:
203
+ past_key, past_value = layer_past
204
+ key_layer = torch.cat((past_key, key_layer), dim=0)
205
+ value_layer = torch.cat((past_value, value_layer), dim=0)
206
+
207
+ # seqlen, batch, num_attention_heads, hidden_size_per_attention_head
208
+ seq_len, b, nh, hidden_size = key_layer.shape
209
+
210
+ if use_cache:
211
+ present = (key_layer, value_layer)
212
+ else:
213
+ present = None
214
+
215
+ query_key_layer_scaling_coeff = float(layer_id + 1)
216
+ if scaling_attention_score:
217
+ query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff)
218
+
219
+ # ===================================
220
+ # Raw attention scores. [b, np, s, s]
221
+ # ===================================
222
+
223
+ # [b, np, sq, sk]
224
+ output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0))
225
+
226
+ # [sq, b, np, hn] -> [sq, b * np, hn]
227
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
228
+ # [sk, b, np, hn] -> [sk, b * np, hn]
229
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1)
230
+
231
+ matmul_result = torch.empty(
232
+ output_size[0] * output_size[1],
233
+ output_size[2],
234
+ output_size[3],
235
+ dtype=query_layer.dtype,
236
+ device=query_layer.device,
237
+ )
238
+
239
+ matmul_result = torch.baddbmm(
240
+ matmul_result,
241
+ query_layer.transpose(0, 1), # [b * np, sq, hn]
242
+ key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk]
243
+ beta=0.0,
244
+ alpha=1.0,
245
+ )
246
+
247
+ # change view to [b, np, sq, sk]
248
+ attention_scores = matmul_result.view(*output_size)
249
+
250
+ if self.scale_mask_softmax:
251
+ self.scale_mask_softmax.scale = query_key_layer_scaling_coeff
252
+ attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous())
253
+ else:
254
+ if not (attention_mask == 0).all():
255
+ # if auto-regressive, skip
256
+ attention_scores.masked_fill_(attention_mask, -10000.0)
257
+ dtype = attention_scores.type()
258
+ attention_scores = attention_scores.float()
259
+ attention_scores = attention_scores * query_key_layer_scaling_coeff
260
+
261
+ attention_probs = F.softmax(attention_scores, dim=-1)
262
+
263
+ attention_probs = attention_probs.type(dtype)
264
+
265
+ # =========================
266
+ # Context layer. [sq, b, hp]
267
+ # =========================
268
+
269
+ # value_layer -> context layer.
270
+ # [sk, b, np, hn] --> [b, np, sq, hn]
271
+
272
+ # context layer shape: [b, np, sq, hn]
273
+ output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3))
274
+
275
+ # change view [sk, b * np, hn]
276
+ value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1)
277
+
278
+ # change view [b * np, sq, sk]
279
+ attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
280
+
281
+ # matmul: [b * np, sq, hn]
282
+ context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1))
283
+
284
+ # change view [b, np, sq, hn]
285
+ context_layer = context_layer.view(*output_size)
286
+
287
+ # [b, np, sq, hn] --> [sq, b, np, hn]
288
+ context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
289
+
290
+ # [sq, b, np, hn] --> [sq, b, hp]
291
+ new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,)
292
+ context_layer = context_layer.view(*new_context_layer_shape)
293
+
294
+ outputs = (context_layer, present, attention_probs)
295
+
296
+ return outputs
297
+
298
+
299
+ class SelfAttention(torch.nn.Module):
300
+ def __init__(self, hidden_size, num_attention_heads,
301
+ layer_id, hidden_size_per_attention_head=None, bias=True,
302
+ params_dtype=torch.float, position_encoding_2d=True):
303
+ super(SelfAttention, self).__init__()
304
+
305
+ self.layer_id = layer_id
306
+ self.hidden_size = hidden_size
307
+ self.hidden_size_per_partition = hidden_size
308
+ self.num_attention_heads = num_attention_heads
309
+ self.num_attention_heads_per_partition = num_attention_heads
310
+ self.position_encoding_2d = position_encoding_2d
311
+ self.rotary_emb = RotaryEmbedding(
312
+ self.hidden_size // (self.num_attention_heads * 2)
313
+ if position_encoding_2d
314
+ else self.hidden_size // self.num_attention_heads,
315
+ base=10000,
316
+ precision=torch.half,
317
+ learnable=False,
318
+ )
319
+
320
+ self.scale_mask_softmax = None
321
+
322
+ if hidden_size_per_attention_head is None:
323
+ self.hidden_size_per_attention_head = hidden_size // num_attention_heads
324
+ else:
325
+ self.hidden_size_per_attention_head = hidden_size_per_attention_head
326
+
327
+ self.inner_hidden_size = num_attention_heads * self.hidden_size_per_attention_head
328
+
329
+ # Strided linear layer.
330
+ self.query_key_value = skip_init(
331
+ torch.nn.Linear,
332
+ hidden_size,
333
+ 3 * self.inner_hidden_size,
334
+ bias=bias,
335
+ dtype=params_dtype,
336
+ )
337
+
338
+ self.dense = skip_init(
339
+ torch.nn.Linear,
340
+ self.inner_hidden_size,
341
+ hidden_size,
342
+ bias=bias,
343
+ dtype=params_dtype,
344
+ )
345
+
346
+ @staticmethod
347
+ def attention_mask_func(attention_scores, attention_mask):
348
+ attention_scores.masked_fill_(attention_mask, -10000.0)
349
+ return attention_scores
350
+
351
+ def split_tensor_along_last_dim(self, tensor, num_partitions,
352
+ contiguous_split_chunks=False):
353
+ """Split a tensor along its last dimension.
354
+ Arguments:
355
+ tensor: input tensor.
356
+ num_partitions: number of partitions to split the tensor
357
+ contiguous_split_chunks: If True, make each chunk contiguous
358
+ in memory.
359
+ """
360
+ # Get the size and dimension.
361
+ last_dim = tensor.dim() - 1
362
+ last_dim_size = tensor.size()[last_dim] // num_partitions
363
+ # Split.
364
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
365
+ # Note: torch.split does not create contiguous tensors by default.
366
+ if contiguous_split_chunks:
367
+ return tuple(chunk.contiguous() for chunk in tensor_list)
368
+
369
+ return tensor_list
370
+
371
+ def forward(
372
+ self,
373
+ hidden_states: torch.Tensor,
374
+ position_ids,
375
+ attention_mask: torch.Tensor,
376
+ layer_id,
377
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
378
+ use_cache: bool = False,
379
+ output_attentions: bool = False,
380
+ ):
381
+ """
382
+ hidden_states: [seq_len, batch, hidden_size]
383
+ attention_mask: [(1, 1), seq_len, seq_len]
384
+ """
385
+
386
+ # [seq_len, batch, 3 * hidden_size]
387
+ mixed_raw_layer = self.query_key_value(hidden_states)
388
+
389
+ # [seq_len, batch, 3 * hidden_size] --> [seq_len, batch, num_attention_heads, 3 * hidden_size_per_attention_head]
390
+ new_tensor_shape = mixed_raw_layer.size()[:-1] + (
391
+ self.num_attention_heads_per_partition,
392
+ 3 * self.hidden_size_per_attention_head,
393
+ )
394
+ mixed_raw_layer = mixed_raw_layer.view(*new_tensor_shape)
395
+
396
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
397
+ (query_layer, key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_raw_layer, 3)
398
+
399
+ if self.position_encoding_2d:
400
+ q1, q2 = query_layer.chunk(2, dim=(query_layer.ndim - 1))
401
+ k1, k2 = key_layer.chunk(2, dim=(key_layer.ndim - 1))
402
+ cos, sin = self.rotary_emb(q1, seq_len=position_ids.max() + 1)
403
+ position_ids, block_position_ids = position_ids[:, 0, :].transpose(0, 1).contiguous(), \
404
+ position_ids[:, 1, :].transpose(0, 1).contiguous()
405
+ q1, k1 = apply_rotary_pos_emb_index(q1, k1, cos, sin, position_ids)
406
+ q2, k2 = apply_rotary_pos_emb_index(q2, k2, cos, sin, block_position_ids)
407
+ query_layer = torch.concat([q1, q2], dim=(q1.ndim - 1))
408
+ key_layer = torch.concat([k1, k2], dim=(k1.ndim - 1))
409
+ else:
410
+ position_ids = position_ids.transpose(0, 1)
411
+ cos, sin = self.rotary_emb(value_layer, seq_len=position_ids.max() + 1)
412
+ # [seq_len, batch, num_attention_heads, hidden_size_per_attention_head]
413
+ query_layer, key_layer = apply_rotary_pos_emb_index(query_layer, key_layer, cos, sin, position_ids)
414
+
415
+ # [seq_len, batch, hidden_size]
416
+ context_layer, present, attention_probs = attention_fn(
417
+ self=self,
418
+ query_layer=query_layer,
419
+ key_layer=key_layer,
420
+ value_layer=value_layer,
421
+ attention_mask=attention_mask,
422
+ hidden_size_per_partition=self.hidden_size_per_partition,
423
+ layer_id=layer_id,
424
+ layer_past=layer_past,
425
+ use_cache=use_cache
426
+ )
427
+
428
+ output = self.dense(context_layer)
429
+
430
+ outputs = (output, present)
431
+
432
+ if output_attentions:
433
+ outputs += (attention_probs,)
434
+
435
+ return outputs # output, present, attention_probs
436
+
437
+
438
+ class GEGLU(torch.nn.Module):
439
+ def __init__(self):
440
+ super().__init__()
441
+ self.activation_fn = F.gelu
442
+
443
+ def forward(self, x):
444
+ # dim=-1 breaks in jit for pt<1.10
445
+ x1, x2 = x.chunk(2, dim=(x.ndim - 1))
446
+ return x1 * self.activation_fn(x2)
447
+
448
+
449
+ class GLU(torch.nn.Module):
450
+ def __init__(self, hidden_size, inner_hidden_size=None,
451
+ layer_id=None, bias=True, activation_func=gelu, params_dtype=torch.float):
452
+ super(GLU, self).__init__()
453
+ self.layer_id = layer_id
454
+ self.activation_func = activation_func
455
+
456
+ # Project to 4h.
457
+ self.hidden_size = hidden_size
458
+ if inner_hidden_size is None:
459
+ inner_hidden_size = 4 * hidden_size
460
+ self.inner_hidden_size = inner_hidden_size
461
+ self.dense_h_to_4h = skip_init(
462
+ torch.nn.Linear,
463
+ self.hidden_size,
464
+ self.inner_hidden_size,
465
+ bias=bias,
466
+ dtype=params_dtype,
467
+ )
468
+ # Project back to h.
469
+ self.dense_4h_to_h = skip_init(
470
+ torch.nn.Linear,
471
+ self.inner_hidden_size,
472
+ self.hidden_size,
473
+ bias=bias,
474
+ dtype=params_dtype,
475
+ )
476
+
477
+ def forward(self, hidden_states):
478
+ """
479
+ hidden_states: [seq_len, batch, hidden_size]
480
+ """
481
+
482
+ # [seq_len, batch, inner_hidden_size]
483
+ intermediate_parallel = self.dense_h_to_4h(hidden_states)
484
+
485
+ intermediate_parallel = self.activation_func(intermediate_parallel)
486
+
487
+ output = self.dense_4h_to_h(intermediate_parallel)
488
+
489
+ return output
490
+
491
+
492
+ class GLMBlock(torch.nn.Module):
493
+ def __init__(
494
+ self,
495
+ hidden_size,
496
+ num_attention_heads,
497
+ layernorm_epsilon,
498
+ layer_id,
499
+ inner_hidden_size=None,
500
+ hidden_size_per_attention_head=None,
501
+ layernorm=LayerNorm,
502
+ use_bias=True,
503
+ params_dtype=torch.float,
504
+ num_layers=28,
505
+ position_encoding_2d=True
506
+ ):
507
+ super(GLMBlock, self).__init__()
508
+ # Set output layer initialization if not provided.
509
+
510
+ self.layer_id = layer_id
511
+
512
+ # Layernorm on the input data.
513
+ self.input_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
514
+
515
+ self.position_encoding_2d = position_encoding_2d
516
+
517
+ # Self attention.
518
+ self.attention = SelfAttention(
519
+ hidden_size,
520
+ num_attention_heads,
521
+ layer_id,
522
+ hidden_size_per_attention_head=hidden_size_per_attention_head,
523
+ bias=use_bias,
524
+ params_dtype=params_dtype,
525
+ position_encoding_2d=self.position_encoding_2d
526
+ )
527
+
528
+ # Layernorm on the input data.
529
+ self.post_attention_layernorm = layernorm(hidden_size, eps=layernorm_epsilon)
530
+
531
+ self.num_layers = num_layers
532
+
533
+ # GLU
534
+ self.mlp = GLU(
535
+ hidden_size,
536
+ inner_hidden_size=inner_hidden_size,
537
+ bias=use_bias,
538
+ layer_id=layer_id,
539
+ params_dtype=params_dtype,
540
+ )
541
+
542
+ def forward(
543
+ self,
544
+ hidden_states: torch.Tensor,
545
+ position_ids,
546
+ attention_mask: torch.Tensor,
547
+ layer_id,
548
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
549
+ use_cache: bool = False,
550
+ output_attentions: bool = False,
551
+ ):
552
+ """
553
+ hidden_states: [seq_len, batch, hidden_size]
554
+ attention_mask: [(1, 1), seq_len, seq_len]
555
+ """
556
+
557
+ # Layer norm at the begining of the transformer layer.
558
+ # [seq_len, batch, hidden_size]
559
+ attention_input = self.input_layernorm(hidden_states)
560
+
561
+ # Self attention.
562
+ attention_outputs = self.attention(
563
+ attention_input,
564
+ position_ids,
565
+ attention_mask=attention_mask,
566
+ layer_id=layer_id,
567
+ layer_past=layer_past,
568
+ use_cache=use_cache,
569
+ output_attentions=output_attentions
570
+ )
571
+
572
+ attention_output = attention_outputs[0]
573
+
574
+ outputs = attention_outputs[1:]
575
+
576
+ # Residual connection.
577
+ alpha = (2 * self.num_layers) ** 0.5
578
+ hidden_states = attention_input * alpha + attention_output
579
+
580
+ mlp_input = self.post_attention_layernorm(hidden_states)
581
+
582
+ # MLP.
583
+ mlp_output = self.mlp(mlp_input)
584
+
585
+ # Second residual connection.
586
+ output = mlp_input * alpha + mlp_output
587
+
588
+ if use_cache:
589
+ outputs = (output,) + outputs
590
+ else:
591
+ outputs = (output,) + outputs[1:]
592
+
593
+ return outputs # hidden_states, present, attentions
594
+
595
+
596
+ class ChatGLMPreTrainedModel(PreTrainedModel):
597
+ """
598
+ An abstract class to handle weights initialization and
599
+ a simple interface for downloading and loading pretrained models.
600
+ """
601
+
602
+ is_parallelizable = True
603
+ supports_gradient_checkpointing = False
604
+ config_class = ChatGLMConfig
605
+ base_model_prefix = "transformer"
606
+ _no_split_modules = ["GLM6BBlock"]
607
+
608
+ def __init__(self, *inputs, **kwargs):
609
+ super().__init__(*inputs, **kwargs)
610
+
611
+ def _init_weights(self, module: nn.Module):
612
+ """Initialize the weights."""
613
+ return
614
+
615
+
616
+ CHATGLM_6B_START_DOCSTRING = r"""
617
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.
618
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general
619
+ usage and behavior.
620
+
621
+ Parameters:
622
+ config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.
623
+ Initializing with a config file does not load the weights associated with the model, only the configuration.
624
+ Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
625
+ """
626
+
627
+ CHATGLM_6B_INPUTS_DOCSTRING = r"""
628
+ Args:
629
+ input_ids (`torch.LongTensor` of shape `({0})`):
630
+ Indices of input sequence tokens in the vocabulary.
631
+
632
+ Indices can be obtained using [`ChatGLM6BTokenizer`].
633
+ See [`PreTrainedTokenizer.encode`] and
634
+ [`PreTrainedTokenizer.__call__`] for details.
635
+
636
+ [What are input IDs?](../glossary#input-ids)
637
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
638
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
639
+
640
+ - 1 for tokens that are **not masked**,
641
+ - 0 for tokens that are **masked**.
642
+
643
+ [What are attention masks?](../glossary#attention-mask)
644
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
645
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
646
+
647
+ - 0 corresponds to a *sentence A* token,
648
+ - 1 corresponds to a *sentence B* token.
649
+
650
+ [What are token type IDs?](../glossary#token-type-ids)
651
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
652
+ Indices of positions of each input sequence tokens in the position embeddings.
653
+ Selected in the range `[0, config.max_position_embeddings - 1]`.
654
+
655
+ [What are position IDs?](../glossary#position-ids)
656
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
657
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
658
+
659
+ - 1 indicates the head is **not masked**,
660
+ - 0 indicates the head is **masked**.
661
+
662
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
663
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
664
+ This is useful if you want more control over how to convert *input_ids* indices into associated vectors
665
+ than the model's internal embedding lookup matrix.
666
+ output_attentions (`bool`, *optional*):
667
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
668
+ tensors for more detail.
669
+ output_hidden_states (`bool`, *optional*):
670
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
671
+ more detail.
672
+ return_dict (`bool`, *optional*):
673
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
674
+ """
675
+
676
+
677
+ @add_start_docstrings(
678
+ "The bare ChatGLM-6B Model transformer outputting raw hidden-states without any specific head on top.",
679
+ CHATGLM_6B_START_DOCSTRING,
680
+ )
681
+ class ChatGLMModel(ChatGLMPreTrainedModel):
682
+ """
683
+
684
+ The model can behave as an encoder (with only self-attention) as well
685
+ as a decoder, in which case a layer of cross-attention is added between
686
+ the self-attention layers, following the architecture described in [Attention is
687
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,
688
+ Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
689
+
690
+ To behave as an decoder the model needs to be initialized with the
691
+ `is_decoder` argument of the configuration set to `True`.
692
+ To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`
693
+ argument and `add_cross_attention` set to `True`; an
694
+ `encoder_hidden_states` is then expected as an input to the forward pass.
695
+ """
696
+
697
+ def __init__(self, config: ChatGLMConfig):
698
+ super().__init__(config)
699
+
700
+ # recording parameters
701
+ self.max_sequence_length = config.max_sequence_length
702
+ self.hidden_size = config.hidden_size
703
+ self.params_dtype = torch.half
704
+ self.num_attention_heads = config.num_attention_heads
705
+ self.vocab_size = config.vocab_size
706
+ self.num_layers = config.num_layers
707
+ self.layernorm_epsilon = config.layernorm_epsilon
708
+ self.inner_hidden_size = config.inner_hidden_size
709
+ self.hidden_size_per_attention_head = self.hidden_size // self.num_attention_heads
710
+ self.position_encoding_2d = config.position_encoding_2d
711
+
712
+ self.word_embeddings = skip_init(
713
+ torch.nn.Embedding,
714
+ num_embeddings=self.vocab_size, embedding_dim=self.hidden_size,
715
+ dtype=self.params_dtype
716
+ )
717
+
718
+ def get_layer(layer_id):
719
+ return GLMBlock(
720
+ self.hidden_size,
721
+ self.num_attention_heads,
722
+ self.layernorm_epsilon,
723
+ layer_id,
724
+ inner_hidden_size=self.inner_hidden_size,
725
+ hidden_size_per_attention_head=self.hidden_size_per_attention_head,
726
+ layernorm=LayerNorm,
727
+ use_bias=True,
728
+ params_dtype=self.params_dtype,
729
+ position_encoding_2d=self.position_encoding_2d,
730
+ )
731
+
732
+ self.layers = torch.nn.ModuleList(
733
+ [get_layer(layer_id) for layer_id in range(self.num_layers)]
734
+ )
735
+
736
+ # Final layer norm before output.
737
+ self.final_layernorm = LayerNorm(self.hidden_size, eps=self.layernorm_epsilon)
738
+
739
+ def get_input_embeddings(self):
740
+ return self.word_embeddings
741
+
742
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
743
+ self.word_embeddings = new_embeddings
744
+
745
+ @staticmethod
746
+ def get_masks(seq, device):
747
+ context_length = seq.index(150004) + 1
748
+
749
+ attention_mask = torch.ones((1, len(seq), len(seq)), device=device)
750
+ attention_mask.tril_()
751
+ attention_mask[..., :context_length - 1] = 1
752
+ attention_mask.unsqueeze_(1)
753
+ attention_mask = (attention_mask < 0.5).bool()
754
+
755
+ return attention_mask
756
+
757
+ def get_position_ids(self, seq, mask_position, device, gmask=False):
758
+ context_length = seq.index(150004) + 1
759
+ if self.position_encoding_2d:
760
+ seq_length = seq.index(150004)
761
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
762
+ if not gmask:
763
+ position_ids[seq_length:] = mask_position
764
+ block_position_ids = torch.cat((
765
+ torch.zeros(seq_length, dtype=torch.long, device=device),
766
+ torch.arange(context_length - seq_length, dtype=torch.long, device=device) + 1
767
+ ))
768
+ position_ids = torch.stack((position_ids, block_position_ids), dim=0)
769
+ else:
770
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
771
+ if not gmask:
772
+ position_ids[context_length - 1:] = mask_position
773
+
774
+ position_ids = position_ids.unsqueeze(0)
775
+
776
+ return position_ids
777
+
778
+ @add_start_docstrings_to_model_forward(CHATGLM_6B_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
779
+ @add_code_sample_docstrings(
780
+ checkpoint=_CHECKPOINT_FOR_DOC,
781
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
782
+ config_class=_CONFIG_FOR_DOC,
783
+ )
784
+ def forward(
785
+ self,
786
+ input_ids: Optional[torch.LongTensor] = None,
787
+ position_ids: Optional[torch.LongTensor] = None,
788
+ attention_mask: Optional[torch.Tensor] = None,
789
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
790
+ inputs_embeds: Optional[torch.LongTensor] = None,
791
+ use_cache: Optional[bool] = None,
792
+ output_attentions: Optional[bool] = None,
793
+ output_hidden_states: Optional[bool] = None,
794
+ return_dict: Optional[bool] = None,
795
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPast]:
796
+
797
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
798
+ output_hidden_states = (
799
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
800
+ )
801
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
802
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
803
+
804
+ if input_ids is not None and inputs_embeds is not None:
805
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
806
+ elif input_ids is not None:
807
+ batch_size, seq_length = input_ids.shape[:2]
808
+ elif inputs_embeds is not None:
809
+ batch_size, seq_length, _ = inputs_embeds.shape[:2]
810
+ else:
811
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
812
+
813
+ if past_key_values is None:
814
+ past_key_values = tuple([None] * len(self.layers))
815
+
816
+ MASK, gMASK = 150000, 150001
817
+ mask_token = MASK if MASK in input_ids else gMASK
818
+ use_gmask = False if MASK in input_ids else gMASK
819
+ seq = input_ids[0].tolist()
820
+
821
+ mask_position = seq.index(mask_token)
822
+
823
+ if attention_mask is None:
824
+ attention_mask = self.get_masks(
825
+ seq=seq,
826
+ device=input_ids.device
827
+ )
828
+
829
+ if position_ids is None:
830
+ position_ids = self.get_position_ids(
831
+ seq=seq,
832
+ mask_position=mask_position,
833
+ device=input_ids.device,
834
+ gmask=use_gmask
835
+ )
836
+
837
+ if inputs_embeds is None:
838
+ inputs_embeds = self.word_embeddings(input_ids)
839
+
840
+ # [seq_len, batch, hidden_size]
841
+ hidden_states = inputs_embeds.transpose(0, 1)
842
+
843
+ presents = () if use_cache else None
844
+ all_self_attentions = () if output_attentions else None
845
+ all_hidden_states = () if output_hidden_states else None
846
+
847
+ seq_length_with_past = seq_length
848
+ past_key_values_length = 0
849
+ if past_key_values[0] is not None:
850
+ past_key_values_length = past_key_values[0][0].shape[0]
851
+ seq_length_with_past = seq_length_with_past + past_key_values_length
852
+ if attention_mask is None:
853
+ attention_mask = torch.zeros(1, 1, device=input_ids.device).bool()
854
+
855
+ else:
856
+ attention_mask = attention_mask.to(input_ids.device)
857
+
858
+ for i, layer in enumerate(self.layers):
859
+
860
+ if output_hidden_states:
861
+ all_hidden_states = all_hidden_states + (hidden_states,)
862
+
863
+ layer_ret = layer(
864
+ hidden_states,
865
+ position_ids=position_ids,
866
+ attention_mask=attention_mask,
867
+ layer_id=torch.tensor(i),
868
+ layer_past=past_key_values[i],
869
+ use_cache=use_cache,
870
+ output_attentions=output_attentions
871
+ )
872
+
873
+ hidden_states = layer_ret[0]
874
+
875
+ if use_cache:
876
+ presents = presents + (layer_ret[1],)
877
+
878
+ if output_attentions:
879
+ all_self_attentions = all_self_attentions + (layer_ret[2 if use_cache else 1],)
880
+
881
+ # Final layer norm.
882
+ hidden_states = self.final_layernorm(hidden_states)
883
+
884
+ if output_hidden_states:
885
+ all_hidden_states = all_hidden_states + (hidden_states,)
886
+
887
+ if not return_dict:
888
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
889
+
890
+ return BaseModelOutputWithPast(
891
+ last_hidden_state=hidden_states,
892
+ past_key_values=presents,
893
+ hidden_states=all_hidden_states,
894
+ attentions=all_self_attentions,
895
+ )
896
+
897
+
898
+ class ChatGLMForConditionalGeneration(ChatGLMPreTrainedModel):
899
+ def __init__(self, config):
900
+ super().__init__(config)
901
+
902
+ # self.hidden_size = config.hidden_size
903
+ # self.params_dtype = torch.half
904
+ # self.vocab_size = config.vocab_size
905
+ self.max_sequence_length = config.max_sequence_length
906
+
907
+ self.position_encoding_2d = config.position_encoding_2d
908
+
909
+ self.transformer = ChatGLMModel(config)
910
+
911
+ self.lm_head = skip_init(
912
+ nn.Linear,
913
+ config.hidden_size,
914
+ config.vocab_size,
915
+ bias=False,
916
+ dtype=torch.half
917
+ )
918
+
919
+ def get_output_embeddings(self):
920
+ return self.lm_head
921
+
922
+ def set_output_embeddings(self, new_embeddings):
923
+ self.lm_head = new_embeddings
924
+
925
+ def get_masks_and_position_ids(self, seq, mask_position, context_length, device, gmask=False):
926
+ attention_mask = torch.ones((1, context_length, context_length), device=device)
927
+ attention_mask.tril_()
928
+ attention_mask[..., :context_length - 1] = 1
929
+ attention_mask.unsqueeze_(1)
930
+ attention_mask = (attention_mask < 0.5).bool()
931
+
932
+ if self.position_encoding_2d:
933
+ seq_length = seq.index(150004)
934
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
935
+ if not gmask:
936
+ position_ids[seq_length:] = mask_position
937
+ block_position_ids = torch.cat((
938
+ torch.zeros(seq_length, dtype=torch.long, device=device),
939
+ torch.arange(context_length - seq_length, dtype=torch.long, device=device) + 1
940
+ ))
941
+ position_ids = torch.stack((position_ids, block_position_ids), dim=0)
942
+ else:
943
+ position_ids = torch.arange(context_length, dtype=torch.long, device=device)
944
+ if not gmask:
945
+ position_ids[context_length - 1:] = mask_position
946
+
947
+ position_ids = position_ids.unsqueeze(0)
948
+
949
+ return attention_mask, position_ids
950
+
951
+ def prepare_inputs_for_generation(
952
+ self,
953
+ input_ids: torch.LongTensor,
954
+ past: Optional[torch.Tensor] = None,
955
+ past_key_values: Optional[torch.Tensor] = None,
956
+ attention_mask: Optional[torch.Tensor] = None,
957
+ **kwargs
958
+ ) -> dict:
959
+
960
+ MASK, gMASK = 150000, 150001
961
+ mask_token = MASK if MASK in input_ids else gMASK
962
+ use_gmask = False if MASK in input_ids else gMASK
963
+ seq = input_ids[0].tolist()
964
+ mask_position = seq.index(mask_token)
965
+
966
+ if mask_token not in seq:
967
+ raise ValueError("You have to add either [MASK] or [gMASK] in your input")
968
+
969
+ # only last token for input_ids if past is not None
970
+ if past is not None or past_key_values is not None:
971
+ context_length = seq.index(150004)
972
+ last_token = input_ids[:, -1].unsqueeze(-1)
973
+ if self.position_encoding_2d:
974
+ position_ids = torch.tensor([[[mask_position], [len(seq) - context_length]]], dtype=torch.long,
975
+ device=input_ids.device)
976
+ else:
977
+ position_ids = torch.tensor([[mask_position]], dtype=torch.long, device=input_ids.device)
978
+
979
+ if past is None:
980
+ past = past_key_values
981
+ return {
982
+ "input_ids": last_token,
983
+ "past_key_values": past,
984
+ "position_ids": position_ids,
985
+ }
986
+ else:
987
+ attention_mask, position_ids = self.get_masks_and_position_ids(
988
+ seq=seq,
989
+ mask_position=mask_position,
990
+ context_length=len(seq),
991
+ device=input_ids.device,
992
+ gmask=use_gmask
993
+ )
994
+
995
+ return {
996
+ "input_ids": input_ids,
997
+ "past_key_values": past,
998
+ "position_ids": position_ids,
999
+ "attention_mask": attention_mask
1000
+ }
1001
+
1002
+ def forward(
1003
+ self,
1004
+ input_ids: Optional[torch.Tensor] = None,
1005
+ position_ids: Optional[torch.Tensor] = None,
1006
+ attention_mask: Optional[torch.Tensor] = None,
1007
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1008
+ inputs_embeds: Optional[torch.Tensor] = None,
1009
+ labels: Optional[torch.Tensor] = None,
1010
+ use_cache: Optional[bool] = None,
1011
+ output_attentions: Optional[bool] = None,
1012
+ output_hidden_states: Optional[bool] = None,
1013
+ return_dict: Optional[bool] = None,
1014
+ ):
1015
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1016
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1017
+
1018
+ transformer_outputs = self.transformer(
1019
+ input_ids=input_ids,
1020
+ position_ids=position_ids,
1021
+ attention_mask=attention_mask,
1022
+ past_key_values=past_key_values,
1023
+ inputs_embeds=inputs_embeds,
1024
+ use_cache=use_cache,
1025
+ output_attentions=output_attentions,
1026
+ output_hidden_states=output_hidden_states,
1027
+ return_dict=return_dict,
1028
+ )
1029
+
1030
+ hidden_states = transformer_outputs[0]
1031
+
1032
+ lm_logits = self.lm_head(hidden_states).permute(1, 0, 2).contiguous()
1033
+
1034
+ loss = None
1035
+ if labels is not None:
1036
+ lm_logits = lm_logits.to(torch.float32)
1037
+
1038
+ # Shift so that tokens < n predict n
1039
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1040
+ shift_labels = labels[..., 1:].contiguous()
1041
+ # Flatten the tokens
1042
+ loss_fct = CrossEntropyLoss()
1043
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1044
+
1045
+ lm_logits = lm_logits.to(hidden_states.dtype)
1046
+ loss = loss.to(hidden_states.dtype)
1047
+
1048
+ if not return_dict:
1049
+ output = (lm_logits,) + transformer_outputs[1:]
1050
+ return ((loss,) + output) if loss is not None else output
1051
+
1052
+ return CausalLMOutputWithPast(
1053
+ loss=loss,
1054
+ logits=lm_logits,
1055
+ past_key_values=transformer_outputs.past_key_values,
1056
+ hidden_states=transformer_outputs.hidden_states,
1057
+ attentions=transformer_outputs.attentions,
1058
+ )
1059
+
1060
+ @staticmethod
1061
+ def _reorder_cache(
1062
+ past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1063
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1064
+ """
1065
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1066
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1067
+ beam_idx at every generation step.
1068
+
1069
+ Output shares the same memory storage as `past`.
1070
+ """
1071
+ return tuple(
1072
+ (
1073
+ layer_past[0].index_select(1, beam_idx.to(layer_past[0].device)),
1074
+ layer_past[1].index_select(1, beam_idx.to(layer_past[1].device)),
1075
+ )
1076
+ for layer_past in past
1077
+ )
1078
+
1079
+ @torch.no_grad()
1080
+ def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,
1081
+ do_sample=True, top_p=0.7, temperature=0.95, **kwargs):
1082
+ if history is None:
1083
+ history = []
1084
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
1085
+ "temperature": temperature, **kwargs}
1086
+ if not history:
1087
+ prompt = query
1088
+ else:
1089
+ prompt = ""
1090
+ for i, (old_query, response) in enumerate(history):
1091
+ prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)
1092
+ prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)
1093
+ input_ids = tokenizer([prompt], return_tensors="pt", padding=True)
1094
+ input_ids = input_ids.to(self.device)
1095
+ outputs = self.generate(**input_ids, **gen_kwargs)
1096
+ outputs = outputs.tolist()[0][len(input_ids["input_ids"][0]) - 2:]
1097
+ response = tokenizer.decode(outputs)
1098
+ response = response.strip()
1099
+ response = response.replace("[[训练时间]]", "2023年")
1100
+ history = history + [(query, response)]
1101
+ return response, history
1102
+
1103
+ @torch.no_grad()
1104
+ def generate(
1105
+ self,
1106
+ **kwargs,
1107
+ ):
1108
+ MASK, gMASK = 150000, 150001
1109
+ bos, eos = 150004, 150005
1110
+
1111
+ if "eos_token_id" not in kwargs:
1112
+ kwargs["eos_token_id"] = eos
1113
+
1114
+ stop = False
1115
+
1116
+ return_seqs = []
1117
+
1118
+ while True:
1119
+ output_ids = super().generate(**kwargs)
1120
+
1121
+ return_seqs = []
1122
+ max_length = 0
1123
+
1124
+ for i in range(output_ids.shape[0]):
1125
+ output_seq = output_ids[i].tolist()
1126
+ mask_token = MASK if MASK in output_seq else gMASK
1127
+ mask_position = output_seq.index(mask_token)
1128
+ bos_position = output_seq.index(bos)
1129
+ if eos in output_seq:
1130
+ eos_position = output_seq.index(eos)
1131
+ else:
1132
+ eos_position = len(output_seq)
1133
+
1134
+ return_seq = output_seq[:mask_position] + output_seq[bos_position + 1:eos_position] + output_seq[
1135
+ mask_position + 1:bos_position]
1136
+ max_length = max(max_length, len(return_seq))
1137
+ return_seqs.append(return_seq)
1138
+
1139
+ for i in range(output_ids.shape[0]):
1140
+ return_seqs[i] = [0] * (max_length - len(return_seqs[i])) + return_seqs[i] # padding
1141
+ if mask_token not in return_seqs[i]:
1142
+ stop = True
1143
+
1144
+ if stop:
1145
+ break
1146
+
1147
+ for return_seq in return_seqs:
1148
+ return_seq += [bos]
1149
+
1150
+ kwargs['input_ids'] = torch.tensor(return_seqs, dtype=torch.long, device=kwargs['input_ids'].device)
1151
+
1152
+ return torch.tensor(return_seqs, dtype=torch.long, device=kwargs['input_ids'].device)
1153
+
1154
+ def quantize(self, bits: int):
1155
+ from .quantization import quantize
1156
+ self.transformer = quantize(self.transformer, bits)
1157
+ return self
moe/pytorch_model.bin.index.json ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 13744473856
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00008-of-00008.bin",
7
+ "transformer.final_layernorm.bias": "pytorch_model-00007-of-00008.bin",
8
+ "transformer.final_layernorm.weight": "pytorch_model-00007-of-00008.bin",
9
+ "transformer.layers.0.attention.dense.bias": "pytorch_model-00001-of-00008.bin",
10
+ "transformer.layers.0.attention.dense.weight": "pytorch_model-00001-of-00008.bin",
11
+ "transformer.layers.0.attention.query_key_value.bias": "pytorch_model-00001-of-00008.bin",
12
+ "transformer.layers.0.attention.query_key_value.weight": "pytorch_model-00001-of-00008.bin",
13
+ "transformer.layers.0.attention.rotary_emb.inv_freq": "pytorch_model-00001-of-00008.bin",
14
+ "transformer.layers.0.input_layernorm.bias": "pytorch_model-00001-of-00008.bin",
15
+ "transformer.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00008.bin",
16
+ "transformer.layers.0.mlp.dense_4h_to_h.bias": "pytorch_model-00001-of-00008.bin",
17
+ "transformer.layers.0.mlp.dense_4h_to_h.weight": "pytorch_model-00001-of-00008.bin",
18
+ "transformer.layers.0.mlp.dense_h_to_4h.bias": "pytorch_model-00001-of-00008.bin",
19
+ "transformer.layers.0.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00008.bin",
20
+ "transformer.layers.0.post_attention_layernorm.bias": "pytorch_model-00001-of-00008.bin",
21
+ "transformer.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00008.bin",
22
+ "transformer.layers.1.attention.dense.bias": "pytorch_model-00001-of-00008.bin",
23
+ "transformer.layers.1.attention.dense.weight": "pytorch_model-00001-of-00008.bin",
24
+ "transformer.layers.1.attention.query_key_value.bias": "pytorch_model-00001-of-00008.bin",
25
+ "transformer.layers.1.attention.query_key_value.weight": "pytorch_model-00001-of-00008.bin",
26
+ "transformer.layers.1.attention.rotary_emb.inv_freq": "pytorch_model-00001-of-00008.bin",
27
+ "transformer.layers.1.input_layernorm.bias": "pytorch_model-00001-of-00008.bin",
28
+ "transformer.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00008.bin",
29
+ "transformer.layers.1.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
30
+ "transformer.layers.1.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
31
+ "transformer.layers.1.mlp.dense_h_to_4h.bias": "pytorch_model-00001-of-00008.bin",
32
+ "transformer.layers.1.mlp.dense_h_to_4h.weight": "pytorch_model-00001-of-00008.bin",
33
+ "transformer.layers.1.post_attention_layernorm.bias": "pytorch_model-00001-of-00008.bin",
34
+ "transformer.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00008.bin",
35
+ "transformer.layers.10.attention.dense.bias": "pytorch_model-00003-of-00008.bin",
36
+ "transformer.layers.10.attention.dense.weight": "pytorch_model-00003-of-00008.bin",
37
+ "transformer.layers.10.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
38
+ "transformer.layers.10.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
39
+ "transformer.layers.10.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
40
+ "transformer.layers.10.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
41
+ "transformer.layers.10.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
42
+ "transformer.layers.10.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
43
+ "transformer.layers.10.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
44
+ "transformer.layers.10.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
45
+ "transformer.layers.10.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
46
+ "transformer.layers.10.post_attention_layernorm.bias": "pytorch_model-00003-of-00008.bin",
47
+ "transformer.layers.10.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
48
+ "transformer.layers.11.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
49
+ "transformer.layers.11.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
50
+ "transformer.layers.11.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
51
+ "transformer.layers.11.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
52
+ "transformer.layers.11.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
53
+ "transformer.layers.11.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
54
+ "transformer.layers.11.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
55
+ "transformer.layers.11.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
56
+ "transformer.layers.11.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
57
+ "transformer.layers.11.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
58
+ "transformer.layers.11.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
59
+ "transformer.layers.11.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
60
+ "transformer.layers.11.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
61
+ "transformer.layers.12.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
62
+ "transformer.layers.12.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
63
+ "transformer.layers.12.attention.query_key_value.bias": "pytorch_model-00004-of-00008.bin",
64
+ "transformer.layers.12.attention.query_key_value.weight": "pytorch_model-00004-of-00008.bin",
65
+ "transformer.layers.12.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
66
+ "transformer.layers.12.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
67
+ "transformer.layers.12.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
68
+ "transformer.layers.12.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
69
+ "transformer.layers.12.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
70
+ "transformer.layers.12.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
71
+ "transformer.layers.12.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
72
+ "transformer.layers.12.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
73
+ "transformer.layers.12.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
74
+ "transformer.layers.13.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
75
+ "transformer.layers.13.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
76
+ "transformer.layers.13.attention.query_key_value.bias": "pytorch_model-00004-of-00008.bin",
77
+ "transformer.layers.13.attention.query_key_value.weight": "pytorch_model-00004-of-00008.bin",
78
+ "transformer.layers.13.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
79
+ "transformer.layers.13.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
80
+ "transformer.layers.13.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
81
+ "transformer.layers.13.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
82
+ "transformer.layers.13.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
83
+ "transformer.layers.13.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
84
+ "transformer.layers.13.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
85
+ "transformer.layers.13.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
86
+ "transformer.layers.13.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
87
+ "transformer.layers.14.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
88
+ "transformer.layers.14.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
89
+ "transformer.layers.14.attention.query_key_value.bias": "pytorch_model-00004-of-00008.bin",
90
+ "transformer.layers.14.attention.query_key_value.weight": "pytorch_model-00004-of-00008.bin",
91
+ "transformer.layers.14.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
92
+ "transformer.layers.14.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
93
+ "transformer.layers.14.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
94
+ "transformer.layers.14.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
95
+ "transformer.layers.14.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
96
+ "transformer.layers.14.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
97
+ "transformer.layers.14.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
98
+ "transformer.layers.14.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
99
+ "transformer.layers.14.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
100
+ "transformer.layers.15.attention.dense.bias": "pytorch_model-00004-of-00008.bin",
101
+ "transformer.layers.15.attention.dense.weight": "pytorch_model-00004-of-00008.bin",
102
+ "transformer.layers.15.attention.query_key_value.bias": "pytorch_model-00004-of-00008.bin",
103
+ "transformer.layers.15.attention.query_key_value.weight": "pytorch_model-00004-of-00008.bin",
104
+ "transformer.layers.15.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
105
+ "transformer.layers.15.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
106
+ "transformer.layers.15.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
107
+ "transformer.layers.15.mlp.dense_4h_to_h.bias": "pytorch_model-00004-of-00008.bin",
108
+ "transformer.layers.15.mlp.dense_4h_to_h.weight": "pytorch_model-00004-of-00008.bin",
109
+ "transformer.layers.15.mlp.dense_h_to_4h.bias": "pytorch_model-00004-of-00008.bin",
110
+ "transformer.layers.15.mlp.dense_h_to_4h.weight": "pytorch_model-00004-of-00008.bin",
111
+ "transformer.layers.15.post_attention_layernorm.bias": "pytorch_model-00004-of-00008.bin",
112
+ "transformer.layers.15.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
113
+ "transformer.layers.16.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
114
+ "transformer.layers.16.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
115
+ "transformer.layers.16.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
116
+ "transformer.layers.16.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
117
+ "transformer.layers.16.attention.rotary_emb.inv_freq": "pytorch_model-00004-of-00008.bin",
118
+ "transformer.layers.16.input_layernorm.bias": "pytorch_model-00004-of-00008.bin",
119
+ "transformer.layers.16.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
120
+ "transformer.layers.16.mlp.dense_4h_to_h.bias": "pytorch_model-00005-of-00008.bin",
121
+ "transformer.layers.16.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00008.bin",
122
+ "transformer.layers.16.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
123
+ "transformer.layers.16.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
124
+ "transformer.layers.16.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
125
+ "transformer.layers.16.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
126
+ "transformer.layers.17.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
127
+ "transformer.layers.17.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
128
+ "transformer.layers.17.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
129
+ "transformer.layers.17.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
130
+ "transformer.layers.17.attention.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
131
+ "transformer.layers.17.input_layernorm.bias": "pytorch_model-00005-of-00008.bin",
132
+ "transformer.layers.17.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
133
+ "transformer.layers.17.mlp.dense_4h_to_h.bias": "pytorch_model-00005-of-00008.bin",
134
+ "transformer.layers.17.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00008.bin",
135
+ "transformer.layers.17.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
136
+ "transformer.layers.17.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
137
+ "transformer.layers.17.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
138
+ "transformer.layers.17.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
139
+ "transformer.layers.18.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
140
+ "transformer.layers.18.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
141
+ "transformer.layers.18.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
142
+ "transformer.layers.18.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
143
+ "transformer.layers.18.attention.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
144
+ "transformer.layers.18.input_layernorm.bias": "pytorch_model-00005-of-00008.bin",
145
+ "transformer.layers.18.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
146
+ "transformer.layers.18.mlp.dense_4h_to_h.bias": "pytorch_model-00005-of-00008.bin",
147
+ "transformer.layers.18.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00008.bin",
148
+ "transformer.layers.18.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
149
+ "transformer.layers.18.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
150
+ "transformer.layers.18.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
151
+ "transformer.layers.18.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
152
+ "transformer.layers.19.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
153
+ "transformer.layers.19.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
154
+ "transformer.layers.19.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
155
+ "transformer.layers.19.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
156
+ "transformer.layers.19.attention.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
157
+ "transformer.layers.19.input_layernorm.bias": "pytorch_model-00005-of-00008.bin",
158
+ "transformer.layers.19.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
159
+ "transformer.layers.19.mlp.dense_4h_to_h.bias": "pytorch_model-00005-of-00008.bin",
160
+ "transformer.layers.19.mlp.dense_4h_to_h.weight": "pytorch_model-00005-of-00008.bin",
161
+ "transformer.layers.19.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
162
+ "transformer.layers.19.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
163
+ "transformer.layers.19.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
164
+ "transformer.layers.19.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
165
+ "transformer.layers.2.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
166
+ "transformer.layers.2.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
167
+ "transformer.layers.2.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
168
+ "transformer.layers.2.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
169
+ "transformer.layers.2.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
170
+ "transformer.layers.2.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
171
+ "transformer.layers.2.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
172
+ "transformer.layers.2.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
173
+ "transformer.layers.2.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
174
+ "transformer.layers.2.mlp.dense_h_to_4h.bias": "pytorch_model-00002-of-00008.bin",
175
+ "transformer.layers.2.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00008.bin",
176
+ "transformer.layers.2.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
177
+ "transformer.layers.2.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
178
+ "transformer.layers.20.attention.dense.bias": "pytorch_model-00005-of-00008.bin",
179
+ "transformer.layers.20.attention.dense.weight": "pytorch_model-00005-of-00008.bin",
180
+ "transformer.layers.20.attention.query_key_value.bias": "pytorch_model-00005-of-00008.bin",
181
+ "transformer.layers.20.attention.query_key_value.weight": "pytorch_model-00005-of-00008.bin",
182
+ "transformer.layers.20.attention.rotary_emb.inv_freq": "pytorch_model-00005-of-00008.bin",
183
+ "transformer.layers.20.input_layernorm.bias": "pytorch_model-00005-of-00008.bin",
184
+ "transformer.layers.20.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
185
+ "transformer.layers.20.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
186
+ "transformer.layers.20.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
187
+ "transformer.layers.20.mlp.dense_h_to_4h.bias": "pytorch_model-00005-of-00008.bin",
188
+ "transformer.layers.20.mlp.dense_h_to_4h.weight": "pytorch_model-00005-of-00008.bin",
189
+ "transformer.layers.20.post_attention_layernorm.bias": "pytorch_model-00005-of-00008.bin",
190
+ "transformer.layers.20.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
191
+ "transformer.layers.21.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
192
+ "transformer.layers.21.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
193
+ "transformer.layers.21.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
194
+ "transformer.layers.21.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
195
+ "transformer.layers.21.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
196
+ "transformer.layers.21.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
197
+ "transformer.layers.21.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
198
+ "transformer.layers.21.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
199
+ "transformer.layers.21.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
200
+ "transformer.layers.21.mlp.dense_h_to_4h.bias": "pytorch_model-00006-of-00008.bin",
201
+ "transformer.layers.21.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00008.bin",
202
+ "transformer.layers.21.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
203
+ "transformer.layers.21.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
204
+ "transformer.layers.22.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
205
+ "transformer.layers.22.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
206
+ "transformer.layers.22.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
207
+ "transformer.layers.22.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
208
+ "transformer.layers.22.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
209
+ "transformer.layers.22.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
210
+ "transformer.layers.22.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
211
+ "transformer.layers.22.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
212
+ "transformer.layers.22.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
213
+ "transformer.layers.22.mlp.dense_h_to_4h.bias": "pytorch_model-00006-of-00008.bin",
214
+ "transformer.layers.22.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00008.bin",
215
+ "transformer.layers.22.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
216
+ "transformer.layers.22.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
217
+ "transformer.layers.23.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
218
+ "transformer.layers.23.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
219
+ "transformer.layers.23.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
220
+ "transformer.layers.23.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
221
+ "transformer.layers.23.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
222
+ "transformer.layers.23.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
223
+ "transformer.layers.23.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
224
+ "transformer.layers.23.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
225
+ "transformer.layers.23.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
226
+ "transformer.layers.23.mlp.dense_h_to_4h.bias": "pytorch_model-00006-of-00008.bin",
227
+ "transformer.layers.23.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00008.bin",
228
+ "transformer.layers.23.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
229
+ "transformer.layers.23.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
230
+ "transformer.layers.24.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
231
+ "transformer.layers.24.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
232
+ "transformer.layers.24.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
233
+ "transformer.layers.24.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
234
+ "transformer.layers.24.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
235
+ "transformer.layers.24.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
236
+ "transformer.layers.24.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
237
+ "transformer.layers.24.mlp.dense_4h_to_h.bias": "pytorch_model-00006-of-00008.bin",
238
+ "transformer.layers.24.mlp.dense_4h_to_h.weight": "pytorch_model-00006-of-00008.bin",
239
+ "transformer.layers.24.mlp.dense_h_to_4h.bias": "pytorch_model-00006-of-00008.bin",
240
+ "transformer.layers.24.mlp.dense_h_to_4h.weight": "pytorch_model-00006-of-00008.bin",
241
+ "transformer.layers.24.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
242
+ "transformer.layers.24.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
243
+ "transformer.layers.25.attention.dense.bias": "pytorch_model-00006-of-00008.bin",
244
+ "transformer.layers.25.attention.dense.weight": "pytorch_model-00006-of-00008.bin",
245
+ "transformer.layers.25.attention.query_key_value.bias": "pytorch_model-00006-of-00008.bin",
246
+ "transformer.layers.25.attention.query_key_value.weight": "pytorch_model-00006-of-00008.bin",
247
+ "transformer.layers.25.attention.rotary_emb.inv_freq": "pytorch_model-00006-of-00008.bin",
248
+ "transformer.layers.25.input_layernorm.bias": "pytorch_model-00006-of-00008.bin",
249
+ "transformer.layers.25.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
250
+ "transformer.layers.25.mlp.dense_4h_to_h.bias": "pytorch_model-00007-of-00008.bin",
251
+ "transformer.layers.25.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00008.bin",
252
+ "transformer.layers.25.mlp.dense_h_to_4h.bias": "pytorch_model-00007-of-00008.bin",
253
+ "transformer.layers.25.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00008.bin",
254
+ "transformer.layers.25.post_attention_layernorm.bias": "pytorch_model-00006-of-00008.bin",
255
+ "transformer.layers.25.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
256
+ "transformer.layers.26.attention.dense.bias": "pytorch_model-00007-of-00008.bin",
257
+ "transformer.layers.26.attention.dense.weight": "pytorch_model-00007-of-00008.bin",
258
+ "transformer.layers.26.attention.query_key_value.bias": "pytorch_model-00007-of-00008.bin",
259
+ "transformer.layers.26.attention.query_key_value.weight": "pytorch_model-00007-of-00008.bin",
260
+ "transformer.layers.26.attention.rotary_emb.inv_freq": "pytorch_model-00007-of-00008.bin",
261
+ "transformer.layers.26.input_layernorm.bias": "pytorch_model-00007-of-00008.bin",
262
+ "transformer.layers.26.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
263
+ "transformer.layers.26.mlp.dense_4h_to_h.bias": "pytorch_model-00007-of-00008.bin",
264
+ "transformer.layers.26.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00008.bin",
265
+ "transformer.layers.26.mlp.dense_h_to_4h.bias": "pytorch_model-00007-of-00008.bin",
266
+ "transformer.layers.26.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00008.bin",
267
+ "transformer.layers.26.post_attention_layernorm.bias": "pytorch_model-00007-of-00008.bin",
268
+ "transformer.layers.26.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
269
+ "transformer.layers.27.attention.dense.bias": "pytorch_model-00007-of-00008.bin",
270
+ "transformer.layers.27.attention.dense.weight": "pytorch_model-00007-of-00008.bin",
271
+ "transformer.layers.27.attention.query_key_value.bias": "pytorch_model-00007-of-00008.bin",
272
+ "transformer.layers.27.attention.query_key_value.weight": "pytorch_model-00007-of-00008.bin",
273
+ "transformer.layers.27.attention.rotary_emb.inv_freq": "pytorch_model-00007-of-00008.bin",
274
+ "transformer.layers.27.input_layernorm.bias": "pytorch_model-00007-of-00008.bin",
275
+ "transformer.layers.27.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
276
+ "transformer.layers.27.mlp.dense_4h_to_h.bias": "pytorch_model-00007-of-00008.bin",
277
+ "transformer.layers.27.mlp.dense_4h_to_h.weight": "pytorch_model-00007-of-00008.bin",
278
+ "transformer.layers.27.mlp.dense_h_to_4h.bias": "pytorch_model-00007-of-00008.bin",
279
+ "transformer.layers.27.mlp.dense_h_to_4h.weight": "pytorch_model-00007-of-00008.bin",
280
+ "transformer.layers.27.post_attention_layernorm.bias": "pytorch_model-00007-of-00008.bin",
281
+ "transformer.layers.27.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
282
+ "transformer.layers.3.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
283
+ "transformer.layers.3.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
284
+ "transformer.layers.3.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
285
+ "transformer.layers.3.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
286
+ "transformer.layers.3.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
287
+ "transformer.layers.3.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
288
+ "transformer.layers.3.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
289
+ "transformer.layers.3.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
290
+ "transformer.layers.3.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
291
+ "transformer.layers.3.mlp.dense_h_to_4h.bias": "pytorch_model-00002-of-00008.bin",
292
+ "transformer.layers.3.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00008.bin",
293
+ "transformer.layers.3.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
294
+ "transformer.layers.3.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
295
+ "transformer.layers.4.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
296
+ "transformer.layers.4.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
297
+ "transformer.layers.4.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
298
+ "transformer.layers.4.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
299
+ "transformer.layers.4.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
300
+ "transformer.layers.4.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
301
+ "transformer.layers.4.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
302
+ "transformer.layers.4.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
303
+ "transformer.layers.4.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
304
+ "transformer.layers.4.mlp.dense_h_to_4h.bias": "pytorch_model-00002-of-00008.bin",
305
+ "transformer.layers.4.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00008.bin",
306
+ "transformer.layers.4.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
307
+ "transformer.layers.4.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
308
+ "transformer.layers.5.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
309
+ "transformer.layers.5.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
310
+ "transformer.layers.5.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
311
+ "transformer.layers.5.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
312
+ "transformer.layers.5.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
313
+ "transformer.layers.5.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
314
+ "transformer.layers.5.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
315
+ "transformer.layers.5.mlp.dense_4h_to_h.bias": "pytorch_model-00002-of-00008.bin",
316
+ "transformer.layers.5.mlp.dense_4h_to_h.weight": "pytorch_model-00002-of-00008.bin",
317
+ "transformer.layers.5.mlp.dense_h_to_4h.bias": "pytorch_model-00002-of-00008.bin",
318
+ "transformer.layers.5.mlp.dense_h_to_4h.weight": "pytorch_model-00002-of-00008.bin",
319
+ "transformer.layers.5.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
320
+ "transformer.layers.5.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
321
+ "transformer.layers.6.attention.dense.bias": "pytorch_model-00002-of-00008.bin",
322
+ "transformer.layers.6.attention.dense.weight": "pytorch_model-00002-of-00008.bin",
323
+ "transformer.layers.6.attention.query_key_value.bias": "pytorch_model-00002-of-00008.bin",
324
+ "transformer.layers.6.attention.query_key_value.weight": "pytorch_model-00002-of-00008.bin",
325
+ "transformer.layers.6.attention.rotary_emb.inv_freq": "pytorch_model-00002-of-00008.bin",
326
+ "transformer.layers.6.input_layernorm.bias": "pytorch_model-00002-of-00008.bin",
327
+ "transformer.layers.6.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
328
+ "transformer.layers.6.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
329
+ "transformer.layers.6.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
330
+ "transformer.layers.6.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
331
+ "transformer.layers.6.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
332
+ "transformer.layers.6.post_attention_layernorm.bias": "pytorch_model-00002-of-00008.bin",
333
+ "transformer.layers.6.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
334
+ "transformer.layers.7.attention.dense.bias": "pytorch_model-00003-of-00008.bin",
335
+ "transformer.layers.7.attention.dense.weight": "pytorch_model-00003-of-00008.bin",
336
+ "transformer.layers.7.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
337
+ "transformer.layers.7.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
338
+ "transformer.layers.7.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
339
+ "transformer.layers.7.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
340
+ "transformer.layers.7.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
341
+ "transformer.layers.7.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
342
+ "transformer.layers.7.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
343
+ "transformer.layers.7.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
344
+ "transformer.layers.7.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
345
+ "transformer.layers.7.post_attention_layernorm.bias": "pytorch_model-00003-of-00008.bin",
346
+ "transformer.layers.7.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
347
+ "transformer.layers.8.attention.dense.bias": "pytorch_model-00003-of-00008.bin",
348
+ "transformer.layers.8.attention.dense.weight": "pytorch_model-00003-of-00008.bin",
349
+ "transformer.layers.8.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
350
+ "transformer.layers.8.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
351
+ "transformer.layers.8.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
352
+ "transformer.layers.8.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
353
+ "transformer.layers.8.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
354
+ "transformer.layers.8.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
355
+ "transformer.layers.8.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
356
+ "transformer.layers.8.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
357
+ "transformer.layers.8.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
358
+ "transformer.layers.8.post_attention_layernorm.bias": "pytorch_model-00003-of-00008.bin",
359
+ "transformer.layers.8.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
360
+ "transformer.layers.9.attention.dense.bias": "pytorch_model-00003-of-00008.bin",
361
+ "transformer.layers.9.attention.dense.weight": "pytorch_model-00003-of-00008.bin",
362
+ "transformer.layers.9.attention.query_key_value.bias": "pytorch_model-00003-of-00008.bin",
363
+ "transformer.layers.9.attention.query_key_value.weight": "pytorch_model-00003-of-00008.bin",
364
+ "transformer.layers.9.attention.rotary_emb.inv_freq": "pytorch_model-00003-of-00008.bin",
365
+ "transformer.layers.9.input_layernorm.bias": "pytorch_model-00003-of-00008.bin",
366
+ "transformer.layers.9.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
367
+ "transformer.layers.9.mlp.dense_4h_to_h.bias": "pytorch_model-00003-of-00008.bin",
368
+ "transformer.layers.9.mlp.dense_4h_to_h.weight": "pytorch_model-00003-of-00008.bin",
369
+ "transformer.layers.9.mlp.dense_h_to_4h.bias": "pytorch_model-00003-of-00008.bin",
370
+ "transformer.layers.9.mlp.dense_h_to_4h.weight": "pytorch_model-00003-of-00008.bin",
371
+ "transformer.layers.9.post_attention_layernorm.bias": "pytorch_model-00003-of-00008.bin",
372
+ "transformer.layers.9.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
373
+ "transformer.word_embeddings.weight": "pytorch_model-00001-of-00008.bin"
374
+ }
375
+ }
moe/quantization.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn import Linear
2
+ from torch.nn.parameter import Parameter
3
+
4
+ import bz2
5
+ import torch
6
+ import base64
7
+ import ctypes
8
+
9
+ from typing import List
10
+ from cpm_kernels.kernels.base import LazyKernelCModule, KernelFunction, round_up
11
+
12
+
13
+ class W8A16Linear(torch.autograd.Function):
14
+ @staticmethod
15
+ def forward(ctx, inp: torch.Tensor, quant_w: torch.Tensor, scale_w: torch.Tensor, weight_bit_width):
16
+ ctx.inp_shape = inp.size()
17
+ ctx.weight_shape = quant_w.size()
18
+ ctx.weight_bit_width = weight_bit_width
19
+ out_features = quant_w.size(0)
20
+ inp = inp.contiguous().view(-1, inp.size(-1))
21
+ weight = extract_weight_to_half(quant_w, scale_w, weight_bit_width)
22
+ output = inp.mm(weight.t())
23
+ ctx.save_for_backward(inp, quant_w, scale_w)
24
+ return output.view(*(ctx.inp_shape[:-1] + (out_features,)))
25
+
26
+ @staticmethod
27
+ def backward(ctx, grad_output: torch.Tensor):
28
+ inp, quant_w, scale_w = ctx.saved_tensors
29
+ weight = extract_weight_to_half(quant_w, scale_w, ctx.weight_bit_width)
30
+ grad_output = grad_output.contiguous().view(-1, weight.size(0))
31
+ grad_input = grad_output.mm(weight)
32
+ grad_weight = grad_output.t().mm(inp)
33
+ return grad_input.view(ctx.inp_shape), grad_weight.view(ctx.weight_shape), None
34
+
35
+
36
+ class Kernel:
37
+ def __init__(self, code: bytes, function_names: List[str]):
38
+ self.code = code
39
+ self._function_names = function_names
40
+ self._cmodule = LazyKernelCModule(self.code)
41
+
42
+ for name in self._function_names:
43
+ setattr(self, name, KernelFunction(self._cmodule, name))
44
+
45
+
46
+ quantization_code = "$QlpoOTFBWSZTWU9yuJUAQHN//////////f/n/8/n///n//bt4dTidcVx8X3V9FV/92/v4B7/AD5FBQFAAAChSgKpFCFAFVSigUAAAEKhSgUUqgFBKigqVREQAABQBQIANDTTIGI00BkZBkNGE0A0BkBkGQGRkaNAaAGQNBoGgDIAAYIGTI0DQAQAaGmmQMRpoDIyDIaMJoBoDIDIMgMjI0aA0AMgaDQNAGQAAwQMmRoGgAgA0NNMgYjTQGRkGQ0YTQDQGQGQZAZGRo0BoAZA0GgaAMgABggZMjQNABABoaaZAxGmgMjIMhowmgGgMgMgyAyMjRoDQAyBoNA0AZAADBAyZGgaAAmqU1NEgJqnptU/Sn4jRR6J6epk2pqb1Q/SgAPUGgyNNGjQ2SBpoAZAAGg0NB6mgDIAAAAA2oaApSREBNAARhGiYEaEwU8pvImlP0k2aam1GaGqbFNM1MHpTwmkepmyU9R6nqPKekHqNNPUxNGhp6n6p6QaZ6o9TG1GMqcoV9ly6nRanHlq6zPNbnGZNi6HSug+2nPiZ13XcnFYZW+45W11CumhzYhchOJ2GLLV1OBjBjGf4TptOddTSOcVxhqYZMYwZXZZY00zI1paX5X9J+b+f4e+x43RXSxXPOdquiGpduatGyXneN696M9t4HU2eR5XX/kPhP261NTx3JO1Ow7LyuDmeo9a7d351T1ZxnvnrvYnrXv/hXxPCeuYx2XsNmO003eg9J3Z6U7b23meJ4ri01OdzTk9BNO96brz+qT5nuvvH3ds/G+m/JcG/F2XYuhXlvO+jP7U3XgrzPN/lr8Sf1n6j4j7jZs+s/T0tNaNNYzTs12rxjwztHlnire3Nzc3N1wuBwOBwXBvZfoHpD7rFmR99V5vj3aXza3xdBbXMalubTg/jIv5dfAi54Pdc75j4z412n3Npj3Ld/ENm7a3b/Cod6h/ret1/5vn/C+l+gdslMvgPSLJ8d8q+U66fevYn/tW1chleEtNTGlcHCbLRlq0tHzF5tsbbZZfHjjLgZu42XCuC3NrdjTasZGNzgxPIrGqp7r3p7L2p5XjnpPSmTd5XtzqnB6U87zzg1Ol0zd0zsLszxR6lkxp35u6/teL0L0W922cR7Lu1lpL9CsHirzuM2T+BgsyViT6LHcm0/Vr6U/7LGGyJeqTEjt0PHWhF5mCT7R9mtlDwriYv0Tyr/OxYt6qp5r0mPVT0608TqnqMZaarU2nFwrTzzlrs1ed7z1ux60wyr4ydCaTi3enW8x68x0zU7tXSlcmPSW1mGpWJMg4zmPC2lK96tp0OE80y4MfEvnZj8zGluR6b22ki1Ou9V2nCd9xovcPvcYMZYy0lvN60ScZ45vN6yeCeeXFb1lVjnnCar5fwXwE2bzJ4HI1XVPXfXZMm44GUsMpYsmLB65TuVdm0cl0b+i/wGNN66XjeV7zuPpHcnK/juhhjdfId5jMdE5nN0dGmmm2zZs2cexD5n9p/dY352XsvXHaZNWWsmmS1atjR452nYudzvqv2HMRyvNNnlMcDl3R2+yx2uVrBubTW9icHDVtbNXlZm7jma1rM4VurZZd2y6nUau7ZXZ7bVU+mnoOVxZGMrVmvX60605JwmzGZhhhjTWtaaaMaaGTGmNMZasY0iX8VMUl8eepaIrzGSpemWOQyZORk2bNpjUybMmxqYmknCGCFynutfksaZpjTNMaaatM0xsxcGR0sociNqxNSmhhR1ZJPbsn8qyF0t2qH6iYBclclalbtTTcHTDsPaX6rlnElph2Jyumumtynv2Kk8GI7rsvXbIcJgHJOSaSXnnGaI3m87RtVXJOZ/YtgdTE6Wpha6ZlE8ayXkef1fh602r2WwvfMXtMdLlkfnLFdYYwYso+bWqm7yJqHXZGw2nrS5ZanSYnWlxBxMF1V940K2wdrI7R6OYf7DGGamMmTSbRhlS45xmVOumF1EyPCmHrrN8wwZOOrdNtLeMtzFzDlWnfTBxMk2NaXIZHBYxYLD4w8yju0ao65Vz1OIXoS9dLanwCe1PWrYuWMqf1if1z2k2yYfKJ741PDgno1ZQ8DRqvUny3mNoWTzGO6m1DkrJI8JiR5cSd+vZdGOO8nrMoc5+NDUFsMSXaZJeNlMmGLtJsovOsUp7I9S5VojKxF6bTVEelXqlfJobQr3LozSh2Jk7VcrVMfhXqszGWMzNqGhqZY0OadxkyyMssKugZR0KNFXBHlqwmJgTE/BNVMk6ItJXZMR0H47GpXv/DMOvNkmVuaV1PRfEdxuqc7Hcd+ZV/zTLaRxWk0nl9CdCeM6mn5rstHIBcpiuwmUZXeq81DacHI2rmrZ5SuE5mOZd6LQrZg9mx32TprA8BMo5jKN6yLTCi3WzQaZSuhzTtM1fUTGVpG8Tw+KXI0tjEpiWxtLYynOlktSbVlaI5kxP8TDH8kx50xoxi5KcA4pcja8KWLRlO/Ks6q06ergnvm1ca3Tq8Uw7LTUsmWyctXPWmpitl/uvGcWTGXGuAXDfhqazGmjkxcJW5hMMMMpYsXl2TZYtVOddG3XCarUt6Ptq9CZXSNzyuRzqRZOjsxdBbFVz6OA5HI43r1jityVlVpVkxmOsyaYWE1NTGq1sOVh36mHMcxtSvcy70edG0ZGR3I1Go1GRlV7mWWo1G0ZGRqlvH40l7o4m5xMWLLLYyNjnqc8556mdPqLJ31n/1nWOncxzG1tizrHs/Z+d2vP/B/l8wdJ6rHUn2nbbDq4p6htFtYzMMMTaZis1K5GKzGNmxhmUx2DDlZ/qNnIx41xnaMfCZWYaZWtNLTNW8ND4Fw1MyZOCdM428suKG1ehW8TesOydg7J+YYcD4cYR+8dFK6M4E3HM9ZfRNNL+Sn6rsl4DsrDl2HpPCnfxjGXtbZtYys1ttlyJ4T+BvexjGWRjMszK4Jpc77D3GyuVD7q0+G8m9G+2+rGm7cOR2y7FdtY2XUYx/oNlfRYxhMYyYZkyyg55enna9Kt/FFi6GMMwYwdwxWgxGMLKYmUyGExTKMZkMFhkymKuh0NOBNnBu+23LdwDoZYYzGGMxtORaTU1pjTGWTTGGtMrNWUsyyTTLLG1qy2ZjbK2DBllWqxMtBMaYZQmcE7zvvRcTkclUwdkxTaSdyySt/7fpL+T1v516Ji97fwr5JbLu305zMn5+GMTTZ9F+y7ExwmGVfG44yxn3dLv6l5i+Wth1jCrDq21nW9LqvvDzz3Vf3LLH/O/32TJ/erx3bXftO4eF+G956D952K/An4NfvOpjFjExjevP/UmE0fIoZXx6/w6lX/no3D0bLt+ixjieBM6ksRd0yB4Lt2SwYNE+gd1detlZWUnpiZfGfFaK+4PyCa/v18V8X75pe9fLXzp7l3VjF76vWZmHwGz1IZNWT7b8yddJ4q5kyrVdfru6atWc7bVYztL9Jf4GXvT+Y8m9/YsXP6H018a8D4XVOqvfzqeR+6yZOD8dPv0+U7/q5Pl+2dNb0MjzGVH5p6MNQ7cOWvw62U9aHE8DprDek+McLyvDz+te+9Zhq5+YTruufMcWMabqysTmZVWjKPfnK0wyVcrsuhjZRdLkHNvD72b9abriOSGIxiLixMOoalNPXzy+wT/tf+U6HHONfsz+xe8ufHBdQWWGWLA9if0rsnmrxK5LvRZQeWsTCsrmOYy8VteVfuRfcVTtDLItLIsMYxZLdU/DbtSemxF6Z6Zo5WBXE4tFdCyVMMXMTEMZXVlS6Xec2T4e0tHsRcEuWshcJ2YsNF5rUx1E8ifCq6Z+ZP7qdCeu/aTwFd53l16/o0NOw6O3dLavP4Hbi4RdmuDk6DoYaninC0+o4uZjbJ7Rxeu0/FbuFg+q7DVS6fQe0rZ6NDGUNNU6DEqOaLTicKnYZMnBWruljQxoaS3dZhocDge0bSTyOvdAbG5hxe2xji7E/L55xX13wWNDi6HCekcFxfCPGxY0MXC+s7afWaMdDyjyr+o8Rudm/NabOZvdl274zH4f5XK9z6On1Pe/K5TdPAslg77BjuO6Y3eO7GqvOPG/stknp1leyvLL0Z7bl9I4noMvLkzytLhWYzrOZzLXCORe028rORzOg4N/L0HlMOQ3Pgmnbb6KczlabORpu980q37TBqRu0/p3PO6234Bl03Ynuz+9W7gnsEcmvYaYY3aMYY0wx3pYd+ujsXauWdaY5Xkbtl23fPzFHiDB/QMo0yFjBllYxTQYYyxkrwn7JufwJ/PfgJ+C83X69ni6zvXcnyXabv0ncbLwsceS+RNlyN2mnneJtX0ngYO0+e+0+UnA+Wch3ji8hj5an4h+i6XBySU4n+R0roVcbw5yvHrmr4Yw8Y7x6c+9POPYHI5HI5HI5HI5HGXGww4nE4nrVyOR8XeqPEO7PLOiukYa3Novk5hV4cdtYZLI93e+uxff2jRo0aNGjRo0aNG1bVtW1dy3m83m8+tQ5ZzHw3nObwOu8La9Rc1dtkdS8A3eTk823tnktXWlxN6Oixe06zrN70Isd9jiOgZFq9yfkPqP/SLhN2Myl8jDM43bl1nbcb4cO57jlh8Jow6pzXZdL4dyODTuuhu77FyO27DdwdRxmvO+O+3N2+BdqyTwLHVczDVY4UPE4O66/ZO2cx1LFzVdSXtF7G4HMbrauOHRw6c8FdZ5m9fHZHYZXfTlZquyynSyTTKke6vcffSD9pzPA/G7n7jxPmuhc1DHMynPMrGL6AdewYmwu5ko+UUyTwrMv27rPH1v1nGqd87+p6N6LU8k3NEng53xXyHS97+44OSg/sy/hn+Se6yfYNjW0/uTgP+PvWYzLMmjhcLB/gGpri6H83/84eUXWT6T9Hsv7785z/7z4icpW+zfXypuR7rx/gMdZb1/wC678pcs8/2a3mDitGHxl9mfPlll5MafWWqxk/eYuTDgcNMzDGWLWvsuglNxs53GtN6uWpktlW1tZZYcuinMMWmnNnJydze3b2Y1McBxrBkXw799izLMZZYyy0TkbsGM4p03S2uVu5s/XXUdSdec6smVxZYYGpVmT8A+8ajuEyV5FatkvVru2x6uxGXXbH4A+jvgP4GMYy3iPLXzq/6z65+E005ey+cwMZD3fZcqc6xpjTFjQ0P3U+e++cPYmTIwj0nrK5NPTfl3WvpfLtXDcb2HQMudYOxFXQBor4L4T6vrOauFctYXJQ++NUWmJe5bmx1jDiZS1dTqWxo4GR8jm3fttpmPHppk9PEyv4/y8/sO07XacOmcqc0x2Vi9BvNJvN5oW8x4mOsydpidRxMYJPx06m1bqPzq9KtK8sxXNXFodD/+MYYaJTLwOhc9brCsV18oOR1i4tXChyTkq4lf4y1Ke+9axjDHqs1mfBbMXuP4Hzi+X7t8vzv7bHerrUPgPCxhjre4fXdfLNtNM+Jd+Zdh8xd8wP87uNPoPgv4W7/5P2BuxfsMabNnMnza+54Pdi5U671GPZY8CehX8Voeoo7FHpkeEc6715FwHZrIrUrHaviPUbPZHND+IhczrP6FcYvhOZ0Di/ETt0OI+YwNWR9r7tpf6WDeZKZDB1+z2IthOl1mPyb5FluvEx9h9d0NnM0Y1XPFkWIsk1WotJ0PBMmkvjvQTd0e71tfeV+8r8lQ/tpzpsmxJ+InrI/dj2UajUajVTUajatRqNRtGo1Go1Go4wjeMpZFMVV9CHbofPraLsJ3JpWV2XOoanCuFky4y3PPNxucK2uKC1Lbdb1eo+m5XomN6HfeZsabHLHRX/K+offtNGGmHWctcVcG44MdSqsOLY9VzX+Zxfxn2HPdWTpzWvkrtJ8M5zorrKcquRytJ5N5DZmcaW02l76nWO+BqPXm1A2Ry/0q71dH/mqrqeFjkYxjEXtsX8qubTk67rGycyqsdm4tZx5D6D5hhi0waaWmiaMP81Yjii5qxPlPuU/GfTL1Y5E6Jyfiq63qTa39A4J0sOGDgO9WF9bOXl0XfPRbsY2bPNKPy1YrFYrFYmRhhlTIyMjJWJYZHXuCXI8OoXsvfljGLFicNifpp2XunoPiG1wtx3p1Tah+/DD66OnVtVXP9rKbVxOnL0tR/rHtqB5UDErUVcl11D4qqvjpOcxX7armUNJB3LpW6bxVvD08e8h3odKKvyCFZBdSh2FVcST9xV3n3T8t1j7Kr9qgrqXg+13Pt5U7JCvFXVIV1YG5lRhkVYZJYYDDD4KOIMoHCp26WS8GB7uBh2zIdgq/PKyInjV2STShuoapUdCpX1yTwqq/z1VvET7Kh5nVPkO8YyxjLt2MaaMmWTLQvx3qnzltnXW0p2jxgbEtSny/Osv8Y9pLMXYoHVPAhkVdWVeODhR6q9/Sxe2liwwZWMVvFXfRkeIDxAePUPIrdJ4ey6yquzH+PD/bUOWAu05qVHtFd8rrKHSoeNIOUqrYr3FXyToqfYJgwmJdKpXXOwYYegNNGMzfZPp/t3t/DVs4zjNTN61rRqaWaa4NYbRjTa0tWwy2Y2tGN8ZO8ofNKq4j9SL7I+cSm4/6ovLV5HNXLI0jJidwrtk6ynCaP6Z++GjRlWS3tLeW129Mi9evxU9mtz6s5J3Z7M2ngTgnKvmpomxpaLCzPfmx0JWE+m3NLDDGOX47RctdYYNK5jakdqLkRlI39n590T5zctGSwwZZDJj6kW8XSi6ot2MmWWJ0DUT3nuvebBudScjZ79g8cWJ8av0k+/bE5WKd5MdbFpbDVMxu1DVMmtNZGJvq1mtRbn6M+g/kP0FwDwr7quZs7xosNGpbscyxhhd9TyJyFwbLcxlTasg75vW7TsV5K7ji44XPMMrdoj+Y3rT0Hie62nlYV/pwczzOmdLqLhYkzGMzCZWGMQzGMSsZYY6Di1t4nlJ+Em63mJxrVLxPbYxNEdgc1dU2iOKyoYYWjNrEeHTYybVk0atSa7ehuwsWMWTqn1TrnS6hYsi71d1+s+k+ic70e20fzE/VaTdxT9ZtU4GIXdeNx3X77guYYfpHeTQjaMX6brOu4OY4K7Y2d9mbHarI5ox3p4GpJ2Vd/Tst60f7j999pppjR+Q/Qf8J/VaORs3cji7FfFuN61+ui9s8hix1OCh5KGVV23BPXvZfz3CLyHpix+exi8z/KnCnosY2eunor+cxyPO/xJ0vKey9OvE9VjqaYu0x3Z3jd6o2b1T12D+F8l232lwaaacD5LE8LBxu7WTlbWraWpew8Xexjel3E+wWD4APITdNqR8F3R3T0lunCQ4GaE9R37DxeCYfcHi4xci5ovKfxVs55y2hf+65E/Xdp6jR5nrebTmi5incpkyOjs50JvrZwstbbW6kfuuQw+2mykf/EXNFzxfKTrxew929TR6bWnGL//F3JFOFCQT3K4lQ"
47
+
48
+ kernels = Kernel(
49
+ bz2.decompress(base64.b64decode(quantization_code)),
50
+ [
51
+ "int4WeightCompression",
52
+ "int4WeightExtractionFloat",
53
+ "int4WeightExtractionHalf",
54
+ "int8WeightExtractionFloat",
55
+ "int8WeightExtractionHalf",
56
+ ],
57
+ )
58
+
59
+
60
+ def compress_int4_weight(weight: torch.Tensor): # (n, m)
61
+ with torch.cuda.device(weight.device):
62
+ n, m = weight.size(0), weight.size(1)
63
+ assert m % 2 == 0
64
+ m = m // 2
65
+ out = torch.empty(n, m, dtype=torch.int8, device="cuda")
66
+ stream = torch.cuda.current_stream()
67
+
68
+ gridDim = (n, 1, 1)
69
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
70
+
71
+ kernels.int4WeightCompression(
72
+ gridDim,
73
+ blockDim,
74
+ 0,
75
+ stream,
76
+ [ctypes.c_void_p(weight.data_ptr()), ctypes.c_void_p(out.data_ptr()), ctypes.c_int32(n), ctypes.c_int32(m)],
77
+ )
78
+ return out
79
+
80
+
81
+ def extract_weight_to_half(weight: torch.Tensor, scale_list: torch.Tensor, source_bit_width: int):
82
+ if source_bit_width == 8:
83
+ func = kernels.int8WeightExtractionHalf
84
+ elif source_bit_width == 4:
85
+ func = kernels.int4WeightExtractionHalf
86
+ else:
87
+ assert False, "Unsupported bit-width"
88
+
89
+ with torch.cuda.device(weight.device):
90
+ n, m = weight.size(0), weight.size(1)
91
+ out = torch.empty(n, m * (8 // source_bit_width), dtype=torch.half, device="cuda")
92
+ stream = torch.cuda.current_stream()
93
+
94
+ gridDim = (n, 1, 1)
95
+ blockDim = (min(round_up(m, 32), 1024), 1, 1)
96
+
97
+ func(
98
+ gridDim,
99
+ blockDim,
100
+ 0,
101
+ stream,
102
+ [
103
+ ctypes.c_void_p(weight.data_ptr()),
104
+ ctypes.c_void_p(scale_list.data_ptr()),
105
+ ctypes.c_void_p(out.data_ptr()),
106
+ ctypes.c_int32(n),
107
+ ctypes.c_int32(m),
108
+ ],
109
+ )
110
+ return out
111
+
112
+
113
+ class QuantizedLinear(Linear):
114
+ def __init__(self, weight_bit_width: int, weight_tensor=None, bias_tensor=None, *args, **kwargs):
115
+ super(QuantizedLinear, self).__init__(*args, **kwargs)
116
+ self.weight_bit_width = weight_bit_width
117
+
118
+ shape = self.weight.shape
119
+ del self.weight
120
+
121
+ if weight_tensor is None:
122
+ self.weight = torch.empty(
123
+ shape[0], shape[1] * weight_bit_width // 8, dtype=torch.int8, device=kwargs["device"]
124
+ )
125
+ self.weight_scale = torch.empty(shape[0], dtype=kwargs["params_dtype"], device=kwargs["device"])
126
+ else:
127
+ self.weight_scale = (weight_tensor.abs().max(dim=-1).values / ((2 ** (weight_bit_width - 1)) - 1)).half()
128
+ self.weight = torch.round(weight_tensor / self.weight_scale[:, None]).to(torch.int8)
129
+ if weight_bit_width == 4:
130
+ self.weight = compress_int4_weight(self.weight)
131
+
132
+ self.weight = Parameter(self.weight.to(kwargs["device"]), requires_grad=False)
133
+ self.weight_scale = Parameter(self.weight_scale.to(kwargs["device"]), requires_grad=False)
134
+ self.bias = Parameter(bias_tensor.to(kwargs["device"]), requires_grad=False)
135
+
136
+ def forward(self, input):
137
+ output = W8A16Linear.apply(input, self.weight, self.weight_scale, self.weight_bit_width)
138
+ if self.bias is not None:
139
+ output = output + self.bias
140
+ return output
141
+
142
+
143
+ def quantize(model, weight_bit_width):
144
+ """Replace fp16 linear with quantized linear"""
145
+
146
+ for layer in model.layers:
147
+ layer.attention.query_key_value = QuantizedLinear(
148
+ weight_bit_width=weight_bit_width,
149
+ weight_tensor=layer.attention.query_key_value.weight.to(torch.cuda.current_device()),
150
+ bias_tensor=layer.attention.query_key_value.bias,
151
+ in_features=layer.attention.query_key_value.in_features,
152
+ out_features=layer.attention.query_key_value.out_features,
153
+ bias=True,
154
+ dtype=torch.half,
155
+ device=layer.attention.query_key_value.weight.device,
156
+ )
157
+ layer.attention.dense = QuantizedLinear(
158
+ weight_bit_width=weight_bit_width,
159
+ weight_tensor=layer.attention.dense.weight.to(torch.cuda.current_device()),
160
+ bias_tensor=layer.attention.dense.bias,
161
+ in_features=layer.attention.dense.in_features,
162
+ out_features=layer.attention.dense.out_features,
163
+ bias=True,
164
+ dtype=torch.half,
165
+ device=layer.attention.dense.weight.device,
166
+ )
167
+ layer.mlp.dense_h_to_4h = QuantizedLinear(
168
+ weight_bit_width=weight_bit_width,
169
+ weight_tensor=layer.mlp.dense_h_to_4h.weight.to(torch.cuda.current_device()),
170
+ bias_tensor=layer.mlp.dense_h_to_4h.bias,
171
+ in_features=layer.mlp.dense_h_to_4h.in_features,
172
+ out_features=layer.mlp.dense_h_to_4h.out_features,
173
+ bias=True,
174
+ dtype=torch.half,
175
+ device=layer.mlp.dense_h_to_4h.weight.device,
176
+ )
177
+ layer.mlp.dense_4h_to_h = QuantizedLinear(
178
+ weight_bit_width=weight_bit_width,
179
+ weight_tensor=layer.mlp.dense_4h_to_h.weight.to(torch.cuda.current_device()),
180
+ bias_tensor=layer.mlp.dense_4h_to_h.bias,
181
+ in_features=layer.mlp.dense_4h_to_h.in_features,
182
+ out_features=layer.mlp.dense_4h_to_h.out_features,
183
+ bias=True,
184
+ dtype=torch.half,
185
+ device=layer.mlp.dense_4h_to_h.weight.device,
186
+ )
187
+ return model
moe/temp1.wav ADDED
Binary file (279 kB). View file
 
moe/temp2.wav ADDED
Binary file (557 kB). View file
 
moe/tokenization_chatglm.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for ChatGLM."""
2
+ import sys
3
+ import unicodedata
4
+ from typing import List, Optional, Union
5
+ from functools import lru_cache
6
+ import os
7
+ import collections
8
+ import re
9
+
10
+ from transformers.tokenization_utils import PreTrainedTokenizer
11
+ from icetk.text_tokenizer import TextTokenizer
12
+ from icetk.utils import auto_create
13
+ import icetk.sentencepiece_model_pb2 as sp_model
14
+ from transformers.utils import logging
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
19
+ "THUDM/chatglm-6b": 2048,
20
+ }
21
+
22
+
23
+ class SPTokenizer:
24
+ def __init__(
25
+ self,
26
+ vocab_file,
27
+ max_blank_length=80,
28
+ byte_fallback=True,
29
+ ):
30
+ assert vocab_file is not None
31
+ self.vocab_file = vocab_file
32
+ self.special_tokens = ["[MASK]", "[gMASK]", "[sMASK]", "<unused_0>", "<sop>", "<eop>", "<ENC>", "<dBLOCK>"]
33
+ self.max_blank_length = max_blank_length
34
+ self.byte_fallback = byte_fallback
35
+ self.text_tokenizer = self._build_text_tokenizer(encode_special_tokens=False)
36
+ self.special_text_tokenizer = self._build_text_tokenizer(encode_special_tokens=True)
37
+
38
+ @staticmethod
39
+ def _configure_tokenizer(
40
+ text_tokenizer: TextTokenizer,
41
+ special_tokens: List[str],
42
+ max_blank_length: int,
43
+ byte_fallback: bool,
44
+ encode_special_tokens=False,
45
+ ):
46
+ # special token
47
+ special_token_type = 4 if encode_special_tokens else 3 # 3 - CONTROL, 4 - USER_DEFINE
48
+ for token in special_tokens:
49
+ text_tokenizer.proto.pieces.append(
50
+ sp_model.ModelProto.SentencePiece(piece=token, score=0.0, type=special_token_type)
51
+ )
52
+ # whitespaces
53
+ for token in [SPTokenizer.get_tab_token()] + [
54
+ SPTokenizer.get_blank_token(i) for i in range(2, max_blank_length + 1)
55
+ ]:
56
+ text_tokenizer.proto.pieces.append(sp_model.ModelProto.SentencePiece(piece=token, score=0.0, type=4))
57
+ # byte fallback
58
+ if byte_fallback:
59
+ text_tokenizer.proto.trainer_spec.byte_fallback = True
60
+ for i in range(256):
61
+ text_tokenizer.proto.pieces.append(
62
+ sp_model.ModelProto.SentencePiece(piece="<0x{:02X}>".format(i), score=0.0, type=6)
63
+ )
64
+ text_tokenizer.refresh()
65
+
66
+ def _build_text_tokenizer(self, encode_special_tokens=False):
67
+ tokenizer = TextTokenizer(self.vocab_file)
68
+ self._configure_tokenizer(
69
+ tokenizer, self.special_tokens, self.max_blank_length, self.byte_fallback, encode_special_tokens
70
+ )
71
+ return tokenizer
72
+
73
+ def _get_text_tokenizer(self, encode_special_tokens=False):
74
+ if encode_special_tokens:
75
+ return self.special_text_tokenizer
76
+ else:
77
+ return self.text_tokenizer
78
+
79
+ @staticmethod
80
+ def get_blank_token(length: int):
81
+ assert length >= 2
82
+ return f"<|blank_{length}|>"
83
+
84
+ @staticmethod
85
+ def get_tab_token():
86
+ return f"<|tab|>"
87
+
88
+ @property
89
+ def num_image_tokens(self):
90
+ return 20000
91
+
92
+ @property
93
+ def num_text_tokens(self):
94
+ return self.text_tokenizer.num_tokens
95
+
96
+ @property
97
+ def num_tokens(self):
98
+ return self.num_image_tokens + self.num_text_tokens
99
+
100
+ @staticmethod
101
+ def _encode_whitespaces(text: str, max_len: int = 80):
102
+ text = text.replace("\t", SPTokenizer.get_tab_token())
103
+ for i in range(max_len, 1, -1):
104
+ text = text.replace(" " * i, SPTokenizer.get_blank_token(i))
105
+ return text
106
+
107
+ def _preprocess(self, text: str, linebreak=True, whitespaces=True):
108
+ if linebreak:
109
+ text = text.replace("\n", "<n>")
110
+ if whitespaces:
111
+ text = self._encode_whitespaces(text, max_len=self.max_blank_length)
112
+ return text
113
+
114
+ def encode(
115
+ self, text: str, linebreak=True, whitespaces=True, special_tokens=False, add_dummy_prefix=True
116
+ ) -> List[int]:
117
+ """
118
+ @param text: Text to encode.
119
+ @param linebreak: Whether to encode newline (\n) in text.
120
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
121
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
122
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
123
+ """
124
+ text = self._preprocess(text, linebreak, whitespaces)
125
+ if not add_dummy_prefix:
126
+ text = "<n>" + text
127
+ tmp = self._get_text_tokenizer(encode_special_tokens=special_tokens).encode(text)
128
+ tokens = [x + self.num_image_tokens for x in tmp]
129
+ return tokens if add_dummy_prefix else tokens[2:]
130
+
131
+ def decode(self, text_ids: List[int], special_tokens=False) -> str:
132
+ ids = [int(_id) - self.num_image_tokens for _id in text_ids]
133
+ text = self._get_text_tokenizer(encode_special_tokens=special_tokens).decode(ids)
134
+ text = text.replace("<n>", "\n")
135
+ text = text.replace(SPTokenizer.get_tab_token(), "\t")
136
+ for i in range(2, self.max_blank_length + 1):
137
+ text = text.replace(self.get_blank_token(i), " " * i)
138
+ return text
139
+
140
+ def tokenize(
141
+ self, text: str, linebreak=True, whitespaces=True, special_tokens=False, add_dummy_prefix=True
142
+ ) -> List[str]:
143
+ """
144
+ @param text: Text to encode.
145
+ @param linebreak: Whether to encode newline (\n) in text.
146
+ @param whitespaces: Whether to encode multiple whitespaces or tab in text, useful for source code encoding.
147
+ @param special_tokens: Whether to encode special token ([MASK], [gMASK], etc.) in text.
148
+ @param add_dummy_prefix: Whether to add dummy blank space in the beginning.
149
+ """
150
+ text = self._preprocess(text, linebreak, whitespaces)
151
+ if not add_dummy_prefix:
152
+ text = "<n>" + text
153
+ tokens = self._get_text_tokenizer(encode_special_tokens=special_tokens).tokenize(text)
154
+ return tokens if add_dummy_prefix else tokens[2:]
155
+
156
+ def __getitem__(self, x: Union[int, str]):
157
+ if isinstance(x, int):
158
+ if x < self.num_image_tokens:
159
+ return "<image_{}>".format(x)
160
+ else:
161
+ return self.text_tokenizer.convert_id_to_token(x - self.num_image_tokens)
162
+ elif isinstance(x, str):
163
+ if x.startswith("<image_") and x.endswith(">") and x[7:-1].isdigit():
164
+ return int(x[7:-1])
165
+ else:
166
+ return self.text_tokenizer.convert_token_to_id(x) + self.num_image_tokens
167
+ else:
168
+ raise ValueError("The key should be str or int.")
169
+
170
+
171
+ class ChatGLMTokenizer(PreTrainedTokenizer):
172
+ """
173
+ Construct a ChatGLM tokenizer. Based on byte-level Byte-Pair-Encoding.
174
+
175
+ Args:
176
+ vocab_file (`str`):
177
+ Path to the vocabulary file.
178
+ """
179
+
180
+ vocab_files_names = {"vocab_file": "ice_text.model"}
181
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
182
+ model_input_names = ["input_ids"]
183
+
184
+ def __init__(
185
+ self,
186
+ vocab_file,
187
+ do_lower_case=False,
188
+ remove_space=False,
189
+ bos_token='sop',
190
+ eos_token='eos',
191
+ eop_token='eop',
192
+ mask_token='[MASK]',
193
+ gmask_token='[gMASK]',
194
+ padding_side="left",
195
+ **kwargs
196
+ ) -> None:
197
+ super().__init__(
198
+ do_lower_case=do_lower_case,
199
+ remove_space=remove_space,
200
+ padding_side=padding_side,
201
+ **kwargs
202
+ )
203
+
204
+ self.do_lower_case = do_lower_case
205
+ self.remove_space = remove_space
206
+ self.vocab_file = vocab_file
207
+
208
+ self.bos_token = bos_token
209
+ self.eos_token = eos_token
210
+ self.eop_token = eop_token
211
+ self.mask_token = mask_token
212
+ self.gMASK_token = gmask_token
213
+
214
+ self.sp_tokenizer = SPTokenizer(vocab_file)
215
+
216
+ """ Initialisation """
217
+
218
+ @property
219
+ def eop_token_id(self) -> Optional[int]:
220
+ """
221
+ `Optional[int]`: Id of the end of sentence token in the vocabulary. Returns `None` if the token has not been
222
+ set.
223
+ """
224
+ if self.eop_token is None:
225
+ return None
226
+ return self.convert_tokens_to_ids(self.eop_token)
227
+
228
+ @property
229
+ def vocab_size(self):
230
+ """ Returns vocab size """
231
+ return self.sp_tokenizer.num_tokens
232
+
233
+ def get_vocab(self):
234
+ """ Returns vocab as a dict """
235
+ vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
236
+ vocab.update(self.added_tokens_encoder)
237
+ return vocab
238
+
239
+ def preprocess_text(self, inputs):
240
+ if self.remove_space:
241
+ outputs = " ".join(inputs.strip().split())
242
+ else:
243
+ outputs = inputs
244
+
245
+ if self.do_lower_case:
246
+ outputs = outputs.lower()
247
+
248
+ return outputs
249
+
250
+ def _tokenize(self, text, **kwargs):
251
+ """ Returns a tokenized string. """
252
+ text = self.preprocess_text(text)
253
+
254
+ seq = self.sp_tokenizer.tokenize(text)
255
+
256
+ return seq
257
+
258
+ def decode(
259
+ self,
260
+ token_ids: Union[List[int], List[List[int]]],
261
+ skip_special_tokens: bool = False,
262
+ clean_up_tokenization_spaces: bool = True,
263
+ spaces_between_special_tokens: bool = True,
264
+ **kwargs
265
+ ) -> str:
266
+ if isinstance(token_ids[0], list):
267
+ tokens = []
268
+ for single_token_ids in token_ids:
269
+ if self.pad_token_id in single_token_ids: # remove pad
270
+ single_token_ids = list(filter((self.pad_token_id).__ne__, single_token_ids))
271
+ tokens.append(self.sp_tokenizer.decode(single_token_ids))
272
+ return (tokens)
273
+ else:
274
+ if self.pad_token_id in token_ids: # remove pad
275
+ token_ids = list(filter((self.pad_token_id).__ne__, token_ids))
276
+ return self.sp_tokenizer.decode(token_ids)
277
+
278
+ def _convert_token_to_id(self, token):
279
+ """ Converts a token (str) in an id using the vocab. """
280
+ return self.sp_tokenizer[token]
281
+
282
+ def _convert_id_to_token(self, index):
283
+ """Converts an index (integer) in a token (str) using the vocab."""
284
+ return self.sp_tokenizer[index]
285
+
286
+ def save_vocabulary(self, save_directory, filename_prefix=None):
287
+ """
288
+ Save the vocabulary and special tokens file to a directory.
289
+
290
+ Args:
291
+ save_directory (`str`):
292
+ The directory in which to save the vocabulary.
293
+ filename_prefix (`str`, *optional*):
294
+ An optional prefix to add to the named of the saved files.
295
+
296
+ Returns:
297
+ `Tuple(str)`: Paths to the files saved.
298
+ """
299
+ if os.path.isdir(save_directory):
300
+ vocab_file = os.path.join(
301
+ save_directory, VOCAB_FILES_NAMES["vocab_file"]
302
+ )
303
+ else:
304
+ vocab_file = save_directory
305
+
306
+ with open(self.vocab_file, 'rb') as fin:
307
+ proto_str = fin.read()
308
+
309
+ with open(vocab_file, "wb") as writer:
310
+ writer.write(proto_str)
311
+
312
+ return (vocab_file,)
313
+
314
+ def build_inputs_with_special_tokens(
315
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
316
+ ) -> List[int]:
317
+ """
318
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
319
+ adding special tokens. A BERT sequence has the following format:
320
+
321
+ - single sequence: `[CLS] X [SEP]`
322
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
323
+
324
+ Args:
325
+ token_ids_0 (`List[int]`):
326
+ List of IDs to which the special tokens will be added.
327
+ token_ids_1 (`List[int]`, *optional*):
328
+ Optional second list of IDs for sequence pairs.
329
+
330
+ Returns:
331
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
332
+ """
333
+ if token_ids_1 is not None:
334
+ token_ids_0 += token_ids_1
335
+ mask_ids = self.sp_tokenizer[self.mask_token]
336
+ gmask_ids = self.sp_tokenizer[self.gMASK_token]
337
+ if mask_ids not in token_ids_0 and gmask_ids not in token_ids_0:
338
+ token_ids_0 += [gmask_ids]
339
+
340
+ if token_ids_0[-1] != mask_ids and token_ids_0[-1] != gmask_ids:
341
+ token_ids_0 += [self.sp_tokenizer[self.eos_token]]
342
+
343
+ token_ids_0 += [self.sp_tokenizer[self.bos_token]]
344
+
345
+ return token_ids_0
moe/tokenizer_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "THUDM/chatglm-6b",
3
+ "bos_token": "<sop>",
4
+ "eop_token": "<eop>",
5
+ "eos_token": "</s>",
6
+ "gmask_token": "[gMASK]",
7
+ "mask_token": "[MASK]",
8
+ "pad_token": "<pad>",
9
+ "unk_token": "<unk>",
10
+ "remove_space": false,
11
+ "do_lower_case": false,
12
+ "tokenizer_class": "ChatGLMTokenizer",
13
+ "auto_map": {
14
+ "AutoTokenizer": [
15
+ "tokenization_chatglm.ChatGLMTokenizer",
16
+ null
17
+ ]
18
+ }
19
+ }
output.wav ADDED
Binary file (557 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flask
2
+ Cython==0.29.21
3
+ librosa==0.8.0
4
+ matplotlib==3.3.1
5
+ numpy==1.21.6
6
+ phonemizer==2.2.1
7
+ scipy==1.5.2
8
+ tensorboard==2.3.0
9
+ torch
10
+ torchvision
11
+ Unidecode==1.1.1
12
+ pyopenjtalk==0.2.0
13
+ jamo==0.4.1
14
+ pypinyin==0.44.0
15
+ jieba==0.42.1
16
+ cn2an==0.5.17
17
+ jieba==0.42.1
18
+ ipython==7.34.0
19
+ gradio==3.4.1
20
+ openai
21
+ pydub
22
+ inflect
23
+ eng_to_ipa
24
+ onnxruntime
text/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2017 Keith Ito
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
text/__init__.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ from https://github.com/keithito/tacotron """
2
+ from text import cleaners
3
+ from text.symbols import symbols
4
+
5
+
6
+ # Mappings from symbol to numeric ID and vice versa:
7
+ _symbol_to_id = {s: i for i, s in enumerate(symbols)}
8
+ _id_to_symbol = {i: s for i, s in enumerate(symbols)}
9
+
10
+
11
+ def text_to_sequence(text, cleaner_names):
12
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
13
+ Args:
14
+ text: string to convert to a sequence
15
+ cleaner_names: names of the cleaner functions to run the text through
16
+ Returns:
17
+ List of integers corresponding to the symbols in the text
18
+ '''
19
+ sequence = []
20
+
21
+ clean_text = _clean_text(text, cleaner_names)
22
+ for symbol in clean_text:
23
+ if symbol not in _symbol_to_id.keys():
24
+ continue
25
+ symbol_id = _symbol_to_id[symbol]
26
+ sequence += [symbol_id]
27
+ return sequence
28
+
29
+
30
+ def cleaned_text_to_sequence(cleaned_text):
31
+ '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
32
+ Args:
33
+ text: string to convert to a sequence
34
+ Returns:
35
+ List of integers corresponding to the symbols in the text
36
+ '''
37
+ sequence = [_symbol_to_id[symbol] for symbol in cleaned_text if symbol in _symbol_to_id.keys()]
38
+ return sequence
39
+
40
+
41
+ def sequence_to_text(sequence):
42
+ '''Converts a sequence of IDs back to a string'''
43
+ result = ''
44
+ for symbol_id in sequence:
45
+ s = _id_to_symbol[symbol_id]
46
+ result += s
47
+ return result
48
+
49
+
50
+ def _clean_text(text, cleaner_names):
51
+ for name in cleaner_names:
52
+ cleaner = getattr(cleaners, name)
53
+ if not cleaner:
54
+ raise Exception('Unknown cleaner: %s' % name)
55
+ text = cleaner(text)
56
+ return text
text/__pycache__/__init__.cpython-37.pyc ADDED
Binary file (2.1 kB). View file
 
text/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (2.15 kB). View file
 
text/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (2.13 kB). View file
 
text/__pycache__/cleaners.cpython-37.pyc ADDED
Binary file (4.1 kB). View file
 
text/__pycache__/cleaners.cpython-38.pyc ADDED
Binary file (6.42 kB). View file
 
text/__pycache__/cleaners.cpython-39.pyc ADDED
Binary file (6.37 kB). View file
 
text/__pycache__/english.cpython-37.pyc ADDED
Binary file (4.94 kB). View file
 
text/__pycache__/english.cpython-38.pyc ADDED
Binary file (4.88 kB). View file
 
text/__pycache__/english.cpython-39.pyc ADDED
Binary file (4.86 kB). View file
 
text/__pycache__/japanese.cpython-37.pyc ADDED
Binary file (4.61 kB). View file
 
text/__pycache__/japanese.cpython-38.pyc ADDED
Binary file (4.47 kB). View file
 
text/__pycache__/japanese.cpython-39.pyc ADDED
Binary file (4.43 kB). View file
 
text/__pycache__/korean.cpython-37.pyc ADDED
Binary file (5.76 kB). View file
 
text/__pycache__/mandarin.cpython-37.pyc ADDED
Binary file (7.52 kB). View file
 
text/__pycache__/mandarin.cpython-38.pyc ADDED
Binary file (6.43 kB). View file
 
text/__pycache__/mandarin.cpython-39.pyc ADDED
Binary file (6.4 kB). View file
 
text/__pycache__/sanskrit.cpython-37.pyc ADDED
Binary file (1.64 kB). View file