1
0

vits.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. import json, logging, math, re, sys, time, wave, argparse, numpy as np
  2. from phonemizer.phonemize import default_separator, _phonemize
  3. from phonemizer.backend import EspeakBackend
  4. from phonemizer.punctuation import Punctuation
  5. from functools import reduce
  6. from pathlib import Path
  7. from typing import List
  8. from tinygrad import nn, dtypes
  9. from tinygrad.helpers import fetch
  10. from tinygrad.nn.state import torch_load
  11. from tinygrad.tensor import Tensor
  12. from tinygrad.engine.jit import TinyJit
  13. from unidecode import unidecode
  14. LRELU_SLOPE = 0.1
  15. class Synthesizer:
  16. def __init__(self, n_vocab, spec_channels, segment_size, inter_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, n_speakers=0, gin_channels=0, use_sdp=True, emotion_embedding=False, **kwargs):
  17. self.n_vocab, self.spec_channels, self.inter_channels, self.hidden_channels, self.filter_channels, self.n_heads, self.n_layers, self.kernel_size, self.p_dropout, self.resblock, self.resblock_kernel_sizes, self.resblock_dilation_sizes, self.upsample_rates, self.upsample_initial_channel, self.upsample_kernel_sizes, self.segment_size, self.n_speakers, self.gin_channels, self.use_sdp = n_vocab, spec_channels, inter_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, segment_size, n_speakers, gin_channels, use_sdp
  18. self.enc_p = TextEncoder(n_vocab, inter_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, emotion_embedding)
  19. self.dec = Generator(inter_channels, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=gin_channels)
  20. self.enc_q = PosteriorEncoder(spec_channels, inter_channels, hidden_channels, 5, 1, 16, gin_channels=gin_channels)
  21. self.flow = ResidualCouplingBlock(inter_channels, hidden_channels, 5, 1, 4, gin_channels=gin_channels)
  22. self.dp = StochasticDurationPredictor(hidden_channels, 192, 3, 0.5, 4, gin_channels=gin_channels) if use_sdp else DurationPredictor(hidden_channels, 256, 3, 0.5, gin_channels=gin_channels)
  23. if n_speakers > 1: self.emb_g = nn.Embedding(n_speakers, gin_channels)
  24. def infer(self, x, x_lengths, sid=None, noise_scale=1.0, length_scale=1, noise_scale_w=1., max_len=None, emotion_embedding=None, max_y_length_estimate_scale=None, pad_length=-1):
  25. x, m_p, logs_p, x_mask = self.enc_p.forward(x.realize(), x_lengths.realize(), emotion_embedding.realize() if emotion_embedding is not None else emotion_embedding)
  26. g = self.emb_g(sid.reshape(1, 1)).squeeze(1).unsqueeze(-1) if self.n_speakers > 0 else None
  27. logw = self.dp.forward(x, x_mask.realize(), g=g.realize(), reverse=self.use_sdp, noise_scale=noise_scale_w if self.use_sdp else 1.0)
  28. w_ceil = Tensor.ceil(logw.exp() * x_mask * length_scale)
  29. y_lengths = Tensor.maximum(w_ceil.sum([1, 2]), 1).cast(dtypes.int64)
  30. return self.generate(g, logs_p, m_p, max_len, max_y_length_estimate_scale, noise_scale, w_ceil, x, x_mask, y_lengths, pad_length)
  31. def generate(self, g, logs_p, m_p, max_len, max_y_length_estimate_scale, noise_scale, w_ceil, x, x_mask, y_lengths, pad_length):
  32. max_y_length = y_lengths.max().item() if max_y_length_estimate_scale is None else max(15, x.shape[-1]) * max_y_length_estimate_scale
  33. y_mask = sequence_mask(y_lengths, max_y_length).unsqueeze(1).cast(x_mask.dtype)
  34. attn_mask = x_mask.unsqueeze(2) * y_mask.unsqueeze(-1)
  35. attn = generate_path(w_ceil, attn_mask)
  36. m_p_2 = attn.squeeze(1).matmul(m_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
  37. logs_p_2 = attn.squeeze(1).matmul(logs_p.transpose(1, 2)).transpose(1, 2) # [b, t', t], [b, t, d] -> [b, d, t']
  38. z_p = m_p_2 + Tensor.randn(*m_p_2.shape, dtype=m_p_2.dtype) * logs_p_2.exp() * noise_scale
  39. row_len = y_mask.shape[2]
  40. if pad_length > -1:
  41. # Pad flow forward inputs to enable JIT
  42. assert pad_length > row_len, "pad length is too small"
  43. y_mask = y_mask.pad(((0, 0), (0, 0), (0, pad_length - row_len)), 0).cast(z_p.dtype)
  44. # New y_mask tensor to remove sts mask
  45. y_mask = Tensor(y_mask.numpy(), device=y_mask.device, dtype=y_mask.dtype, requires_grad=y_mask.requires_grad)
  46. z_p = z_p.squeeze(0).pad(((0, 0), (0, pad_length - z_p.shape[2])), 1).unsqueeze(0)
  47. z = self.flow.forward(z_p.realize(), y_mask.realize(), g=g.realize(), reverse=True)
  48. result_length = reduce(lambda x, y: x * y, self.dec.upsample_rates, row_len)
  49. o = self.dec.forward((z * y_mask)[:, :, :max_len], g=g)[:, :, :result_length]
  50. if max_y_length_estimate_scale is not None:
  51. length_scaler = o.shape[-1] / max_y_length
  52. o.realize()
  53. real_max_y_length = y_lengths.max().numpy()
  54. if real_max_y_length > max_y_length:
  55. logging.warning(f"Underestimated max length by {(((real_max_y_length / max_y_length) * 100) - 100):.2f}%, recomputing inference without estimate...")
  56. return self.generate(g, logs_p, m_p, max_len, None, noise_scale, w_ceil, x, x_mask, y_lengths)
  57. if real_max_y_length < max_y_length:
  58. overestimation = ((max_y_length / real_max_y_length) * 100) - 100
  59. logging.info(f"Overestimated max length by {overestimation:.2f}%")
  60. if overestimation > 10: logging.warning("Warning: max length overestimated by more than 10%")
  61. o = o[:, :, :(real_max_y_length * length_scaler).astype(np.int32)]
  62. return o
  63. class StochasticDurationPredictor:
  64. def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, n_flows=4, gin_channels=0):
  65. filter_channels = in_channels # it needs to be removed from future version.
  66. self.in_channels, self.filter_channels, self.kernel_size, self.p_dropout, self.n_flows, self.gin_channels = in_channels, filter_channels, kernel_size, p_dropout, n_flows, gin_channels
  67. self.log_flow, self.flows = Log(), [ElementwiseAffine(2)]
  68. for _ in range(n_flows):
  69. self.flows.append(ConvFlow(2, filter_channels, kernel_size, n_layers=3))
  70. self.flows.append(Flip())
  71. self.post_pre, self.post_proj = nn.Conv1d(1, filter_channels, 1), nn.Conv1d(filter_channels, filter_channels, 1)
  72. self.post_convs = DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
  73. self.post_flows = [ElementwiseAffine(2)]
  74. for _ in range(4):
  75. self.post_flows.append(ConvFlow(2, filter_channels, kernel_size, n_layers=3))
  76. self.post_flows.append(Flip())
  77. self.pre, self.proj = nn.Conv1d(in_channels, filter_channels, 1), nn.Conv1d(filter_channels, filter_channels, 1)
  78. self.convs = DDSConv(filter_channels, kernel_size, n_layers=3, p_dropout=p_dropout)
  79. if gin_channels != 0: self.cond = nn.Conv1d(gin_channels, filter_channels, 1)
  80. @TinyJit
  81. def forward(self, x: Tensor, x_mask, w=None, g=None, reverse=False, noise_scale=1.0):
  82. x = self.pre(x.detach())
  83. if g is not None: x = x + self.cond(g.detach())
  84. x = self.convs.forward(x, x_mask)
  85. x = self.proj(x) * x_mask
  86. if not reverse:
  87. flows = self.flows
  88. assert w is not None
  89. log_det_tot_q = 0
  90. h_w = self.post_proj(self.post_convs.forward(self.post_pre(w), x_mask)) * x_mask
  91. e_q = Tensor.randn(w.size(0), 2, w.size(2), dtype=x.dtype).to(device=x.device) * x_mask
  92. z_q = e_q
  93. for flow in self.post_flows:
  94. z_q, log_det_q = flow.forward(z_q, x_mask, g=(x + h_w))
  95. log_det_tot_q += log_det_q
  96. z_u, z1 = z_q.split([1, 1], 1)
  97. u = z_u.sigmoid() * x_mask
  98. z0 = (w - u) * x_mask
  99. log_det_tot_q += Tensor.sum((z_u.logsigmoid() + (-z_u).logsigmoid()) * x_mask, [1,2])
  100. log_q = Tensor.sum(-0.5 * (math.log(2*math.pi) + (e_q**2)) * x_mask, [1,2]) - log_det_tot_q
  101. log_det_tot = 0
  102. z0, log_det = self.log_flow.forward(z0, x_mask)
  103. log_det_tot += log_det
  104. z = z0.cat(z1, 1)
  105. for flow in flows:
  106. z, log_det = flow.forward(z, x_mask, g=x, reverse=reverse)
  107. log_det_tot = log_det_tot + log_det
  108. nll = Tensor.sum(0.5 * (math.log(2*math.pi) + (z**2)) * x_mask, [1,2]) - log_det_tot
  109. return (nll + log_q).realize() # [b]
  110. flows = list(reversed(self.flows))
  111. flows = flows[:-2] + [flows[-1]] # remove a useless vflow
  112. z = Tensor.randn(x.shape[0], 2, x.shape[2], dtype=x.dtype).to(device=x.device) * noise_scale
  113. for flow in flows: z = flow.forward(z, x_mask, g=x, reverse=reverse)
  114. z0, z1 = split(z, [1, 1], 1)
  115. return z0.realize()
  116. class DurationPredictor:
  117. def __init__(self, in_channels, filter_channels, kernel_size, p_dropout, gin_channels=0):
  118. self.in_channels, self.filter_channels, self.kernel_size, self.p_dropout, self.gin_channels = in_channels, filter_channels, kernel_size, p_dropout, gin_channels
  119. self.conv_1, self.norm_1 = nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size//2), LayerNorm(filter_channels)
  120. self.conv_2, self.norm_2 = nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size//2), LayerNorm(filter_channels)
  121. self.proj = nn.Conv1d(filter_channels, 1, 1)
  122. if gin_channels != 0: self.cond = nn.Conv1d(gin_channels, in_channels, 1)
  123. def forward(self, x: Tensor, x_mask, g=None):
  124. x = x.detach()
  125. if g is not None: x = x + self.cond(g.detach())
  126. x = self.conv_1(x * x_mask).relu()
  127. x = self.norm_1(x).dropout(self.p_dropout)
  128. x = self.conv_2(x * x_mask).relu(x)
  129. x = self.norm_2(x).dropout(self.p_dropout)
  130. return self.proj(x * x_mask) * x_mask
  131. class TextEncoder:
  132. def __init__(self, n_vocab, out_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, emotion_embedding):
  133. self.n_vocab, self.out_channels, self.hidden_channels, self.filter_channels, self.n_heads, self.n_layers, self.kernel_size, self.p_dropout = n_vocab, out_channels, hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
  134. if n_vocab!=0:self.emb = nn.Embedding(n_vocab, hidden_channels)
  135. if emotion_embedding: self.emo_proj = nn.Linear(1024, hidden_channels)
  136. self.encoder = Encoder(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout)
  137. self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
  138. @TinyJit
  139. def forward(self, x: Tensor, x_lengths: Tensor, emotion_embedding=None):
  140. if self.n_vocab!=0: x = (self.emb(x) * math.sqrt(self.hidden_channels))
  141. if emotion_embedding: x = x + self.emo_proj(emotion_embedding).unsqueeze(1)
  142. x = x.transpose(1, -1) # [b, t, h] -transpose-> [b, h, t]
  143. x_mask = sequence_mask(x_lengths, x.shape[2]).unsqueeze(1).cast(x.dtype)
  144. x = self.encoder.forward(x * x_mask, x_mask)
  145. m, logs = split(self.proj(x) * x_mask, self.out_channels, dim=1)
  146. return x.realize(), m.realize(), logs.realize(), x_mask.realize()
  147. class ResidualCouplingBlock:
  148. def __init__(self, channels, hidden_channels, kernel_size, dilation_rate, n_layers, n_flows=4, gin_channels=0):
  149. self.channels, self.hidden_channels, self.kernel_size, self.dilation_rate, self.n_layers, self.n_flows, self.gin_channels = channels, hidden_channels, kernel_size, dilation_rate, n_layers, n_flows, gin_channels
  150. self.flows = []
  151. for _ in range(n_flows):
  152. self.flows.append(ResidualCouplingLayer(channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels, mean_only=True))
  153. self.flows.append(Flip())
  154. @TinyJit
  155. def forward(self, x, x_mask, g=None, reverse=False):
  156. for flow in reversed(self.flows) if reverse else self.flows: x = flow.forward(x, x_mask, g=g, reverse=reverse)
  157. return x.realize()
  158. class PosteriorEncoder:
  159. def __init__(self, in_channels, out_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0):
  160. self.in_channels, self.out_channels, self.hidden_channels, self.kernel_size, self.dilation_rate, self.n_layers, self.gin_channels = in_channels, out_channels, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels
  161. self.pre, self.proj = nn.Conv1d(in_channels, hidden_channels, 1), nn.Conv1d(hidden_channels, out_channels * 2, 1)
  162. self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=gin_channels)
  163. def forward(self, x, x_lengths, g=None):
  164. x_mask = sequence_mask(x_lengths, x.size(2)).unsqueeze(1).cast(x.dtype)
  165. stats = self.proj(self.enc.forward(self.pre(x) * x_mask, x_mask, g=g)) * x_mask
  166. m, logs = stats.split(self.out_channels, dim=1)
  167. z = (m + Tensor.randn(m.shape, m.dtype) * logs.exp()) * x_mask
  168. return z, m, logs, x_mask
  169. class Generator:
  170. def __init__(self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0):
  171. self.num_kernels, self.num_upsamples = len(resblock_kernel_sizes), len(upsample_rates)
  172. self.conv_pre = nn.Conv1d(initial_channel, upsample_initial_channel, 7, 1, padding=3)
  173. resblock = ResBlock1 if resblock == '1' else ResBlock2
  174. self.ups = [nn.ConvTranspose1d(upsample_initial_channel//(2**i), upsample_initial_channel//(2**(i+1)), k, u, padding=(k-u)//2) for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes))]
  175. self.resblocks = []
  176. self.upsample_rates = upsample_rates
  177. for i in range(len(self.ups)):
  178. ch = upsample_initial_channel // (2 ** (i + 1))
  179. for _, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
  180. self.resblocks.append(resblock(ch, k, d))
  181. self.conv_post = nn.Conv1d(ch, 1, 7, 1, padding=3, bias=False)
  182. if gin_channels != 0: self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
  183. @TinyJit
  184. def forward(self, x: Tensor, g=None):
  185. x = self.conv_pre(x)
  186. if g is not None: x = x + self.cond(g)
  187. for i in range(self.num_upsamples):
  188. x = self.ups[i](x.leakyrelu(LRELU_SLOPE))
  189. xs = sum(self.resblocks[i * self.num_kernels + j].forward(x) for j in range(self.num_kernels))
  190. x = (xs / self.num_kernels).realize()
  191. res = self.conv_post(x.leakyrelu()).tanh().realize()
  192. return res
  193. class LayerNorm(nn.LayerNorm):
  194. def __init__(self, channels, eps=1e-5): super().__init__(channels, eps, elementwise_affine=True)
  195. def forward(self, x: Tensor): return self.__call__(x.transpose(1, -1)).transpose(1, -1)
  196. class WN:
  197. def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
  198. assert (kernel_size % 2 == 1)
  199. self.hidden_channels, self.kernel_size, self.dilation_rate, self.n_layers, self.gin_channels, self.p_dropout = hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels, p_dropout
  200. self.in_layers, self.res_skip_layers = [], []
  201. if gin_channels != 0: self.cond_layer = nn.Conv1d(gin_channels, 2 * hidden_channels * n_layers, 1)
  202. for i in range(n_layers):
  203. dilation = dilation_rate ** i
  204. self.in_layers.append(nn.Conv1d(hidden_channels, 2 * hidden_channels, kernel_size, dilation=dilation, padding=int((kernel_size * dilation - dilation) / 2)))
  205. self.res_skip_layers.append(nn.Conv1d(hidden_channels, 2 * hidden_channels if i < n_layers - 1 else hidden_channels, 1))
  206. def forward(self, x, x_mask, g=None, **kwargs):
  207. output = Tensor.zeros_like(x)
  208. if g is not None: g = self.cond_layer(g)
  209. for i in range(self.n_layers):
  210. x_in = self.in_layers[i](x)
  211. if g is not None:
  212. cond_offset = i * 2 * self.hidden_channels
  213. g_l = g[:, cond_offset:cond_offset + 2 * self.hidden_channels, :]
  214. else:
  215. g_l = Tensor.zeros_like(x_in)
  216. acts = fused_add_tanh_sigmoid_multiply(x_in, g_l, self.hidden_channels)
  217. res_skip_acts = self.res_skip_layers[i](acts)
  218. if i < self.n_layers - 1:
  219. x = (x + res_skip_acts[:, :self.hidden_channels, :]) * x_mask
  220. output = output + res_skip_acts[:, self.hidden_channels:, :]
  221. else:
  222. output = output + res_skip_acts
  223. return output * x_mask
  224. class ResBlock1:
  225. def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
  226. self.convs1 = [nn.Conv1d(channels, channels, kernel_size, 1, dilation=dilation[i], padding=get_padding(kernel_size, dilation[i])) for i in range(3)]
  227. self.convs2 = [nn.Conv1d(channels, channels, kernel_size, 1, dilation=1, padding=get_padding(kernel_size, 1)) for _ in range(3)]
  228. def forward(self, x: Tensor, x_mask=None):
  229. for c1, c2 in zip(self.convs1, self.convs2):
  230. xt = x.leakyrelu(LRELU_SLOPE)
  231. xt = c1(xt if x_mask is None else xt * x_mask).leakyrelu(LRELU_SLOPE)
  232. x = c2(xt if x_mask is None else xt * x_mask) + x
  233. return x if x_mask is None else x * x_mask
  234. class ResBlock2:
  235. def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
  236. self.convs = [nn.Conv1d(channels, channels, kernel_size, 1, dilation=dilation[i], padding=get_padding(kernel_size, dilation[i])) for i in range(2)]
  237. def forward(self, x, x_mask=None):
  238. for c in self.convs:
  239. xt = x.leaky_relu(LRELU_SLOPE)
  240. xt = c(xt if x_mask is None else xt * x_mask)
  241. x = xt + x
  242. return x if x_mask is None else x * x_mask
  243. class DDSConv: # Dilated and Depth-Separable Convolution
  244. def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
  245. self.channels, self.kernel_size, self.n_layers, self.p_dropout = channels, kernel_size, n_layers, p_dropout
  246. self.convs_sep, self.convs_1x1, self.norms_1, self.norms_2 = [], [], [], []
  247. for i in range(n_layers):
  248. dilation = kernel_size ** i
  249. padding = (kernel_size * dilation - dilation) // 2
  250. self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size, groups=channels, dilation=dilation, padding=padding))
  251. self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
  252. self.norms_1.append(LayerNorm(channels))
  253. self.norms_2.append(LayerNorm(channels))
  254. def forward(self, x, x_mask, g=None):
  255. if g is not None: x = x + g
  256. for i in range(self.n_layers):
  257. y = self.convs_sep[i](x * x_mask)
  258. y = self.norms_1[i].forward(y).gelu()
  259. y = self.convs_1x1[i](y)
  260. y = self.norms_2[i].forward(y).gelu()
  261. x = x + y.dropout(self.p_dropout)
  262. return x * x_mask
  263. class ConvFlow:
  264. def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
  265. self.in_channels, self.filter_channels, self.kernel_size, self.n_layers, self.num_bins, self.tail_bound = in_channels, filter_channels, kernel_size, n_layers, num_bins, tail_bound
  266. self.half_channels = in_channels // 2
  267. self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
  268. self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
  269. self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
  270. def forward(self, x, x_mask, g=None, reverse=False):
  271. x0, x1 = split(x, [self.half_channels] * 2, 1)
  272. h = self.proj(self.convs.forward(self.pre(x0), x_mask, g=g)) * x_mask
  273. b, c, t = x0.shape
  274. h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
  275. un_normalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
  276. un_normalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
  277. un_normalized_derivatives = h[..., 2 * self.num_bins:]
  278. x1, log_abs_det = piecewise_rational_quadratic_transform(x1, un_normalized_widths, un_normalized_heights, un_normalized_derivatives, inverse=reverse, tails='linear', tail_bound=self.tail_bound)
  279. x = x0.cat(x1, dim=1) * x_mask
  280. return x if reverse else (x, Tensor.sum(log_abs_det * x_mask, [1,2]))
  281. class ResidualCouplingLayer:
  282. def __init__(self, channels, hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=0, gin_channels=0, mean_only=False):
  283. assert channels % 2 == 0, "channels should be divisible by 2"
  284. self.channels, self.hidden_channels, self.kernel_size, self.dilation_rate, self.n_layers, self.mean_only = channels, hidden_channels, kernel_size, dilation_rate, n_layers, mean_only
  285. self.half_channels = channels // 2
  286. self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
  287. self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
  288. self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
  289. def forward(self, x, x_mask, g=None, reverse=False):
  290. x0, x1 = split(x, [self.half_channels] * 2, 1)
  291. stats = self.post(self.enc.forward(self.pre(x0) * x_mask, x_mask, g=g)) * x_mask
  292. if not self.mean_only:
  293. m, logs = split(stats, [self.half_channels] * 2, 1)
  294. else:
  295. m = stats
  296. logs = Tensor.zeros_like(m)
  297. if not reverse: return x0.cat((m + x1 * logs.exp() * x_mask), dim=1)
  298. return x0.cat(((x1 - m) * (-logs).exp() * x_mask), dim=1)
  299. class Log:
  300. def forward(self, x : Tensor, x_mask, reverse=False):
  301. if not reverse:
  302. y = x.maximum(1e-5).log() * x_mask
  303. return y, (-y).sum([1, 2])
  304. return x.exp() * x_mask
  305. class Flip:
  306. def forward(self, x: Tensor, *args, reverse=False, **kwargs):
  307. return x.flip([1]) if reverse else (x.flip([1]), Tensor.zeros(x.shape[0], dtype=x.dtype).to(device=x.device))
  308. class ElementwiseAffine:
  309. def __init__(self, channels): self.m, self.logs = Tensor.zeros(channels, 1), Tensor.zeros(channels, 1)
  310. def forward(self, x, x_mask, reverse=False, **kwargs): # x if reverse else y, logdet
  311. return (x - self.m) * Tensor.exp(-self.logs) * x_mask if reverse \
  312. else ((self.m + Tensor.exp(self.logs) * x) * x_mask, Tensor.sum(self.logs * x_mask, [1, 2]))
  313. class MultiHeadAttention:
  314. def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
  315. assert channels % n_heads == 0
  316. self.channels, self.out_channels, self.n_heads, self.p_dropout, self.window_size, self.heads_share, self.block_length, self.proximal_bias, self.proximal_init = channels, out_channels, n_heads, p_dropout, window_size, heads_share, block_length, proximal_bias, proximal_init
  317. self.attn, self.k_channels = None, channels // n_heads
  318. self.conv_q, self.conv_k, self.conv_v = [nn.Conv1d(channels, channels, 1) for _ in range(3)]
  319. self.conv_o = nn.Conv1d(channels, out_channels, 1)
  320. if window_size is not None: self.emb_rel_k, self.emb_rel_v = [Tensor.randn(1 if heads_share else n_heads, window_size * 2 + 1, self.k_channels) * (self.k_channels ** -0.5) for _ in range(2)]
  321. def forward(self, x, c, attn_mask=None):
  322. q, k, v = self.conv_q(x), self.conv_k(c), self.conv_v(c)
  323. x, self.attn = self.attention(q, k, v, mask=attn_mask)
  324. return self.conv_o(x)
  325. def attention(self, query: Tensor, key: Tensor, value: Tensor, mask=None):# reshape [b, d, t] -> [b, n_h, t, d_k]
  326. b, d, t_s, t_t = key.shape[0], key.shape[1], key.shape[2], query.shape[2]
  327. query = query.reshape(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
  328. key = key.reshape(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
  329. value = value.reshape(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
  330. scores = (query / math.sqrt(self.k_channels)) @ key.transpose(-2, -1)
  331. if self.window_size is not None:
  332. assert t_s == t_t, "Relative attention is only available for self-attention."
  333. key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
  334. rel_logits = self._matmul_with_relative_keys(query / math.sqrt(self.k_channels), key_relative_embeddings)
  335. scores = scores + self._relative_position_to_absolute_position(rel_logits)
  336. if mask is not None:
  337. scores = Tensor.where(mask, scores, -1e4)
  338. if self.block_length is not None:
  339. assert t_s == t_t, "Local attention is only available for self-attention."
  340. scores = Tensor.where(Tensor.ones_like(scores).triu(-self.block_length).tril(self.block_length), scores, -1e4)
  341. p_attn = scores.softmax(axis=-1) # [b, n_h, t_t, t_s]
  342. output = p_attn.matmul(value)
  343. if self.window_size is not None:
  344. relative_weights = self._absolute_position_to_relative_position(p_attn)
  345. value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
  346. output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
  347. output = output.transpose(2, 3).contiguous().reshape(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
  348. return output, p_attn
  349. def _matmul_with_relative_values(self, x, y): return x.matmul(y.unsqueeze(0)) # x: [b, h, l, m], y: [h or 1, m, d], ret: [b, h, l, d]
  350. def _matmul_with_relative_keys(self, x, y): return x.matmul(y.unsqueeze(0).transpose(-2, -1)) # x: [b, h, l, d], y: [h or 1, m, d], re, : [b, h, l, m]
  351. def _get_relative_embeddings(self, relative_embeddings, length):
  352. pad_length, slice_start_position = max(length - (self.window_size + 1), 0), max((self.window_size + 1) - length, 0)
  353. padded_relative_embeddings = relative_embeddings if pad_length <= 0\
  354. else relative_embeddings.pad(convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
  355. return padded_relative_embeddings[:, slice_start_position:(slice_start_position + 2 * length - 1)] #used_relative_embeddings
  356. def _relative_position_to_absolute_position(self, x: Tensor): # x: [b, h, l, 2*l-1] -> [b, h, l, l]
  357. batch, heads, length, _ = x.shape
  358. x = x.pad(convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
  359. x_flat = x.reshape([batch, heads, length * 2 * length]).pad(convert_pad_shape([[0,0],[0,0],[0,length-1]]))
  360. return x_flat.reshape([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
  361. def _absolute_position_to_relative_position(self, x: Tensor): # x: [b, h, l, l] -> [b, h, l, 2*l-1]
  362. batch, heads, length, _ = x.shape
  363. x = x.pad(convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
  364. x_flat = x.reshape([batch, heads, length**2 + length*(length -1)]).pad(convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
  365. return x_flat.reshape([batch, heads, length, 2*length])[:,:,:,1:]
  366. class FFN:
  367. def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
  368. self.in_channels, self.out_channels, self.filter_channels, self.kernel_size, self.p_dropout, self.activation, self.causal = in_channels, out_channels, filter_channels, kernel_size, p_dropout, activation, causal
  369. self.padding = self._causal_padding if causal else self._same_padding
  370. self.conv_1, self.conv_2 = nn.Conv1d(in_channels, filter_channels, kernel_size), nn.Conv1d(filter_channels, out_channels, kernel_size)
  371. def forward(self, x, x_mask):
  372. x = self.conv_1(self.padding(x * x_mask))
  373. x = x * (1.702 * x).sigmoid() if self.activation == "gelu" else x.relu()
  374. return self.conv_2(self.padding(x.dropout(self.p_dropout) * x_mask)) * x_mask
  375. def _causal_padding(self, x):return x if self.kernel_size == 1 else x.pad(convert_pad_shape([[0, 0], [0, 0], [self.kernel_size - 1, 0]]))
  376. def _same_padding(self, x): return x if self.kernel_size == 1 else x.pad(convert_pad_shape([[0, 0], [0, 0], [(self.kernel_size - 1) // 2, self.kernel_size // 2]]))
  377. class Encoder:
  378. def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
  379. self.hidden_channels, self.filter_channels, self.n_heads, self.n_layers, self.kernel_size, self.p_dropout, self.window_size = hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, window_size
  380. self.attn_layers, self.norm_layers_1, self.ffn_layers, self.norm_layers_2 = [], [], [], []
  381. for _ in range(n_layers):
  382. self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
  383. self.norm_layers_1.append(LayerNorm(hidden_channels))
  384. self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
  385. self.norm_layers_2.append(LayerNorm(hidden_channels))
  386. def forward(self, x, x_mask):
  387. attn_mask, x = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1), x * x_mask
  388. for i in range(self.n_layers):
  389. y = self.attn_layers[i].forward(x, x, attn_mask).dropout(self.p_dropout)
  390. x = self.norm_layers_1[i].forward(x + y)
  391. y = self.ffn_layers[i].forward(x, x_mask).dropout(self.p_dropout)
  392. x = self.norm_layers_2[i].forward(x + y)
  393. return x * x_mask
  394. DEFAULT_MIN_BIN_WIDTH, DEFAULT_MIN_BIN_HEIGHT, DEFAULT_MIN_DERIVATIVE = 1e-3, 1e-3, 1e-3
  395. def piecewise_rational_quadratic_transform(inputs, un_normalized_widths, un_normalized_heights, un_normalized_derivatives, inverse=False, tails=None, tail_bound=1., min_bin_width=DEFAULT_MIN_BIN_WIDTH, min_bin_height=DEFAULT_MIN_BIN_HEIGHT, min_derivative=DEFAULT_MIN_DERIVATIVE):
  396. if tails is None: spline_fn, spline_kwargs = rational_quadratic_spline, {}
  397. else: spline_fn, spline_kwargs = unconstrained_rational_quadratic_spline, {'tails': tails, 'tail_bound': tail_bound}
  398. return spline_fn(inputs=inputs, un_normalized_widths=un_normalized_widths, un_normalized_heights=un_normalized_heights, un_normalized_derivatives=un_normalized_derivatives, inverse=inverse, min_bin_width=min_bin_width, min_bin_height=min_bin_height, min_derivative=min_derivative, **spline_kwargs)
  399. def unconstrained_rational_quadratic_spline(inputs, un_normalized_widths, un_normalized_heights, un_normalized_derivatives, inverse=False, tails='linear', tail_bound=1., min_bin_width=DEFAULT_MIN_BIN_WIDTH, min_bin_height=DEFAULT_MIN_BIN_HEIGHT, min_derivative=DEFAULT_MIN_DERIVATIVE):
  400. if not tails == 'linear': raise RuntimeError('{} tails are not implemented.'.format(tails))
  401. constant = np.log(np.exp(1 - min_derivative) - 1)
  402. un_normalized_derivatives = cat_lr(un_normalized_derivatives, constant, constant)
  403. output, log_abs_det = rational_quadratic_spline(inputs=inputs.squeeze(dim=0).squeeze(dim=0), unnormalized_widths=un_normalized_widths.squeeze(dim=0).squeeze(dim=0), unnormalized_heights=un_normalized_heights.squeeze(dim=0).squeeze(dim=0), unnormalized_derivatives=un_normalized_derivatives.squeeze(dim=0).squeeze(dim=0), inverse=inverse, left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound, min_bin_width=min_bin_width, min_bin_height=min_bin_height, min_derivative=min_derivative)
  404. return output.unsqueeze(dim=0).unsqueeze(dim=0), log_abs_det.unsqueeze(dim=0).unsqueeze(dim=0)
  405. def rational_quadratic_spline(inputs: Tensor, unnormalized_widths: Tensor, unnormalized_heights: Tensor, unnormalized_derivatives: Tensor, inverse=False, left=0., right=1., bottom=0., top=1., min_bin_width=DEFAULT_MIN_BIN_WIDTH, min_bin_height=DEFAULT_MIN_BIN_HEIGHT, min_derivative=DEFAULT_MIN_DERIVATIVE):
  406. num_bins = unnormalized_widths.shape[-1]
  407. if min_bin_width * num_bins > 1.0: raise ValueError('Minimal bin width too large for the number of bins')
  408. if min_bin_height * num_bins > 1.0: raise ValueError('Minimal bin height too large for the number of bins')
  409. widths = min_bin_width + (1 - min_bin_width * num_bins) * unnormalized_widths.softmax(axis=-1)
  410. cum_widths = cat_lr(((right - left) * widths[..., :-1].cumsum(axis=1) + left), left, right + 1e-6 if not inverse else right)
  411. widths = cum_widths[..., 1:] - cum_widths[..., :-1]
  412. derivatives = min_derivative + (unnormalized_derivatives.exp()+1).log()
  413. heights = min_bin_height + (1 - min_bin_height * num_bins) * unnormalized_heights.softmax(axis=-1)
  414. cum_heights = cat_lr(((top - bottom) * heights[..., :-1].cumsum(axis=1) + bottom), bottom, top + 1e-6 if inverse else top)
  415. heights = cum_heights[..., 1:] - cum_heights[..., :-1]
  416. bin_idx = ((inputs[..., None] >= (cum_heights if inverse else cum_widths)).sum(axis=-1) - 1)[..., None]
  417. input_cum_widths = gather(cum_widths, bin_idx, axis=-1)[..., 0]
  418. input_bin_widths = gather(widths, bin_idx, axis=-1)[..., 0]
  419. input_cum_heights = gather(cum_heights, bin_idx, axis=-1)[..., 0]
  420. input_delta = gather(heights / widths, bin_idx, axis=-1)[..., 0]
  421. input_derivatives = gather(derivatives, bin_idx, axis=-1)[..., 0]
  422. input_derivatives_plus_one = gather(derivatives[..., 1:], bin_idx, axis=-1)[..., 0]
  423. input_heights = gather(heights, bin_idx, axis=-1)[..., 0]
  424. if inverse:
  425. a = ((inputs - input_cum_heights) * (input_derivatives + input_derivatives_plus_one - 2 * input_delta) + input_heights * (input_delta - input_derivatives))
  426. b = (input_heights * input_derivatives - (inputs - input_cum_heights) * (input_derivatives + input_derivatives_plus_one - 2 * input_delta))
  427. c = - input_delta * (inputs - input_cum_heights)
  428. discriminant = b.square() - 4 * a * c
  429. # assert (discriminant.numpy() >= 0).all()
  430. root = (2 * c) / (-b - discriminant.sqrt())
  431. theta_one_minus_theta = root * (1 - root)
  432. denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta) * theta_one_minus_theta)
  433. derivative_numerator = input_delta.square() * (input_derivatives_plus_one * root.square() + 2 * input_delta * theta_one_minus_theta + input_derivatives * (1 - root).square())
  434. return root * input_bin_widths + input_cum_widths, -(derivative_numerator.log() - 2 * denominator.log())
  435. theta = (inputs - input_cum_widths) / input_bin_widths
  436. theta_one_minus_theta = theta * (1 - theta)
  437. numerator = input_heights * (input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta)
  438. denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta) * theta_one_minus_theta)
  439. derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2) + 2 * input_delta * theta_one_minus_theta + input_derivatives * (1 - theta).pow(2))
  440. return input_cum_heights + numerator / denominator, derivative_numerator.log() - 2 * denominator.log()
  441. def sequence_mask(length: Tensor, max_length): return Tensor.arange(max_length, dtype=length.dtype, device=length.device).unsqueeze(0) < length.unsqueeze(1)
  442. def generate_path(duration: Tensor, mask: Tensor): # duration: [b, 1, t_x], mask: [b, 1, t_y, t_x]
  443. b, _, t_y, t_x = mask.shape
  444. path = sequence_mask(duration.cumsum(axis=2).reshape(b * t_x), t_y).cast(mask.dtype).reshape(b, t_x, t_y)
  445. path = path - path.pad(convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
  446. return path.unsqueeze(1).transpose(2, 3) * mask
  447. def fused_add_tanh_sigmoid_multiply(input_a: Tensor, input_b: Tensor, n_channels: int):
  448. n_channels_int, in_act = n_channels, input_a + input_b
  449. t_act, s_act = in_act[:, :n_channels_int, :].tanh(), in_act[:, n_channels_int:, :].sigmoid()
  450. return t_act * s_act
  451. def cat_lr(t, left, right): return Tensor.full(get_shape(t), left).cat(t, dim=-1).cat(Tensor.full(get_shape(t), right), dim=-1)
  452. def get_shape(tensor):
  453. (shape := list(tensor.shape))[-1] = 1
  454. return tuple(shape)
  455. def convert_pad_shape(pad_shape): return tuple(tuple(x) for x in pad_shape)
  456. def get_padding(kernel_size, dilation=1): return int((kernel_size*dilation - dilation)/2)
  457. def split(tensor, split_sizes, dim=0): # if split_sizes is an integer, convert it to a tuple of size split_sizes elements
  458. if isinstance(split_sizes, int): split_sizes = (split_sizes,) * (tensor.shape[dim] // split_sizes)
  459. assert sum(split_sizes) == tensor.shape[
  460. dim], "Sum of split_sizes must equal the dimension size of tensor along the given dimension."
  461. start, slices = 0, []
  462. for size in split_sizes:
  463. slice_range = [(start, start + size) if j == dim else None for j in range(len(tensor.shape))]
  464. slices.append(slice_range)
  465. start += size
  466. return [tensor._slice(s) for s in slices]
  467. def gather(x, indices, axis):
  468. indices = (indices < 0).where(indices + x.shape[axis], indices).transpose(0, axis)
  469. permute_args = list(range(x.ndim))
  470. permute_args[0], permute_args[axis] = permute_args[axis], permute_args[0]
  471. permute_args.append(permute_args.pop(0))
  472. x = x.permute(*permute_args)
  473. reshape_arg = [1] * x.ndim + [x.shape[-1]]
  474. return ((indices.unsqueeze(indices.ndim).expand(*indices.shape, x.shape[-1]) ==
  475. Tensor.arange(x.shape[-1]).reshape(*reshape_arg).expand(*indices.shape, x.shape[-1])) * x).sum(indices.ndim).transpose(0, axis)
  476. def norm_except_dim(v, dim):
  477. if dim == -1: return np.linalg.norm(v)
  478. if dim == 0:
  479. (output_shape := [1] * v.ndim)[0] = v.shape[0]
  480. return np.linalg.norm(v.reshape(v.shape[0], -1), axis=1).reshape(output_shape)
  481. if dim == v.ndim - 1:
  482. (output_shape := [1] * v.ndim)[-1] = v.shape[-1]
  483. return np.linalg.norm(v.reshape(-1, v.shape[-1]), axis=0).reshape(output_shape)
  484. transposed_v = np.transpose(v, (dim,) + tuple(i for i in range(v.ndim) if i != dim))
  485. return np.transpose(norm_except_dim(transposed_v, 0), (dim,) + tuple(i for i in range(v.ndim) if i != dim))
  486. def weight_norm(v: Tensor, g: Tensor, dim):
  487. v, g = v.numpy(), g.numpy()
  488. return Tensor(v * (g / norm_except_dim(v, dim)))
  489. # HPARAMS LOADING
  490. def get_hparams_from_file(path):
  491. with open(path, "r") as f:
  492. data = f.read()
  493. return HParams(**json.loads(data))
  494. class HParams:
  495. def __init__(self, **kwargs):
  496. for k, v in kwargs.items(): self[k] = v if type(v) != dict else HParams(**v)
  497. def keys(self): return self.__dict__.keys()
  498. def items(self): return self.__dict__.items()
  499. def values(self): return self.__dict__.values()
  500. def __len__(self): return len(self.__dict__)
  501. def __getitem__(self, key): return getattr(self, key)
  502. def __setitem__(self, key, value): return setattr(self, key, value)
  503. def __contains__(self, key): return key in self.__dict__
  504. def __repr__(self): return self.__dict__.__repr__()
  505. # MODEL LOADING
  506. def load_model(symbols, hps, model) -> Synthesizer:
  507. net_g = Synthesizer(len(symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers = hps.data.n_speakers, **hps.model)
  508. _ = load_checkpoint(fetch(model[1]), net_g, None)
  509. return net_g
  510. def load_checkpoint(checkpoint_path, model: Synthesizer, optimizer=None, skip_list=[]):
  511. assert Path(checkpoint_path).is_file()
  512. start_time = time.time()
  513. checkpoint_dict = torch_load(checkpoint_path)
  514. iteration, learning_rate = checkpoint_dict['iteration'], checkpoint_dict['learning_rate']
  515. if optimizer: optimizer.load_state_dict(checkpoint_dict['optimizer'])
  516. saved_state_dict = checkpoint_dict['model']
  517. weight_g, weight_v, parent = None, None, None
  518. for key, v in saved_state_dict.items():
  519. if any(layer in key for layer in skip_list): continue
  520. try:
  521. obj, skip = model, False
  522. for k in key.split('.'):
  523. if k.isnumeric(): obj = obj[int(k)]
  524. elif isinstance(obj, dict): obj = obj[k]
  525. else:
  526. if isinstance(obj, (LayerNorm, nn.LayerNorm)) and k in ["gamma", "beta"]:
  527. k = "weight" if k == "gamma" else "bias"
  528. elif k in ["weight_g", "weight_v"]:
  529. parent, skip = obj, True
  530. if k == "weight_g": weight_g = v
  531. else: weight_v = v
  532. if not skip: obj = getattr(obj, k)
  533. if weight_g is not None and weight_v is not None:
  534. setattr(obj, "weight_g", weight_g.numpy())
  535. setattr(obj, "weight_v", weight_v.numpy())
  536. obj, v = getattr(parent, "weight"), weight_norm(weight_v, weight_g, 0)
  537. weight_g, weight_v, parent, skip = None, None, None, False
  538. if not skip and obj.shape == v.shape: obj.assign(v.to(obj.device))
  539. elif not skip: logging.error(f"MISMATCH SHAPE IN {key}, {obj.shape} {v.shape}")
  540. except Exception as e: raise e
  541. logging.info(f"Loaded checkpoint '{checkpoint_path}' (iteration {iteration}) in {time.time() - start_time:.4f}s")
  542. return model, optimizer, learning_rate, iteration
  543. # Used for cleaning input text and mapping to symbols
  544. class TextMapper: # Based on https://github.com/keithito/tacotron
  545. def __init__(self, symbols, apply_cleaners=True):
  546. self.apply_cleaners, self.symbols, self._inflect = apply_cleaners, symbols, None
  547. self._symbol_to_id, _id_to_symbol = {s: i for i, s in enumerate(symbols)}, {i: s for i, s in enumerate(symbols)}
  548. self._whitespace_re, self._abbreviations = re.compile(r'\s+'), [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [('mrs', 'misess'), ('mr', 'mister'), ('dr', 'doctor'), ('st', 'saint'), ('co', 'company'), ('jr', 'junior'), ('maj', 'major'), ('gen', 'general'), ('drs', 'doctors'), ('rev', 'reverend'), ('lt', 'lieutenant'), ('hon', 'honorable'), ('sgt', 'sergeant'), ('capt', 'captain'), ('esq', 'esquire'), ('ltd', 'limited'), ('col', 'colonel'), ('ft', 'fort'), ]]
  549. self.phonemizer = EspeakBackend(
  550. language="en-us", punctuation_marks=Punctuation.default_marks(), preserve_punctuation=True, with_stress=True,
  551. )
  552. def text_to_sequence(self, text, cleaner_names):
  553. if self.apply_cleaners:
  554. for name in cleaner_names:
  555. cleaner = getattr(self, name)
  556. if not cleaner: raise ModuleNotFoundError('Unknown cleaner: %s' % name)
  557. text = cleaner(text)
  558. else: text = text.strip()
  559. return [self._symbol_to_id[symbol] for symbol in text]
  560. def get_text(self, text, add_blank=False, cleaners=('english_cleaners2',)):
  561. text_norm = self.text_to_sequence(text, cleaners)
  562. return Tensor(self.intersperse(text_norm, 0) if add_blank else text_norm, dtype=dtypes.int64)
  563. def intersperse(self, lst, item):
  564. (result := [item] * (len(lst) * 2 + 1))[1::2] = lst
  565. return result
  566. def phonemize(self, text, strip=True): return _phonemize(self.phonemizer, text, default_separator, strip, 1, False, False)
  567. def filter_oov(self, text): return "".join(list(filter(lambda x: x in self._symbol_to_id, text)))
  568. def base_english_cleaners(self, text): return self.collapse_whitespace(self.phonemize(self.expand_abbreviations(unidecode(text.lower()))))
  569. def english_cleaners2(self, text): return self.base_english_cleaners(text)
  570. def transliteration_cleaners(self, text): return self.collapse_whitespace(unidecode(text.lower()))
  571. def cjke_cleaners(self, text): return re.sub(r'([^\.,!\?\-…~])$', r'\1.', re.sub(r'\s+$', '', self.english_to_ipa2(text).replace('ɑ', 'a').replace('ɔ', 'o').replace('ɛ', 'e').replace('ɪ', 'i').replace('ʊ', 'u')))
  572. def cjke_cleaners2(self, text): return re.sub(r'([^\.,!\?\-…~])$', r'\1.', re.sub(r'\s+$', '', self.english_to_ipa2(text)))
  573. def cjks_cleaners(self, text): return re.sub(r'([^\.,!\?\-…~])$', r'\1.', re.sub(r'\s+$', '', self.english_to_lazy_ipa(text)))
  574. def english_to_ipa2(self, text):
  575. _ipa_to_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [ ('r', 'ɹ'), ('ʤ', 'dʒ'), ('ʧ', 'tʃ')]]
  576. return reduce(lambda t, rx: re.sub(rx[0], rx[1], t), _ipa_to_ipa2, self.mark_dark_l(self.english_to_ipa(text))).replace('...', '…')
  577. def mark_dark_l(self, text): return re.sub(r'l([^aeiouæɑɔəɛɪʊ ]*(?: |$))', lambda x: 'ɫ' + x.group(1), text)
  578. def english_to_ipa(self, text):
  579. import eng_to_ipa as ipa
  580. return self.collapse_whitespace(ipa.convert(self.normalize_numbers(self.expand_abbreviations(unidecode(text).lower()))))
  581. def english_to_lazy_ipa(self, text):
  582. _lazy_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [('r', 'ɹ'), ('æ', 'e'), ('ɑ', 'a'), ('ɔ', 'o'), ('ð', 'z'), ('θ', 's'), ('ɛ', 'e'), ('ɪ', 'i'), ('ʊ', 'u'), ('ʒ', 'ʥ'), ('ʤ', 'ʥ'), ('ˈ', '↓')]]
  583. return reduce(lambda t, rx: re.sub(rx[0], rx[1], t), _lazy_ipa, self.english_to_ipa(text))
  584. def expand_abbreviations(self, text): return reduce(lambda t, abbr: re.sub(abbr[0], abbr[1], t), self._abbreviations, text)
  585. def collapse_whitespace(self, text): return re.sub(self._whitespace_re, ' ', text)
  586. def normalize_numbers(self, text):
  587. import inflect
  588. self._inflect = inflect.engine()
  589. text = re.sub(re.compile(r'([0-9][0-9\,]+[0-9])'), self._remove_commas, text)
  590. text = re.sub(re.compile(r'£([0-9\,]*[0-9]+)'), r'\1 pounds', text)
  591. text = re.sub(re.compile(r'\$([0-9\.\,]*[0-9]+)'), self._expand_dollars, text)
  592. text = re.sub(re.compile(r'([0-9]+\.[0-9]+)'), self._expand_decimal_point, text)
  593. text = re.sub(re.compile(r'[0-9]+(st|nd|rd|th)'), self._expand_ordinal, text)
  594. text = re.sub(re.compile(r'[0-9]+'), self._expand_number, text)
  595. return text
  596. def _remove_commas(self, m): return m.group(1).replace(',', '') # george won't like this
  597. def _expand_dollars(self, m):
  598. match = m.group(1)
  599. parts = match.split('.')
  600. if len(parts) > 2: return match + ' dollars' # Unexpected format
  601. dollars, cents = int(parts[0]) if parts[0] else 0, int(parts[1]) if len(parts) > 1 and parts[1] else 0
  602. if dollars and cents: return '%s %s, %s %s' % (dollars, 'dollar' if dollars == 1 else 'dollars', cents, 'cent' if cents == 1 else 'cents')
  603. if dollars: return '%s %s' % (dollars, 'dollar' if dollars == 1 else 'dollars')
  604. if cents: return '%s %s' % (cents, 'cent' if cents == 1 else 'cents')
  605. return 'zero dollars'
  606. def _expand_decimal_point(self, m): return m.group(1).replace('.', ' point ')
  607. def _expand_ordinal(self, m): return self._inflect.number_to_words(m.group(0))
  608. def _expand_number(self, _inflect, m):
  609. num = int(m.group(0))
  610. if 1000 < num < 3000:
  611. if num == 2000: return 'two thousand'
  612. if 2000 < num < 2010: return 'two thousand ' + self._inflect.number_to_words(num % 100)
  613. if num % 100 == 0: return self._inflect.number_to_words(num // 100) + ' hundred'
  614. return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ')
  615. return self._inflect.number_to_words(num, andword='')
  616. #########################################################################################
  617. # PAPER: https://arxiv.org/abs/2106.06103
  618. # CODE: https://github.com/jaywalnut310/vits/tree/main
  619. #########################################################################################
  620. # INSTALLATION: this is based on default config, dependencies are for preprocessing.
  621. # vctk, ljs | pip3 install unidecode phonemizer | phonemizer requires [eSpeak](https://espeak.sourceforge.net) backend to be installed on your system
  622. # mmts-tts | pip3 install unidecode |
  623. # uma_trilingual, cjks, voistock | pip3 install unidecode inflect eng_to_ipa |
  624. #########################################################################################
  625. # Some good speakers to try out, there may be much better ones, I only tried out a few:
  626. # male vctk 1 | --model_to_use vctk --speaker_id 2
  627. # male vctk 2 | --model_to_use vctk --speaker_id 6
  628. # anime lady 1 | --model_to_use uma_trilingual --speaker_id 36
  629. # anime lady 2 | --model_to_use uma_trilingual --speaker_id 121
  630. #########################################################################################
  631. VITS_PATH = Path(__file__).parents[1] / "weights/VITS/"
  632. MODELS = { # config_url, weights_url
  633. "ljs": ("https://raw.githubusercontent.com/jaywalnut310/vits/main/configs/ljs_base.json", "https://drive.google.com/uc?export=download&id=1q86w74Ygw2hNzYP9cWkeClGT5X25PvBT&confirm=t"),
  634. "vctk": ("https://raw.githubusercontent.com/jaywalnut310/vits/main/configs/vctk_base.json", "https://drive.google.com/uc?export=download&id=11aHOlhnxzjpdWDpsz1vFDCzbeEfoIxru&confirm=t"),
  635. "mmts-tts": ("https://huggingface.co/facebook/mms-tts/raw/main/full_models/eng/config.json", "https://huggingface.co/facebook/mms-tts/resolve/main/full_models/eng/G_100000.pth"),
  636. "uma_trilingual": ("https://huggingface.co/spaces/Plachta/VITS-Umamusume-voice-synthesizer/raw/main/configs/uma_trilingual.json", "https://huggingface.co/spaces/Plachta/VITS-Umamusume-voice-synthesizer/resolve/main/pretrained_models/G_trilingual.pth"),
  637. "cjks": ("https://huggingface.co/spaces/skytnt/moe-tts/resolve/main/saved_model/14/config.json", "https://huggingface.co/spaces/skytnt/moe-tts/resolve/main/saved_model/14/model.pth"),
  638. "voistock": ("https://huggingface.co/spaces/skytnt/moe-tts/resolve/main/saved_model/15/config.json", "https://huggingface.co/spaces/skytnt/moe-tts/resolve/main/saved_model/15/model.pth"),
  639. }
  640. Y_LENGTH_ESTIMATE_SCALARS = {"ljs": 2.8, "vctk": 1.74, "mmts-tts": 1.9, "uma_trilingual": 2.3, "cjks": 3.3, "voistock": 3.1}
  641. if __name__ == '__main__':
  642. logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
  643. parser = argparse.ArgumentParser()
  644. parser.add_argument("--model_to_use", default="vctk", help="Specify the model to use. Default is 'vctk'.")
  645. parser.add_argument("--speaker_id", type=int, default=6, help="Specify the speaker ID. Default is 6.")
  646. parser.add_argument("--out_path", default=None, help="Specify the full output path. Overrides the --out_dir and --name parameter.")
  647. parser.add_argument("--out_dir", default=str(Path(__file__).parents[1] / "temp"), help="Specify the output path.")
  648. parser.add_argument("--base_name", default="test", help="Specify the base of the output file name. Default is 'test'.")
  649. parser.add_argument("--text_to_synthesize", default="""Hello person. If the code you are contributing isn't some of the highest quality code you've written in your life, either put in the effort to make it great, or don't bother.""", help="Specify the text to synthesize. Default is a greeting message.")
  650. parser.add_argument("--noise_scale", type=float, default=0.667, help="Specify the noise scale. Default is 0.667.")
  651. parser.add_argument("--noise_scale_w", type=float, default=0.8, help="Specify the noise scale w. Default is 0.8.")
  652. parser.add_argument("--length_scale", type=float, default=1, help="Specify the length scale. Default is 1.")
  653. parser.add_argument("--seed", type=int, default=1337, help="Specify the seed (set to None if no seed). Default is 1337.")
  654. parser.add_argument("--num_channels", type=int, default=1, help="Specify the number of audio output channels. Default is 1.")
  655. parser.add_argument("--sample_width", type=int, default=2, help="Specify the number of bytes per sample, adjust if necessary. Default is 2.")
  656. parser.add_argument("--emotion_path", type=str, default=None, help="Specify the path to emotion reference.")
  657. parser.add_argument("--estimate_max_y_length", type=str, default=False, help="If true, overestimate the output length and then trim it to the correct length, to prevent premature realization, much more performant for larger inputs, for smaller inputs not so much. Default is False.")
  658. args = parser.parse_args()
  659. model_config = MODELS[args.model_to_use]
  660. # Load the hyperparameters from the config file.
  661. hps = get_hparams_from_file(fetch(model_config[0]))
  662. # If model has multiple speakers, validate speaker id and retrieve name if available.
  663. model_has_multiple_speakers = hps.data.n_speakers > 0
  664. if model_has_multiple_speakers:
  665. logging.info(f"Model has {hps.data.n_speakers} speakers")
  666. if args.speaker_id >= hps.data.n_speakers: raise ValueError(f"Speaker ID {args.speaker_id} is invalid for this model.")
  667. speaker_name = "?"
  668. if hps.__contains__("speakers"): # maps speaker ids to names
  669. speakers = hps.speakers
  670. if isinstance(speakers, List): speakers = {speaker: i for i, speaker in enumerate(speakers)}
  671. speaker_name = next((key for key, value in speakers.items() if value == args.speaker_id), None)
  672. logging.info(f"You selected speaker {args.speaker_id} (name: {speaker_name})")
  673. # Load emotions if any. TODO: find an english model with emotions, this is untested atm.
  674. emotion_embedding = None
  675. if args.emotion_path is not None:
  676. if args.emotion_path.endswith(".npy"): emotion_embedding = Tensor(np.load(args.emotion_path), dtype=dtypes.int64).unsqueeze(0)
  677. else: raise ValueError("Emotion path must be a .npy file.")
  678. # Load symbols, instantiate TextMapper and clean the text.
  679. if hps.__contains__("symbols"): symbols = hps.symbols
  680. elif args.model_to_use == "mmts-tts": symbols = [x.replace("\n", "") for x in fetch("https://huggingface.co/facebook/mms-tts/raw/main/full_models/eng/vocab.txt").open(encoding="utf-8").readlines()]
  681. else: symbols = ['_'] + list(';:,.!?¡¿—…"«»“” ') + list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') + list("ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ")
  682. text_mapper = TextMapper(apply_cleaners=True, symbols=symbols)
  683. # Load the model.
  684. Tensor.no_grad = True
  685. if args.seed is not None:
  686. Tensor.manual_seed(args.seed)
  687. np.random.seed(args.seed)
  688. net_g = load_model(text_mapper.symbols, hps, model_config)
  689. logging.debug(f"Loaded model with hps: {hps}")
  690. # Convert the input text to a tensor.
  691. text_to_synthesize = args.text_to_synthesize
  692. if args.model_to_use == "mmts-tts": text_to_synthesize = text_mapper.filter_oov(text_to_synthesize.lower())
  693. stn_tst = text_mapper.get_text(text_to_synthesize, hps.data.add_blank, hps.data.text_cleaners)
  694. logging.debug(f"Converted input text to tensor \"{text_to_synthesize}\" -> Tensor({stn_tst.shape}): {stn_tst.numpy()}")
  695. x_tst, x_tst_lengths = stn_tst.unsqueeze(0), Tensor([stn_tst.shape[0]], dtype=dtypes.int64)
  696. sid = Tensor([args.speaker_id], dtype=dtypes.int64) if model_has_multiple_speakers else None
  697. # Perform inference.
  698. start_time = time.time()
  699. audio_tensor = net_g.infer(x_tst, x_tst_lengths, sid, args.noise_scale, args.length_scale, args.noise_scale_w, emotion_embedding=emotion_embedding,
  700. max_y_length_estimate_scale=Y_LENGTH_ESTIMATE_SCALARS[args.model_to_use] if args.estimate_max_y_length else None)[0, 0].realize()
  701. logging.info(f"Inference took {(time.time() - start_time):.2f}s")
  702. # Save the audio output.
  703. audio_data = (np.clip(audio_tensor.numpy(), -1.0, 1.0) * 32767).astype(np.int16)
  704. out_path = Path(args.out_path or Path(args.out_dir)/f"{args.model_to_use}{f'_sid_{args.speaker_id}' if model_has_multiple_speakers else ''}_{args.base_name}.wav")
  705. out_path.parent.mkdir(parents=True, exist_ok=True)
  706. with wave.open(str(out_path), 'wb') as wav_file:
  707. wav_file.setnchannels(args.num_channels)
  708. wav_file.setsampwidth(args.sample_width)
  709. wav_file.setframerate(hps.data.sampling_rate)
  710. wav_file.setnframes(len(audio_data))
  711. wav_file.writeframes(audio_data.tobytes())
  712. logging.info(f"Saved audio output to {out_path}")