attentions.py 12 KB

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