modules.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. import numpy as np
  2. import torch
  3. from torch import nn
  4. from torch.nn import Conv1d
  5. from torch.nn import functional as F
  6. from torch.nn.utils import remove_weight_norm, weight_norm
  7. from .commons import fused_add_tanh_sigmoid_multiply, get_padding, init_weights
  8. LRELU_SLOPE = 0.1
  9. class LayerNorm(nn.Module):
  10. def __init__(self, channels, eps=1e-5):
  11. super().__init__()
  12. self.channels = channels
  13. self.eps = eps
  14. self.gamma = nn.Parameter(torch.ones(channels))
  15. self.beta = nn.Parameter(torch.zeros(channels))
  16. def forward(self, x):
  17. x = x.transpose(1, -1)
  18. x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
  19. return x.transpose(1, -1)
  20. class ConvReluNorm(nn.Module):
  21. def __init__(
  22. self,
  23. in_channels,
  24. hidden_channels,
  25. out_channels,
  26. kernel_size,
  27. n_layers,
  28. p_dropout,
  29. ):
  30. super().__init__()
  31. self.in_channels = in_channels
  32. self.hidden_channels = hidden_channels
  33. self.out_channels = out_channels
  34. self.kernel_size = kernel_size
  35. self.n_layers = n_layers
  36. self.p_dropout = p_dropout
  37. assert n_layers > 1, "Number of layers should be larger than 0."
  38. self.conv_layers = nn.ModuleList()
  39. self.norm_layers = nn.ModuleList()
  40. self.conv_layers.append(
  41. nn.Conv1d(
  42. in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
  43. )
  44. )
  45. self.norm_layers.append(LayerNorm(hidden_channels))
  46. self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
  47. for _ in range(n_layers - 1):
  48. self.conv_layers.append(
  49. nn.Conv1d(
  50. hidden_channels,
  51. hidden_channels,
  52. kernel_size,
  53. padding=kernel_size // 2,
  54. )
  55. )
  56. self.norm_layers.append(LayerNorm(hidden_channels))
  57. self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
  58. self.proj.weight.data.zero_()
  59. self.proj.bias.data.zero_()
  60. def forward(self, x, x_mask):
  61. x_org = x
  62. for i in range(self.n_layers):
  63. x = self.conv_layers[i](x * x_mask)
  64. x = self.norm_layers[i](x)
  65. x = self.relu_drop(x)
  66. x = x_org + self.proj(x)
  67. return x * x_mask
  68. class WN(torch.nn.Module):
  69. def __init__(
  70. self,
  71. hidden_channels,
  72. kernel_size,
  73. dilation_rate,
  74. n_layers,
  75. gin_channels=0,
  76. p_dropout=0,
  77. ):
  78. super(WN, self).__init__()
  79. assert kernel_size % 2 == 1
  80. self.hidden_channels = hidden_channels
  81. self.kernel_size = (kernel_size,)
  82. self.dilation_rate = dilation_rate
  83. self.n_layers = n_layers
  84. self.gin_channels = gin_channels
  85. self.p_dropout = p_dropout
  86. self.in_layers = torch.nn.ModuleList()
  87. self.res_skip_layers = torch.nn.ModuleList()
  88. self.drop = nn.Dropout(p_dropout)
  89. if gin_channels != 0:
  90. cond_layer = torch.nn.Conv1d(
  91. gin_channels, 2 * hidden_channels * n_layers, 1
  92. )
  93. self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
  94. for i in range(n_layers):
  95. dilation = dilation_rate**i
  96. padding = int((kernel_size * dilation - dilation) / 2)
  97. in_layer = torch.nn.Conv1d(
  98. hidden_channels,
  99. 2 * hidden_channels,
  100. kernel_size,
  101. dilation=dilation,
  102. padding=padding,
  103. )
  104. in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
  105. self.in_layers.append(in_layer)
  106. # last one is not necessary
  107. if i < n_layers - 1:
  108. res_skip_channels = 2 * hidden_channels
  109. else:
  110. res_skip_channels = hidden_channels
  111. res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
  112. res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
  113. self.res_skip_layers.append(res_skip_layer)
  114. def forward(self, x, x_mask, g=None, **kwargs):
  115. output = torch.zeros_like(x)
  116. n_channels_tensor = torch.IntTensor([self.hidden_channels])
  117. if g is not None:
  118. g = self.cond_layer(g)
  119. for i in range(self.n_layers):
  120. x_in = self.in_layers[i](x)
  121. if g is not None:
  122. cond_offset = i * 2 * self.hidden_channels
  123. g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
  124. else:
  125. g_l = torch.zeros_like(x_in)
  126. acts = fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
  127. acts = self.drop(acts)
  128. res_skip_acts = self.res_skip_layers[i](acts)
  129. if i < self.n_layers - 1:
  130. res_acts = res_skip_acts[:, : self.hidden_channels, :]
  131. x = (x + res_acts) * x_mask
  132. output = output + res_skip_acts[:, self.hidden_channels :, :]
  133. else:
  134. output = output + res_skip_acts
  135. return output * x_mask
  136. def remove_weight_norm(self):
  137. if self.gin_channels != 0:
  138. torch.nn.utils.remove_weight_norm(self.cond_layer)
  139. for l in self.in_layers:
  140. torch.nn.utils.remove_weight_norm(l)
  141. for l in self.res_skip_layers:
  142. torch.nn.utils.remove_weight_norm(l)
  143. class ResBlock1(torch.nn.Module):
  144. def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
  145. super(ResBlock1, self).__init__()
  146. self.convs1 = nn.ModuleList(
  147. [
  148. weight_norm(
  149. Conv1d(
  150. channels,
  151. channels,
  152. kernel_size,
  153. 1,
  154. dilation=dilation[0],
  155. padding=get_padding(kernel_size, dilation[0]),
  156. )
  157. ),
  158. weight_norm(
  159. Conv1d(
  160. channels,
  161. channels,
  162. kernel_size,
  163. 1,
  164. dilation=dilation[1],
  165. padding=get_padding(kernel_size, dilation[1]),
  166. )
  167. ),
  168. weight_norm(
  169. Conv1d(
  170. channels,
  171. channels,
  172. kernel_size,
  173. 1,
  174. dilation=dilation[2],
  175. padding=get_padding(kernel_size, dilation[2]),
  176. )
  177. ),
  178. ]
  179. )
  180. self.convs1.apply(init_weights)
  181. self.convs2 = nn.ModuleList(
  182. [
  183. weight_norm(
  184. Conv1d(
  185. channels,
  186. channels,
  187. kernel_size,
  188. 1,
  189. dilation=1,
  190. padding=get_padding(kernel_size, 1),
  191. )
  192. ),
  193. weight_norm(
  194. Conv1d(
  195. channels,
  196. channels,
  197. kernel_size,
  198. 1,
  199. dilation=1,
  200. padding=get_padding(kernel_size, 1),
  201. )
  202. ),
  203. weight_norm(
  204. Conv1d(
  205. channels,
  206. channels,
  207. kernel_size,
  208. 1,
  209. dilation=1,
  210. padding=get_padding(kernel_size, 1),
  211. )
  212. ),
  213. ]
  214. )
  215. self.convs2.apply(init_weights)
  216. def forward(self, x, x_mask=None):
  217. for c1, c2 in zip(self.convs1, self.convs2):
  218. xt = F.leaky_relu(x, LRELU_SLOPE)
  219. if x_mask is not None:
  220. xt = xt * x_mask
  221. xt = c1(xt)
  222. xt = F.leaky_relu(xt, LRELU_SLOPE)
  223. if x_mask is not None:
  224. xt = xt * x_mask
  225. xt = c2(xt)
  226. x = xt + x
  227. if x_mask is not None:
  228. x = x * x_mask
  229. return x
  230. def remove_weight_norm(self):
  231. for l in self.convs1:
  232. remove_weight_norm(l)
  233. for l in self.convs2:
  234. remove_weight_norm(l)
  235. class ResBlock2(torch.nn.Module):
  236. def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
  237. super(ResBlock2, self).__init__()
  238. self.convs = nn.ModuleList(
  239. [
  240. weight_norm(
  241. Conv1d(
  242. channels,
  243. channels,
  244. kernel_size,
  245. 1,
  246. dilation=dilation[0],
  247. padding=get_padding(kernel_size, dilation[0]),
  248. )
  249. ),
  250. weight_norm(
  251. Conv1d(
  252. channels,
  253. channels,
  254. kernel_size,
  255. 1,
  256. dilation=dilation[1],
  257. padding=get_padding(kernel_size, dilation[1]),
  258. )
  259. ),
  260. ]
  261. )
  262. self.convs.apply(init_weights)
  263. def forward(self, x, x_mask=None):
  264. for c in self.convs:
  265. xt = F.leaky_relu(x, LRELU_SLOPE)
  266. if x_mask is not None:
  267. xt = xt * x_mask
  268. xt = c(xt)
  269. x = xt + x
  270. if x_mask is not None:
  271. x = x * x_mask
  272. return x
  273. def remove_weight_norm(self):
  274. for l in self.convs:
  275. remove_weight_norm(l)
  276. class Flip(nn.Module):
  277. def forward(self, x, *args, reverse=False, **kwargs):
  278. x = torch.flip(x, [1])
  279. if not reverse:
  280. logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
  281. return x, logdet
  282. else:
  283. return x
  284. class ResidualCouplingLayer(nn.Module):
  285. def __init__(
  286. self,
  287. channels,
  288. hidden_channels,
  289. kernel_size,
  290. dilation_rate,
  291. n_layers,
  292. p_dropout=0,
  293. gin_channels=0,
  294. mean_only=False,
  295. ):
  296. assert channels % 2 == 0, "channels should be divisible by 2"
  297. super().__init__()
  298. self.channels = channels
  299. self.hidden_channels = hidden_channels
  300. self.kernel_size = kernel_size
  301. self.dilation_rate = dilation_rate
  302. self.n_layers = n_layers
  303. self.half_channels = channels // 2
  304. self.mean_only = mean_only
  305. self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
  306. self.enc = WN(
  307. hidden_channels,
  308. kernel_size,
  309. dilation_rate,
  310. n_layers,
  311. p_dropout=p_dropout,
  312. gin_channels=gin_channels,
  313. )
  314. self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
  315. self.post.weight.data.zero_()
  316. self.post.bias.data.zero_()
  317. def forward(self, x, x_mask, g=None, reverse=False):
  318. x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
  319. h = self.pre(x0) * x_mask
  320. h = self.enc(h, x_mask, g=g)
  321. stats = self.post(h) * x_mask
  322. if not self.mean_only:
  323. m, logs = torch.split(stats, [self.half_channels] * 2, 1)
  324. else:
  325. m = stats
  326. logs = torch.zeros_like(m)
  327. if not reverse:
  328. x1 = m + x1 * torch.exp(logs) * x_mask
  329. x = torch.cat([x0, x1], 1)
  330. logdet = torch.sum(logs, [1, 2])
  331. return x, logdet
  332. else:
  333. x1 = (x1 - m) * torch.exp(-logs) * x_mask
  334. x = torch.cat([x0, x1], 1)
  335. return x
  336. class LinearNorm(nn.Module):
  337. def __init__(
  338. self,
  339. in_channels,
  340. out_channels,
  341. bias=True,
  342. spectral_norm=False,
  343. ):
  344. super(LinearNorm, self).__init__()
  345. self.fc = nn.Linear(in_channels, out_channels, bias)
  346. if spectral_norm:
  347. self.fc = nn.utils.spectral_norm(self.fc)
  348. def forward(self, input):
  349. out = self.fc(input)
  350. return out
  351. class Mish(nn.Module):
  352. def __init__(self):
  353. super(Mish, self).__init__()
  354. def forward(self, x):
  355. return x * torch.tanh(F.softplus(x))
  356. class Conv1dGLU(nn.Module):
  357. """
  358. Conv1d + GLU(Gated Linear Unit) with residual connection.
  359. For GLU refer to https://arxiv.org/abs/1612.08083 paper.
  360. """
  361. def __init__(self, in_channels, out_channels, kernel_size, dropout):
  362. super(Conv1dGLU, self).__init__()
  363. self.out_channels = out_channels
  364. self.conv1 = ConvNorm(in_channels, 2 * out_channels, kernel_size=kernel_size)
  365. self.dropout = nn.Dropout(dropout)
  366. def forward(self, x):
  367. residual = x
  368. x = self.conv1(x)
  369. x1, x2 = torch.split(x, split_size_or_sections=self.out_channels, dim=1)
  370. x = x1 * torch.sigmoid(x2)
  371. x = residual + self.dropout(x)
  372. return x
  373. class ConvNorm(nn.Module):
  374. def __init__(
  375. self,
  376. in_channels,
  377. out_channels,
  378. kernel_size=1,
  379. stride=1,
  380. padding=None,
  381. dilation=1,
  382. bias=True,
  383. spectral_norm=False,
  384. ):
  385. super(ConvNorm, self).__init__()
  386. if padding is None:
  387. assert kernel_size % 2 == 1
  388. padding = int(dilation * (kernel_size - 1) / 2)
  389. self.conv = torch.nn.Conv1d(
  390. in_channels,
  391. out_channels,
  392. kernel_size=kernel_size,
  393. stride=stride,
  394. padding=padding,
  395. dilation=dilation,
  396. bias=bias,
  397. )
  398. if spectral_norm:
  399. self.conv = nn.utils.spectral_norm(self.conv)
  400. def forward(self, input):
  401. out = self.conv(input)
  402. return out
  403. class MultiHeadAttention(nn.Module):
  404. """Multi-Head Attention module"""
  405. def __init__(self, n_head, d_model, d_k, d_v, dropout=0.0, spectral_norm=False):
  406. super().__init__()
  407. self.n_head = n_head
  408. self.d_k = d_k
  409. self.d_v = d_v
  410. self.w_qs = nn.Linear(d_model, n_head * d_k)
  411. self.w_ks = nn.Linear(d_model, n_head * d_k)
  412. self.w_vs = nn.Linear(d_model, n_head * d_v)
  413. self.attention = ScaledDotProductAttention(
  414. temperature=np.power(d_model, 0.5), dropout=dropout
  415. )
  416. self.fc = nn.Linear(n_head * d_v, d_model)
  417. self.dropout = nn.Dropout(dropout)
  418. if spectral_norm:
  419. self.w_qs = nn.utils.spectral_norm(self.w_qs)
  420. self.w_ks = nn.utils.spectral_norm(self.w_ks)
  421. self.w_vs = nn.utils.spectral_norm(self.w_vs)
  422. self.fc = nn.utils.spectral_norm(self.fc)
  423. def forward(self, x, mask=None):
  424. d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
  425. sz_b, len_x, _ = x.size()
  426. residual = x
  427. q = self.w_qs(x).view(sz_b, len_x, n_head, d_k)
  428. k = self.w_ks(x).view(sz_b, len_x, n_head, d_k)
  429. v = self.w_vs(x).view(sz_b, len_x, n_head, d_v)
  430. q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_x, d_k) # (n*b) x lq x dk
  431. k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_x, d_k) # (n*b) x lk x dk
  432. v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_x, d_v) # (n*b) x lv x dv
  433. if mask is not None:
  434. slf_mask = mask.repeat(n_head, 1, 1) # (n*b) x .. x ..
  435. else:
  436. slf_mask = None
  437. output, attn = self.attention(q, k, v, mask=slf_mask)
  438. output = output.view(n_head, sz_b, len_x, d_v)
  439. output = (
  440. output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_x, -1)
  441. ) # b x lq x (n*dv)
  442. output = self.fc(output)
  443. output = self.dropout(output) + residual
  444. return output, attn
  445. class ScaledDotProductAttention(nn.Module):
  446. """Scaled Dot-Product Attention"""
  447. def __init__(self, temperature, dropout):
  448. super().__init__()
  449. self.temperature = temperature
  450. self.softmax = nn.Softmax(dim=2)
  451. self.dropout = nn.Dropout(dropout)
  452. def forward(self, q, k, v, mask=None):
  453. attn = torch.bmm(q, k.transpose(1, 2))
  454. attn = attn / self.temperature
  455. if mask is not None:
  456. attn = attn.masked_fill(mask, -np.inf)
  457. attn = self.softmax(attn)
  458. p_attn = self.dropout(attn)
  459. output = torch.bmm(p_attn, v)
  460. return output, attn
  461. class MelStyleEncoder(nn.Module):
  462. """MelStyleEncoder"""
  463. def __init__(
  464. self,
  465. n_mel_channels=80,
  466. style_hidden=128,
  467. style_vector_dim=256,
  468. style_kernel_size=5,
  469. style_head=2,
  470. dropout=0.1,
  471. ):
  472. super(MelStyleEncoder, self).__init__()
  473. self.in_dim = n_mel_channels
  474. self.hidden_dim = style_hidden
  475. self.out_dim = style_vector_dim
  476. self.kernel_size = style_kernel_size
  477. self.n_head = style_head
  478. self.dropout = dropout
  479. self.spectral = nn.Sequential(
  480. LinearNorm(self.in_dim, self.hidden_dim),
  481. Mish(),
  482. nn.Dropout(self.dropout),
  483. LinearNorm(self.hidden_dim, self.hidden_dim),
  484. Mish(),
  485. nn.Dropout(self.dropout),
  486. )
  487. self.temporal = nn.Sequential(
  488. Conv1dGLU(self.hidden_dim, self.hidden_dim, self.kernel_size, self.dropout),
  489. Conv1dGLU(self.hidden_dim, self.hidden_dim, self.kernel_size, self.dropout),
  490. )
  491. self.slf_attn = MultiHeadAttention(
  492. self.n_head,
  493. self.hidden_dim,
  494. self.hidden_dim // self.n_head,
  495. self.hidden_dim // self.n_head,
  496. self.dropout,
  497. )
  498. self.fc = LinearNorm(self.hidden_dim, self.out_dim)
  499. def temporal_avg_pool(self, x, mask=None):
  500. if mask is None:
  501. out = torch.mean(x, dim=1)
  502. else:
  503. len_ = (~mask).sum(dim=1).unsqueeze(1)
  504. x = x.masked_fill(mask.unsqueeze(-1), 0)
  505. x = x.sum(dim=1)
  506. out = torch.div(x, len_)
  507. return out
  508. def forward(self, x, mask=None):
  509. x = x.transpose(1, 2)
  510. if mask is not None:
  511. mask = (mask.int() == 0).squeeze(1)
  512. max_len = x.shape[1]
  513. slf_attn_mask = (
  514. mask.unsqueeze(1).expand(-1, max_len, -1) if mask is not None else None
  515. )
  516. # spectral
  517. x = self.spectral(x)
  518. # temporal
  519. x = x.transpose(1, 2)
  520. x = self.temporal(x)
  521. x = x.transpose(1, 2)
  522. # self-attention
  523. if mask is not None:
  524. x = x.masked_fill(mask.unsqueeze(-1), 0)
  525. x, _ = self.slf_attn(x, mask=slf_attn_mask)
  526. # fc
  527. x = self.fc(x)
  528. # temoral average pooling
  529. w = self.temporal_avg_pool(x, mask=mask)
  530. return w.unsqueeze(-1)