modules.py 20 KB

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