attentions.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. import math
  2. import torch
  3. from torch import nn
  4. from torch.nn import functional as F
  5. from module import commons
  6. from module.modules import LayerNorm
  7. class Encoder(nn.Module):
  8. def __init__(
  9. self,
  10. hidden_channels,
  11. filter_channels,
  12. n_heads,
  13. n_layers,
  14. kernel_size=1,
  15. p_dropout=0.0,
  16. window_size=4,
  17. isflow=False,
  18. **kwargs
  19. ):
  20. super().__init__()
  21. self.hidden_channels = hidden_channels
  22. self.filter_channels = filter_channels
  23. self.n_heads = n_heads
  24. self.n_layers = n_layers
  25. self.kernel_size = kernel_size
  26. self.p_dropout = p_dropout
  27. self.window_size = window_size
  28. self.drop = nn.Dropout(p_dropout)
  29. self.attn_layers = nn.ModuleList()
  30. self.norm_layers_1 = nn.ModuleList()
  31. self.ffn_layers = nn.ModuleList()
  32. self.norm_layers_2 = nn.ModuleList()
  33. for i in range(self.n_layers):
  34. self.attn_layers.append(
  35. MultiHeadAttention(
  36. hidden_channels,
  37. hidden_channels,
  38. n_heads,
  39. p_dropout=p_dropout,
  40. window_size=window_size,
  41. )
  42. )
  43. self.norm_layers_1.append(LayerNorm(hidden_channels))
  44. self.ffn_layers.append(
  45. FFN(
  46. hidden_channels,
  47. hidden_channels,
  48. filter_channels,
  49. kernel_size,
  50. p_dropout=p_dropout,
  51. )
  52. )
  53. self.norm_layers_2.append(LayerNorm(hidden_channels))
  54. if isflow:
  55. cond_layer = torch.nn.Conv1d(
  56. kwargs["gin_channels"], 2 * hidden_channels * n_layers, 1
  57. )
  58. self.cond_pre = torch.nn.Conv1d(hidden_channels, 2 * hidden_channels, 1)
  59. self.cond_layer = weight_norm_modules(cond_layer, name="weight")
  60. self.gin_channels = kwargs["gin_channels"]
  61. def forward(self, x, x_mask, g=None):
  62. attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
  63. x = x * x_mask
  64. if g is not None:
  65. g = self.cond_layer(g)
  66. for i in range(self.n_layers):
  67. if g is not None:
  68. x = self.cond_pre(x)
  69. cond_offset = i * 2 * self.hidden_channels
  70. g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
  71. x = commons.fused_add_tanh_sigmoid_multiply(
  72. x, g_l, torch.IntTensor([self.hidden_channels])
  73. )
  74. y = self.attn_layers[i](x, x, attn_mask)
  75. y = self.drop(y)
  76. x = self.norm_layers_1[i](x + y)
  77. y = self.ffn_layers[i](x, x_mask)
  78. y = self.drop(y)
  79. x = self.norm_layers_2[i](x + y)
  80. x = x * x_mask
  81. return x
  82. class Decoder(nn.Module):
  83. def __init__(
  84. self,
  85. hidden_channels,
  86. filter_channels,
  87. n_heads,
  88. n_layers,
  89. kernel_size=1,
  90. p_dropout=0.0,
  91. proximal_bias=False,
  92. proximal_init=True,
  93. **kwargs
  94. ):
  95. super().__init__()
  96. self.hidden_channels = hidden_channels
  97. self.filter_channels = filter_channels
  98. self.n_heads = n_heads
  99. self.n_layers = n_layers
  100. self.kernel_size = kernel_size
  101. self.p_dropout = p_dropout
  102. self.proximal_bias = proximal_bias
  103. self.proximal_init = proximal_init
  104. self.drop = nn.Dropout(p_dropout)
  105. self.self_attn_layers = nn.ModuleList()
  106. self.norm_layers_0 = nn.ModuleList()
  107. self.encdec_attn_layers = nn.ModuleList()
  108. self.norm_layers_1 = nn.ModuleList()
  109. self.ffn_layers = nn.ModuleList()
  110. self.norm_layers_2 = nn.ModuleList()
  111. for i in range(self.n_layers):
  112. self.self_attn_layers.append(
  113. MultiHeadAttention(
  114. hidden_channels,
  115. hidden_channels,
  116. n_heads,
  117. p_dropout=p_dropout,
  118. proximal_bias=proximal_bias,
  119. proximal_init=proximal_init,
  120. )
  121. )
  122. self.norm_layers_0.append(LayerNorm(hidden_channels))
  123. self.encdec_attn_layers.append(
  124. MultiHeadAttention(
  125. hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
  126. )
  127. )
  128. self.norm_layers_1.append(LayerNorm(hidden_channels))
  129. self.ffn_layers.append(
  130. FFN(
  131. hidden_channels,
  132. hidden_channels,
  133. filter_channels,
  134. kernel_size,
  135. p_dropout=p_dropout,
  136. causal=True,
  137. )
  138. )
  139. self.norm_layers_2.append(LayerNorm(hidden_channels))
  140. def forward(self, x, x_mask, h, h_mask):
  141. """
  142. x: decoder input
  143. h: encoder output
  144. """
  145. self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
  146. device=x.device, dtype=x.dtype
  147. )
  148. encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
  149. x = x * x_mask
  150. for i in range(self.n_layers):
  151. y = self.self_attn_layers[i](x, x, self_attn_mask)
  152. y = self.drop(y)
  153. x = self.norm_layers_0[i](x + y)
  154. y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
  155. y = self.drop(y)
  156. x = self.norm_layers_1[i](x + y)
  157. y = self.ffn_layers[i](x, x_mask)
  158. y = self.drop(y)
  159. x = self.norm_layers_2[i](x + y)
  160. x = x * x_mask
  161. return x
  162. class MultiHeadAttention(nn.Module):
  163. def __init__(
  164. self,
  165. channels,
  166. out_channels,
  167. n_heads,
  168. p_dropout=0.0,
  169. window_size=None,
  170. heads_share=True,
  171. block_length=None,
  172. proximal_bias=False,
  173. proximal_init=False,
  174. ):
  175. super().__init__()
  176. assert channels % n_heads == 0
  177. self.channels = channels
  178. self.out_channels = out_channels
  179. self.n_heads = n_heads
  180. self.p_dropout = p_dropout
  181. self.window_size = window_size
  182. self.heads_share = heads_share
  183. self.block_length = block_length
  184. self.proximal_bias = proximal_bias
  185. self.proximal_init = proximal_init
  186. self.attn = None
  187. self.k_channels = channels // n_heads
  188. self.conv_q = nn.Conv1d(channels, channels, 1)
  189. self.conv_k = nn.Conv1d(channels, channels, 1)
  190. self.conv_v = nn.Conv1d(channels, channels, 1)
  191. self.conv_o = nn.Conv1d(channels, out_channels, 1)
  192. self.drop = nn.Dropout(p_dropout)
  193. if window_size is not None:
  194. n_heads_rel = 1 if heads_share else n_heads
  195. rel_stddev = self.k_channels**-0.5
  196. self.emb_rel_k = nn.Parameter(
  197. torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
  198. * rel_stddev
  199. )
  200. self.emb_rel_v = nn.Parameter(
  201. torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
  202. * rel_stddev
  203. )
  204. nn.init.xavier_uniform_(self.conv_q.weight)
  205. nn.init.xavier_uniform_(self.conv_k.weight)
  206. nn.init.xavier_uniform_(self.conv_v.weight)
  207. if proximal_init:
  208. with torch.no_grad():
  209. self.conv_k.weight.copy_(self.conv_q.weight)
  210. self.conv_k.bias.copy_(self.conv_q.bias)
  211. def forward(self, x, c, attn_mask=None):
  212. q = self.conv_q(x)
  213. k = self.conv_k(c)
  214. v = self.conv_v(c)
  215. x, self.attn = self.attention(q, k, v, mask=attn_mask)
  216. x = self.conv_o(x)
  217. return x
  218. def attention(self, query, key, value, mask=None):
  219. # reshape [b, d, t] -> [b, n_h, t, d_k]
  220. b, d, t_s, t_t = (*key.size(), query.size(2))
  221. query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
  222. key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
  223. value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
  224. scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
  225. if self.window_size is not None:
  226. assert (
  227. t_s == t_t
  228. ), "Relative attention is only available for self-attention."
  229. key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
  230. rel_logits = self._matmul_with_relative_keys(
  231. query / math.sqrt(self.k_channels), key_relative_embeddings
  232. )
  233. scores_local = self._relative_position_to_absolute_position(rel_logits)
  234. scores = scores + scores_local
  235. if self.proximal_bias:
  236. assert t_s == t_t, "Proximal bias is only available for self-attention."
  237. scores = scores + self._attention_bias_proximal(t_s).to(
  238. device=scores.device, dtype=scores.dtype
  239. )
  240. if mask is not None:
  241. scores = scores.masked_fill(mask == 0, -1e4)
  242. if self.block_length is not None:
  243. assert (
  244. t_s == t_t
  245. ), "Local attention is only available for self-attention."
  246. block_mask = (
  247. torch.ones_like(scores)
  248. .triu(-self.block_length)
  249. .tril(self.block_length)
  250. )
  251. scores = scores.masked_fill(block_mask == 0, -1e4)
  252. p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
  253. p_attn = self.drop(p_attn)
  254. output = torch.matmul(p_attn, value)
  255. if self.window_size is not None:
  256. relative_weights = self._absolute_position_to_relative_position(p_attn)
  257. value_relative_embeddings = self._get_relative_embeddings(
  258. self.emb_rel_v, t_s
  259. )
  260. output = output + self._matmul_with_relative_values(
  261. relative_weights, value_relative_embeddings
  262. )
  263. output = (
  264. output.transpose(2, 3).contiguous().view(b, d, t_t)
  265. ) # [b, n_h, t_t, d_k] -> [b, d, t_t]
  266. return output, p_attn
  267. def _matmul_with_relative_values(self, x, y):
  268. """
  269. x: [b, h, l, m]
  270. y: [h or 1, m, d]
  271. ret: [b, h, l, d]
  272. """
  273. ret = torch.matmul(x, y.unsqueeze(0))
  274. return ret
  275. def _matmul_with_relative_keys(self, x, y):
  276. """
  277. x: [b, h, l, d]
  278. y: [h or 1, m, d]
  279. ret: [b, h, l, m]
  280. """
  281. ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
  282. return ret
  283. def _get_relative_embeddings(self, relative_embeddings, length):
  284. max_relative_position = 2 * self.window_size + 1
  285. # Pad first before slice to avoid using cond ops.
  286. pad_length = max(length - (self.window_size + 1), 0)
  287. slice_start_position = max((self.window_size + 1) - length, 0)
  288. slice_end_position = slice_start_position + 2 * length - 1
  289. if pad_length > 0:
  290. padded_relative_embeddings = F.pad(
  291. relative_embeddings,
  292. commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
  293. )
  294. else:
  295. padded_relative_embeddings = relative_embeddings
  296. used_relative_embeddings = padded_relative_embeddings[
  297. :, slice_start_position:slice_end_position
  298. ]
  299. return used_relative_embeddings
  300. def _relative_position_to_absolute_position(self, x):
  301. """
  302. x: [b, h, l, 2*l-1]
  303. ret: [b, h, l, l]
  304. """
  305. batch, heads, length, _ = x.size()
  306. # Concat columns of pad to shift from relative to absolute indexing.
  307. x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
  308. # Concat extra elements so to add up to shape (len+1, 2*len-1).
  309. x_flat = x.view([batch, heads, length * 2 * length])
  310. x_flat = F.pad(
  311. x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
  312. )
  313. # Reshape and slice out the padded elements.
  314. x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
  315. :, :, :length, length - 1 :
  316. ]
  317. return x_final
  318. def _absolute_position_to_relative_position(self, x):
  319. """
  320. x: [b, h, l, l]
  321. ret: [b, h, l, 2*l-1]
  322. """
  323. batch, heads, length, _ = x.size()
  324. # padd along column
  325. x = F.pad(
  326. x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
  327. )
  328. x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
  329. # add 0's in the beginning that will skew the elements after reshape
  330. x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
  331. x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
  332. return x_final
  333. def _attention_bias_proximal(self, length):
  334. """Bias for self-attention to encourage attention to close positions.
  335. Args:
  336. length: an integer scalar.
  337. Returns:
  338. a Tensor with shape [1, 1, length, length]
  339. """
  340. r = torch.arange(length, dtype=torch.float32)
  341. diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
  342. return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
  343. class FFN(nn.Module):
  344. def __init__(
  345. self,
  346. in_channels,
  347. out_channels,
  348. filter_channels,
  349. kernel_size,
  350. p_dropout=0.0,
  351. activation=None,
  352. causal=False,
  353. ):
  354. super().__init__()
  355. self.in_channels = in_channels
  356. self.out_channels = out_channels
  357. self.filter_channels = filter_channels
  358. self.kernel_size = kernel_size
  359. self.p_dropout = p_dropout
  360. self.activation = activation
  361. self.causal = causal
  362. if causal:
  363. self.padding = self._causal_padding
  364. else:
  365. self.padding = self._same_padding
  366. self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
  367. self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
  368. self.drop = nn.Dropout(p_dropout)
  369. def forward(self, x, x_mask):
  370. x = self.conv_1(self.padding(x * x_mask))
  371. if self.activation == "gelu":
  372. x = x * torch.sigmoid(1.702 * x)
  373. else:
  374. x = torch.relu(x)
  375. x = self.drop(x)
  376. x = self.conv_2(self.padding(x * x_mask))
  377. return x * x_mask
  378. def _causal_padding(self, x):
  379. if self.kernel_size == 1:
  380. return x
  381. pad_l = self.kernel_size - 1
  382. pad_r = 0
  383. padding = [[0, 0], [0, 0], [pad_l, pad_r]]
  384. x = F.pad(x, commons.convert_pad_shape(padding))
  385. return x
  386. def _same_padding(self, x):
  387. if self.kernel_size == 1:
  388. return x
  389. pad_l = (self.kernel_size - 1) // 2
  390. pad_r = self.kernel_size // 2
  391. padding = [[0, 0], [0, 0], [pad_l, pad_r]]
  392. x = F.pad(x, commons.convert_pad_shape(padding))
  393. return x
  394. import torch.nn as nn
  395. from torch.nn.utils import remove_weight_norm, weight_norm
  396. class Depthwise_Separable_Conv1D(nn.Module):
  397. def __init__(
  398. self,
  399. in_channels,
  400. out_channels,
  401. kernel_size,
  402. stride=1,
  403. padding=0,
  404. dilation=1,
  405. bias=True,
  406. padding_mode="zeros", # TODO: refine this type
  407. device=None,
  408. dtype=None,
  409. ):
  410. super().__init__()
  411. self.depth_conv = nn.Conv1d(
  412. in_channels=in_channels,
  413. out_channels=in_channels,
  414. kernel_size=kernel_size,
  415. groups=in_channels,
  416. stride=stride,
  417. padding=padding,
  418. dilation=dilation,
  419. bias=bias,
  420. padding_mode=padding_mode,
  421. device=device,
  422. dtype=dtype,
  423. )
  424. self.point_conv = nn.Conv1d(
  425. in_channels=in_channels,
  426. out_channels=out_channels,
  427. kernel_size=1,
  428. bias=bias,
  429. device=device,
  430. dtype=dtype,
  431. )
  432. def forward(self, input):
  433. return self.point_conv(self.depth_conv(input))
  434. def weight_norm(self):
  435. self.depth_conv = weight_norm(self.depth_conv, name="weight")
  436. self.point_conv = weight_norm(self.point_conv, name="weight")
  437. def remove_weight_norm(self):
  438. self.depth_conv = remove_weight_norm(self.depth_conv, name="weight")
  439. self.point_conv = remove_weight_norm(self.point_conv, name="weight")
  440. class Depthwise_Separable_TransposeConv1D(nn.Module):
  441. def __init__(
  442. self,
  443. in_channels,
  444. out_channels,
  445. kernel_size,
  446. stride=1,
  447. padding=0,
  448. output_padding=0,
  449. bias=True,
  450. dilation=1,
  451. padding_mode="zeros", # TODO: refine this type
  452. device=None,
  453. dtype=None,
  454. ):
  455. super().__init__()
  456. self.depth_conv = nn.ConvTranspose1d(
  457. in_channels=in_channels,
  458. out_channels=in_channels,
  459. kernel_size=kernel_size,
  460. groups=in_channels,
  461. stride=stride,
  462. output_padding=output_padding,
  463. padding=padding,
  464. dilation=dilation,
  465. bias=bias,
  466. padding_mode=padding_mode,
  467. device=device,
  468. dtype=dtype,
  469. )
  470. self.point_conv = nn.Conv1d(
  471. in_channels=in_channels,
  472. out_channels=out_channels,
  473. kernel_size=1,
  474. bias=bias,
  475. device=device,
  476. dtype=dtype,
  477. )
  478. def forward(self, input):
  479. return self.point_conv(self.depth_conv(input))
  480. def weight_norm(self):
  481. self.depth_conv = weight_norm(self.depth_conv, name="weight")
  482. self.point_conv = weight_norm(self.point_conv, name="weight")
  483. def remove_weight_norm(self):
  484. remove_weight_norm(self.depth_conv, name="weight")
  485. remove_weight_norm(self.point_conv, name="weight")
  486. def weight_norm_modules(module, name="weight", dim=0):
  487. if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(
  488. module, Depthwise_Separable_TransposeConv1D
  489. ):
  490. module.weight_norm()
  491. return module
  492. else:
  493. return weight_norm(module, name, dim)
  494. def remove_weight_norm_modules(module, name="weight"):
  495. if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(
  496. module, Depthwise_Separable_TransposeConv1D
  497. ):
  498. module.remove_weight_norm()
  499. else:
  500. remove_weight_norm(module, name)
  501. class FFT(nn.Module):
  502. def __init__(
  503. self,
  504. hidden_channels,
  505. filter_channels,
  506. n_heads,
  507. n_layers=1,
  508. kernel_size=1,
  509. p_dropout=0.0,
  510. proximal_bias=False,
  511. proximal_init=True,
  512. isflow=False,
  513. **kwargs
  514. ):
  515. super().__init__()
  516. self.hidden_channels = hidden_channels
  517. self.filter_channels = filter_channels
  518. self.n_heads = n_heads
  519. self.n_layers = n_layers
  520. self.kernel_size = kernel_size
  521. self.p_dropout = p_dropout
  522. self.proximal_bias = proximal_bias
  523. self.proximal_init = proximal_init
  524. if isflow:
  525. cond_layer = torch.nn.Conv1d(
  526. kwargs["gin_channels"], 2 * hidden_channels * n_layers, 1
  527. )
  528. self.cond_pre = torch.nn.Conv1d(hidden_channels, 2 * hidden_channels, 1)
  529. self.cond_layer = weight_norm_modules(cond_layer, name="weight")
  530. self.gin_channels = kwargs["gin_channels"]
  531. self.drop = nn.Dropout(p_dropout)
  532. self.self_attn_layers = nn.ModuleList()
  533. self.norm_layers_0 = nn.ModuleList()
  534. self.ffn_layers = nn.ModuleList()
  535. self.norm_layers_1 = nn.ModuleList()
  536. for i in range(self.n_layers):
  537. self.self_attn_layers.append(
  538. MultiHeadAttention(
  539. hidden_channels,
  540. hidden_channels,
  541. n_heads,
  542. p_dropout=p_dropout,
  543. proximal_bias=proximal_bias,
  544. proximal_init=proximal_init,
  545. )
  546. )
  547. self.norm_layers_0.append(LayerNorm(hidden_channels))
  548. self.ffn_layers.append(
  549. FFN(
  550. hidden_channels,
  551. hidden_channels,
  552. filter_channels,
  553. kernel_size,
  554. p_dropout=p_dropout,
  555. causal=True,
  556. )
  557. )
  558. self.norm_layers_1.append(LayerNorm(hidden_channels))
  559. def forward(self, x, x_mask, g=None):
  560. """
  561. x: decoder input
  562. h: encoder output
  563. """
  564. if g is not None:
  565. g = self.cond_layer(g)
  566. self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
  567. device=x.device, dtype=x.dtype
  568. )
  569. x = x * x_mask
  570. for i in range(self.n_layers):
  571. if g is not None:
  572. x = self.cond_pre(x)
  573. cond_offset = i * 2 * self.hidden_channels
  574. g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
  575. x = commons.fused_add_tanh_sigmoid_multiply(
  576. x, g_l, torch.IntTensor([self.hidden_channels])
  577. )
  578. y = self.self_attn_layers[i](x, x, self_attn_mask)
  579. y = self.drop(y)
  580. x = self.norm_layers_0[i](x + y)
  581. y = self.ffn_layers[i](x, x_mask)
  582. y = self.drop(y)
  583. x = self.norm_layers_1[i](x + y)
  584. x = x * x_mask
  585. return x
  586. class TransformerCouplingLayer(nn.Module):
  587. def __init__(
  588. self,
  589. channels,
  590. hidden_channels,
  591. kernel_size,
  592. n_layers,
  593. n_heads,
  594. p_dropout=0,
  595. filter_channels=0,
  596. mean_only=False,
  597. wn_sharing_parameter=None,
  598. gin_channels=0,
  599. ):
  600. assert channels % 2 == 0, "channels should be divisible by 2"
  601. super().__init__()
  602. self.channels = channels
  603. self.hidden_channels = hidden_channels
  604. self.kernel_size = kernel_size
  605. self.n_layers = n_layers
  606. self.half_channels = channels // 2
  607. self.mean_only = mean_only
  608. self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
  609. self.enc = (
  610. Encoder(
  611. hidden_channels,
  612. filter_channels,
  613. n_heads,
  614. n_layers,
  615. kernel_size,
  616. p_dropout,
  617. isflow=True,
  618. gin_channels=gin_channels,
  619. )
  620. if wn_sharing_parameter is None
  621. else wn_sharing_parameter
  622. )
  623. self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
  624. self.post.weight.data.zero_()
  625. self.post.bias.data.zero_()
  626. def forward(self, x, x_mask, g=None, reverse=False):
  627. x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
  628. h = self.pre(x0) * x_mask
  629. h = self.enc(h, x_mask, g=g)
  630. stats = self.post(h) * x_mask
  631. if not self.mean_only:
  632. m, logs = torch.split(stats, [self.half_channels] * 2, 1)
  633. else:
  634. m = stats
  635. logs = torch.zeros_like(m)
  636. if not reverse:
  637. x1 = m + x1 * torch.exp(logs) * x_mask
  638. x = torch.cat([x0, x1], 1)
  639. logdet = torch.sum(logs, [1, 2])
  640. return x, logdet
  641. else:
  642. x1 = (x1 - m) * torch.exp(-logs) * x_mask
  643. x = torch.cat([x0, x1], 1)
  644. return x