attentions_onnx.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 LayerNorm(nn.Module):
  8. def __init__(self, channels, eps=1e-5):
  9. super().__init__()
  10. self.channels = channels
  11. self.eps = eps
  12. self.gamma = nn.Parameter(torch.ones(channels))
  13. self.beta = nn.Parameter(torch.zeros(channels))
  14. def forward(self, x):
  15. x = x.transpose(1, -1)
  16. x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
  17. return x.transpose(1, -1)
  18. @torch.jit.script
  19. def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
  20. n_channels_int = n_channels[0]
  21. in_act = input_a + input_b
  22. t_act = torch.tanh(in_act[:, :n_channels_int, :])
  23. s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
  24. acts = t_act * s_act
  25. return acts
  26. class Encoder(nn.Module):
  27. def __init__(
  28. self,
  29. hidden_channels,
  30. filter_channels,
  31. n_heads,
  32. n_layers,
  33. kernel_size=1,
  34. p_dropout=0.0,
  35. window_size=4,
  36. isflow=True,
  37. **kwargs
  38. ):
  39. super().__init__()
  40. self.hidden_channels = hidden_channels
  41. self.filter_channels = filter_channels
  42. self.n_heads = n_heads
  43. self.n_layers = n_layers
  44. self.kernel_size = kernel_size
  45. self.p_dropout = p_dropout
  46. self.window_size = window_size
  47. # if isflow:
  48. # cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
  49. # self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
  50. # self.cond_layer = weight_norm(cond_layer, name='weight')
  51. # self.gin_channels = 256
  52. self.cond_layer_idx = self.n_layers
  53. if "gin_channels" in kwargs:
  54. self.gin_channels = kwargs["gin_channels"]
  55. if self.gin_channels != 0:
  56. self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
  57. # vits2 says 3rd block, so idx is 2 by default
  58. self.cond_layer_idx = (
  59. kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
  60. )
  61. logging.debug(self.gin_channels, self.cond_layer_idx)
  62. assert (
  63. self.cond_layer_idx < self.n_layers
  64. ), "cond_layer_idx should be less than n_layers"
  65. self.drop = nn.Dropout(p_dropout)
  66. self.attn_layers = nn.ModuleList()
  67. self.norm_layers_1 = nn.ModuleList()
  68. self.ffn_layers = nn.ModuleList()
  69. self.norm_layers_2 = nn.ModuleList()
  70. for i in range(self.n_layers):
  71. self.attn_layers.append(
  72. MultiHeadAttention(
  73. hidden_channels,
  74. hidden_channels,
  75. n_heads,
  76. p_dropout=p_dropout,
  77. window_size=window_size,
  78. )
  79. )
  80. self.norm_layers_1.append(LayerNorm(hidden_channels))
  81. self.ffn_layers.append(
  82. FFN(
  83. hidden_channels,
  84. hidden_channels,
  85. filter_channels,
  86. kernel_size,
  87. p_dropout=p_dropout,
  88. )
  89. )
  90. self.norm_layers_2.append(LayerNorm(hidden_channels))
  91. def forward(self, x, x_mask, g=None):
  92. attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
  93. x = x * x_mask
  94. for i in range(self.n_layers):
  95. if i == self.cond_layer_idx and g is not None:
  96. g = self.spk_emb_linear(g.transpose(1, 2))
  97. g = g.transpose(1, 2)
  98. x = x + g
  99. x = x * x_mask
  100. y = self.attn_layers[i](x, x, attn_mask)
  101. y = self.drop(y)
  102. x = self.norm_layers_1[i](x + y)
  103. y = self.ffn_layers[i](x, x_mask)
  104. y = self.drop(y)
  105. x = self.norm_layers_2[i](x + y)
  106. x = x * x_mask
  107. return x
  108. class MultiHeadAttention(nn.Module):
  109. def __init__(
  110. self,
  111. channels,
  112. out_channels,
  113. n_heads,
  114. p_dropout=0.0,
  115. window_size=None,
  116. heads_share=True,
  117. block_length=None,
  118. proximal_bias=False,
  119. proximal_init=False,
  120. ):
  121. super().__init__()
  122. assert channels % n_heads == 0
  123. self.channels = channels
  124. self.out_channels = out_channels
  125. self.n_heads = n_heads
  126. self.p_dropout = p_dropout
  127. self.window_size = window_size
  128. self.heads_share = heads_share
  129. self.block_length = block_length
  130. self.proximal_bias = proximal_bias
  131. self.proximal_init = proximal_init
  132. self.attn = None
  133. self.k_channels = channels // n_heads
  134. self.conv_q = nn.Conv1d(channels, channels, 1)
  135. self.conv_k = nn.Conv1d(channels, channels, 1)
  136. self.conv_v = nn.Conv1d(channels, channels, 1)
  137. self.conv_o = nn.Conv1d(channels, out_channels, 1)
  138. self.drop = nn.Dropout(p_dropout)
  139. if window_size is not None:
  140. n_heads_rel = 1 if heads_share else n_heads
  141. rel_stddev = self.k_channels**-0.5
  142. self.emb_rel_k = nn.Parameter(
  143. torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
  144. * rel_stddev
  145. )
  146. self.emb_rel_v = nn.Parameter(
  147. torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
  148. * rel_stddev
  149. )
  150. nn.init.xavier_uniform_(self.conv_q.weight)
  151. nn.init.xavier_uniform_(self.conv_k.weight)
  152. nn.init.xavier_uniform_(self.conv_v.weight)
  153. if proximal_init:
  154. with torch.no_grad():
  155. self.conv_k.weight.copy_(self.conv_q.weight)
  156. self.conv_k.bias.copy_(self.conv_q.bias)
  157. def forward(self, x, c, attn_mask=None):
  158. q = self.conv_q(x)
  159. k = self.conv_k(c)
  160. v = self.conv_v(c)
  161. x, self.attn = self.attention(q, k, v, mask=attn_mask)
  162. x = self.conv_o(x)
  163. return x
  164. def attention(self, query, key, value, mask=None):
  165. # reshape [b, d, t] -> [b, n_h, t, d_k]
  166. b, d, t_s, _ = (*key.size(), query.size(2))
  167. query = query.view(b, self.n_heads, self.k_channels, -1).transpose(2, 3)
  168. key = key.view(b, self.n_heads, self.k_channels, -1).transpose(2, 3)
  169. value = value.view(b, self.n_heads, self.k_channels, -1).transpose(2, 3)
  170. scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
  171. if self.window_size is not None:
  172. key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
  173. rel_logits = self._matmul_with_relative_keys(query / math.sqrt(self.k_channels), key_relative_embeddings)
  174. scores_local = self._relative_position_to_absolute_position(rel_logits)
  175. scores = scores + scores_local
  176. if mask is not None:
  177. scores = scores.masked_fill(mask == 0, -1e4)
  178. p_attn = F.softmax(scores, dim=-1)
  179. p_attn = self.drop(p_attn)
  180. output = torch.matmul(p_attn, value)
  181. if self.window_size is not None:
  182. relative_weights = self._absolute_position_to_relative_position(p_attn)
  183. value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
  184. output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
  185. output = (output.transpose(2, 3).contiguous().view(b, d, -1))
  186. return output, p_attn
  187. def _matmul_with_relative_values(self, x, y):
  188. """
  189. x: [b, h, l, m]
  190. y: [h or 1, m, d]
  191. ret: [b, h, l, d]
  192. """
  193. ret = torch.matmul(x, y.unsqueeze(0))
  194. return ret
  195. def _matmul_with_relative_keys(self, x, y):
  196. """
  197. x: [b, h, l, d]
  198. y: [h or 1, m, d]
  199. ret: [b, h, l, m]
  200. """
  201. ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
  202. return ret
  203. def _get_relative_embeddings(self, relative_embeddings, length):
  204. max_relative_position = 2 * self.window_size + 1
  205. # Pad first before slice to avoid using cond ops.
  206. pad_l = torch.zeros((1), dtype = torch.int64) + length - (self.window_size + 1)
  207. pad_s = torch.zeros((1), dtype = torch.int64) + (self.window_size + 1) - length
  208. pad_length = torch.max(pad_l, other=torch.zeros((1), dtype = torch.int64))
  209. slice_start_position = torch.max(pad_s, other=torch.zeros((1), dtype = torch.int64))
  210. slice_end_position = slice_start_position + 2 * length - 1
  211. padded_relative_embeddings = F.pad(
  212. relative_embeddings,
  213. commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
  214. )
  215. used_relative_embeddings = padded_relative_embeddings[
  216. :, slice_start_position:slice_end_position
  217. ]
  218. return used_relative_embeddings
  219. def _relative_position_to_absolute_position(self, x):
  220. """
  221. x: [b, h, l, 2*l-1]
  222. ret: [b, h, l, l]
  223. """
  224. batch, heads, length, _ = x.size()
  225. # Concat columns of pad to shift from relative to absolute indexing.
  226. x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
  227. # Concat extra elements so to add up to shape (len+1, 2*len-1).
  228. x_flat = x.view([batch, heads, length * 2 * length])
  229. x_flat = F.pad(
  230. x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
  231. )
  232. # Reshape and slice out the padded elements.
  233. x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
  234. :, :, :length, length - 1 :
  235. ]
  236. return x_final
  237. def _absolute_position_to_relative_position(self, x):
  238. """
  239. x: [b, h, l, l]
  240. ret: [b, h, l, 2*l-1]
  241. """
  242. batch, heads, length, _ = x.size()
  243. # padd along column
  244. x = F.pad(
  245. x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
  246. )
  247. x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
  248. # add 0's in the beginning that will skew the elements after reshape
  249. x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
  250. x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
  251. return x_final
  252. def _attention_bias_proximal(self, length):
  253. """Bias for self-attention to encourage attention to close positions.
  254. Args:
  255. length: an integer scalar.
  256. Returns:
  257. a Tensor with shape [1, 1, length, length]
  258. """
  259. r = torch.arange(length, dtype=torch.float32)
  260. diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
  261. return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
  262. class FFN(nn.Module):
  263. def __init__(
  264. self,
  265. in_channels,
  266. out_channels,
  267. filter_channels,
  268. kernel_size,
  269. p_dropout=0.0,
  270. activation=None,
  271. causal=False,
  272. ):
  273. super().__init__()
  274. self.in_channels = in_channels
  275. self.out_channels = out_channels
  276. self.filter_channels = filter_channels
  277. self.kernel_size = kernel_size
  278. self.p_dropout = p_dropout
  279. self.activation = activation
  280. self.causal = causal
  281. if causal:
  282. self.padding = self._causal_padding
  283. else:
  284. self.padding = self._same_padding
  285. self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
  286. self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
  287. self.drop = nn.Dropout(p_dropout)
  288. def forward(self, x, x_mask):
  289. x = self.conv_1(self.padding(x * x_mask))
  290. if self.activation == "gelu":
  291. x = x * torch.sigmoid(1.702 * x)
  292. else:
  293. x = torch.relu(x)
  294. x = self.drop(x)
  295. x = self.conv_2(self.padding(x * x_mask))
  296. return x * x_mask
  297. def _causal_padding(self, x):
  298. if self.kernel_size == 1:
  299. return x
  300. pad_l = self.kernel_size - 1
  301. pad_r = 0
  302. padding = [[0, 0], [0, 0], [pad_l, pad_r]]
  303. x = F.pad(x, commons.convert_pad_shape(padding))
  304. return x
  305. def _same_padding(self, x):
  306. if self.kernel_size == 1:
  307. return x
  308. pad_l = (self.kernel_size - 1) // 2
  309. pad_r = self.kernel_size // 2
  310. padding = [[0, 0], [0, 0], [pad_l, pad_r]]
  311. x = F.pad(x, commons.convert_pad_shape(padding))
  312. return x