CoolFace
Apppublic

hanfish/LSai

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
attentions.py514 linesDownload Raw Back to module
1import math2import torch3from torch import nn4from torch.nn import functional as F5 6from module import commons7from module. modules import LayerNorm8   9 10class Encoder(nn.Module):11  def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4,isflow=False, **kwargs):12    super().__init__()13    self.hidden_channels = hidden_channels14    self.filter_channels = filter_channels15    self.n_heads = n_heads16    self.n_layers = n_layers17    self.kernel_size = kernel_size18    self.p_dropout = p_dropout19    self.window_size = window_size20 21    self.drop = nn.Dropout(p_dropout)22    self.attn_layers = nn.ModuleList()23    self.norm_layers_1 = nn.ModuleList()24    self.ffn_layers = nn.ModuleList()25    self.norm_layers_2 = nn.ModuleList()26    for i in range(self.n_layers):27      self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))28      self.norm_layers_1.append(LayerNorm(hidden_channels))29      self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))30      self.norm_layers_2.append(LayerNorm(hidden_channels))31    if isflow:32      cond_layer = torch.nn.Conv1d(kwargs["gin_channels"], 2*hidden_channels*n_layers, 1)33      self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)34      self.cond_layer = weight_norm_modules(cond_layer, name='weight')35      self.gin_channels = kwargs["gin_channels"]36  def forward(self, x, x_mask, g=None):37    attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)38    x = x * x_mask39    if g is not None:40      g = self.cond_layer(g)41 42    for i in range(self.n_layers):43      if g is not None:44        x = self.cond_pre(x)45        cond_offset = i * 2 * self.hidden_channels46        g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]47        x = commons.fused_add_tanh_sigmoid_multiply(48          x,49          g_l,50          torch.IntTensor([self.hidden_channels]))51      y = self.attn_layers[i](x, x, attn_mask)52      y = self.drop(y)53      x = self.norm_layers_1[i](x + y)54 55      y = self.ffn_layers[i](x, x_mask)56      y = self.drop(y)57      x = self.norm_layers_2[i](x + y)58    x = x * x_mask59    return x60 61 62class Decoder(nn.Module):63  def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):64    super().__init__()65    self.hidden_channels = hidden_channels66    self.filter_channels = filter_channels67    self.n_heads = n_heads68    self.n_layers = n_layers69    self.kernel_size = kernel_size70    self.p_dropout = p_dropout71    self.proximal_bias = proximal_bias72    self.proximal_init = proximal_init73 74    self.drop = nn.Dropout(p_dropout)75    self.self_attn_layers = nn.ModuleList()76    self.norm_layers_0 = nn.ModuleList()77    self.encdec_attn_layers = nn.ModuleList()78    self.norm_layers_1 = nn.ModuleList()79    self.ffn_layers = nn.ModuleList()80    self.norm_layers_2 = nn.ModuleList()81    for i in range(self.n_layers):82      self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))83      self.norm_layers_0.append(LayerNorm(hidden_channels))84      self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))85      self.norm_layers_1.append(LayerNorm(hidden_channels))86      self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))87      self.norm_layers_2.append(LayerNorm(hidden_channels))88 89  def forward(self, x, x_mask, h, h_mask):90    """91    x: decoder input92    h: encoder output93    """94    self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)95    encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)96    x = x * x_mask97    for i in range(self.n_layers):98      y = self.self_attn_layers[i](x, x, self_attn_mask)99      y = self.drop(y)100      x = self.norm_layers_0[i](x + y)101 102      y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)103      y = self.drop(y)104      x = self.norm_layers_1[i](x + y)105      106      y = self.ffn_layers[i](x, x_mask)107      y = self.drop(y)108      x = self.norm_layers_2[i](x + y)109    x = x * x_mask110    return x111 112 113class MultiHeadAttention(nn.Module):114  def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):115    super().__init__()116    assert channels % n_heads == 0117 118    self.channels = channels119    self.out_channels = out_channels120    self.n_heads = n_heads121    self.p_dropout = p_dropout122    self.window_size = window_size123    self.heads_share = heads_share124    self.block_length = block_length125    self.proximal_bias = proximal_bias126    self.proximal_init = proximal_init127    self.attn = None128 129    self.k_channels = channels // n_heads130    self.conv_q = nn.Conv1d(channels, channels, 1)131    self.conv_k = nn.Conv1d(channels, channels, 1)132    self.conv_v = nn.Conv1d(channels, channels, 1)133    self.conv_o = nn.Conv1d(channels, out_channels, 1)134    self.drop = nn.Dropout(p_dropout)135 136    if window_size is not None:137      n_heads_rel = 1 if heads_share else n_heads138      rel_stddev = self.k_channels**-0.5139      self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)140      self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)141 142    nn.init.xavier_uniform_(self.conv_q.weight)143    nn.init.xavier_uniform_(self.conv_k.weight)144    nn.init.xavier_uniform_(self.conv_v.weight)145    if proximal_init:146      with torch.no_grad():147        self.conv_k.weight.copy_(self.conv_q.weight)148        self.conv_k.bias.copy_(self.conv_q.bias)149      150  def forward(self, x, c, attn_mask=None):151    q = self.conv_q(x)152    k = self.conv_k(c)153    v = self.conv_v(c)154    155    x, self.attn = self.attention(q, k, v, mask=attn_mask)156 157    x = self.conv_o(x)158    return x159 160  def attention(self, query, key, value, mask=None):161    # reshape [b, d, t] -> [b, n_h, t, d_k]162    b, d, t_s, t_t = (*key.size(), query.size(2))163    query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)164    key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)165    value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)166 167    scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))168    if self.window_size is not None:169      assert t_s == t_t, "Relative attention is only available for self-attention."170      key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)171      rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)172      scores_local = self._relative_position_to_absolute_position(rel_logits)173      scores = scores + scores_local174    if self.proximal_bias:175      assert t_s == t_t, "Proximal bias is only available for self-attention."176      scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)177    if mask is not None:178      scores = scores.masked_fill(mask == 0, -1e4)179      if self.block_length is not None:180        assert t_s == t_t, "Local attention is only available for self-attention."181        block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)182        scores = scores.masked_fill(block_mask == 0, -1e4)183    p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]184    p_attn = self.drop(p_attn)185    output = torch.matmul(p_attn, value)186    if self.window_size is not None:187      relative_weights = self._absolute_position_to_relative_position(p_attn)188      value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)189      output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)190    output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]191    return output, p_attn192 193  def _matmul_with_relative_values(self, x, y):194    """195    x: [b, h, l, m]196    y: [h or 1, m, d]197    ret: [b, h, l, d]198    """199    ret = torch.matmul(x, y.unsqueeze(0))200    return ret201 202  def _matmul_with_relative_keys(self, x, y):203    """204    x: [b, h, l, d]205    y: [h or 1, m, d]206    ret: [b, h, l, m]207    """208    ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))209    return ret210 211  def _get_relative_embeddings(self, relative_embeddings, length):212    max_relative_position = 2 * self.window_size + 1213    # Pad first before slice to avoid using cond ops.214    pad_length = max(length - (self.window_size + 1), 0)215    slice_start_position = max((self.window_size + 1) - length, 0)216    slice_end_position = slice_start_position + 2 * length - 1217    if pad_length > 0:218      padded_relative_embeddings = F.pad(219          relative_embeddings,220          commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))221    else:222      padded_relative_embeddings = relative_embeddings223    used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]224    return used_relative_embeddings225 226  def _relative_position_to_absolute_position(self, x):227    """228    x: [b, h, l, 2*l-1]229    ret: [b, h, l, l]230    """231    batch, heads, length, _ = x.size()232    # Concat columns of pad to shift from relative to absolute indexing.233    x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))234 235    # Concat extra elements so to add up to shape (len+1, 2*len-1).236    x_flat = x.view([batch, heads, length * 2 * length])237    x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]]))238 239    # Reshape and slice out the padded elements.240    x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]241    return x_final242 243  def _absolute_position_to_relative_position(self, x):244    """245    x: [b, h, l, l]246    ret: [b, h, l, 2*l-1]247    """248    batch, heads, length, _ = x.size()249    # padd along column250    x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]]))251    x_flat = x.view([batch, heads, length**2 + length*(length -1)])252    # add 0's in the beginning that will skew the elements after reshape253    x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))254    x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]255    return x_final256 257  def _attention_bias_proximal(self, length):258    """Bias for self-attention to encourage attention to close positions.259    Args:260      length: an integer scalar.261    Returns:262      a Tensor with shape [1, 1, length, length]263    """264    r = torch.arange(length, dtype=torch.float32)265    diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)266    return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)267 268 269class FFN(nn.Module):270  def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):271    super().__init__()272    self.in_channels = in_channels273    self.out_channels = out_channels274    self.filter_channels = filter_channels275    self.kernel_size = kernel_size276    self.p_dropout = p_dropout277    self.activation = activation278    self.causal = causal279 280    if causal:281      self.padding = self._causal_padding282    else:283      self.padding = self._same_padding284 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 289  def forward(self, x, x_mask):290    x = self.conv_1(self.padding(x * x_mask))291    if self.activation == "gelu":292      x = x * torch.sigmoid(1.702 * x)293    else:294      x = torch.relu(x)295    x = self.drop(x)296    x = self.conv_2(self.padding(x * x_mask))297    return x * x_mask298  299  def _causal_padding(self, x):300    if self.kernel_size == 1:301      return x302    pad_l = self.kernel_size - 1303    pad_r = 0304    padding = [[0, 0], [0, 0], [pad_l, pad_r]]305    x = F.pad(x, commons.convert_pad_shape(padding))306    return x307 308  def _same_padding(self, x):309    if self.kernel_size == 1:310      return x311    pad_l = (self.kernel_size - 1) // 2312    pad_r = self.kernel_size // 2313    padding = [[0, 0], [0, 0], [pad_l, pad_r]]314    x = F.pad(x, commons.convert_pad_shape(padding))315    return x316 317 318import torch.nn as nn319from torch.nn.utils import remove_weight_norm, weight_norm320 321 322class Depthwise_Separable_Conv1D(nn.Module):323  def __init__(324          self,325          in_channels,326          out_channels,327          kernel_size,328          stride=1,329          padding=0,330          dilation=1,331          bias=True,332          padding_mode='zeros',  # TODO: refine this type333          device=None,334          dtype=None335  ):336    super().__init__()337    self.depth_conv = nn.Conv1d(in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size,338                                groups=in_channels, stride=stride, padding=padding, dilation=dilation, bias=bias,339                                padding_mode=padding_mode, device=device, dtype=dtype)340    self.point_conv = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias,341                                device=device, dtype=dtype)342 343  def forward(self, input):344    return self.point_conv(self.depth_conv(input))345 346  def weight_norm(self):347    self.depth_conv = weight_norm(self.depth_conv, name='weight')348    self.point_conv = weight_norm(self.point_conv, name='weight')349 350  def remove_weight_norm(self):351    self.depth_conv = remove_weight_norm(self.depth_conv, name='weight')352    self.point_conv = remove_weight_norm(self.point_conv, name='weight')353 354 355class Depthwise_Separable_TransposeConv1D(nn.Module):356  def __init__(357          self,358          in_channels,359          out_channels,360          kernel_size,361          stride=1,362          padding=0,363          output_padding=0,364          bias=True,365          dilation=1,366          padding_mode='zeros',  # TODO: refine this type367          device=None,368          dtype=None369  ):370    super().__init__()371    self.depth_conv = nn.ConvTranspose1d(in_channels=in_channels, out_channels=in_channels, kernel_size=kernel_size,372                                         groups=in_channels, stride=stride, output_padding=output_padding,373                                         padding=padding, dilation=dilation, bias=bias, padding_mode=padding_mode,374                                         device=device, dtype=dtype)375    self.point_conv = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias,376                                device=device, dtype=dtype)377 378  def forward(self, input):379    return self.point_conv(self.depth_conv(input))380 381  def weight_norm(self):382    self.depth_conv = weight_norm(self.depth_conv, name='weight')383    self.point_conv = weight_norm(self.point_conv, name='weight')384 385  def remove_weight_norm(self):386    remove_weight_norm(self.depth_conv, name='weight')387    remove_weight_norm(self.point_conv, name='weight')388 389 390def weight_norm_modules(module, name='weight', dim=0):391  if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(module, Depthwise_Separable_TransposeConv1D):392    module.weight_norm()393    return module394  else:395    return weight_norm(module, name, dim)396 397 398def remove_weight_norm_modules(module, name='weight'):399  if isinstance(module, Depthwise_Separable_Conv1D) or isinstance(module, Depthwise_Separable_TransposeConv1D):400    module.remove_weight_norm()401  else:402    remove_weight_norm(module, name)403 404 405class FFT(nn.Module):406  def __init__(self, hidden_channels, filter_channels, n_heads, n_layers=1, kernel_size=1, p_dropout=0.,407               proximal_bias=False, proximal_init=True, isflow = False, **kwargs):408    super().__init__()409    self.hidden_channels = hidden_channels410    self.filter_channels = filter_channels411    self.n_heads = n_heads412    self.n_layers = n_layers413    self.kernel_size = kernel_size414    self.p_dropout = p_dropout415    self.proximal_bias = proximal_bias416    self.proximal_init = proximal_init417    if isflow:418      cond_layer = torch.nn.Conv1d(kwargs["gin_channels"], 2*hidden_channels*n_layers, 1)419      self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)420      self.cond_layer = weight_norm_modules(cond_layer, name='weight')421      self.gin_channels = kwargs["gin_channels"]422    self.drop = nn.Dropout(p_dropout)423    self.self_attn_layers = nn.ModuleList()424    self.norm_layers_0 = nn.ModuleList()425    self.ffn_layers = nn.ModuleList()426    self.norm_layers_1 = nn.ModuleList()427    for i in range(self.n_layers):428      self.self_attn_layers.append(429        MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias,430                           proximal_init=proximal_init))431      self.norm_layers_0.append(LayerNorm(hidden_channels))432      self.ffn_layers.append(433        FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))434      self.norm_layers_1.append(LayerNorm(hidden_channels))435 436  def forward(self, x, x_mask, g = None):437    """438    x: decoder input439    h: encoder output440    """441    if g is not None:442      g = self.cond_layer(g)443 444    self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)445    x = x * x_mask446    for i in range(self.n_layers):447      if g is not None:448        x = self.cond_pre(x)449        cond_offset = i * 2 * self.hidden_channels450        g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]451        x = commons.fused_add_tanh_sigmoid_multiply(452          x,453          g_l,454          torch.IntTensor([self.hidden_channels]))455      y = self.self_attn_layers[i](x, x, self_attn_mask)456      y = self.drop(y)457      x = self.norm_layers_0[i](x + y)458 459      y = self.ffn_layers[i](x, x_mask)460      y = self.drop(y)461      x = self.norm_layers_1[i](x + y)462    x = x * x_mask463    return x464 465 466 467class TransformerCouplingLayer(nn.Module):468  def __init__(self,469      channels,470      hidden_channels,471      kernel_size,472      n_layers,473      n_heads,474      p_dropout=0,475      filter_channels=0,476      mean_only=False,477      wn_sharing_parameter=None,478      gin_channels = 0479      ):480    assert channels % 2 == 0, "channels should be divisible by 2"481    super().__init__()482    self.channels = channels483    self.hidden_channels = hidden_channels484    self.kernel_size = kernel_size485    self.n_layers = n_layers486    self.half_channels = channels // 2487    self.mean_only = mean_only488 489    self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)490    self.enc = Encoder(hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout, isflow = True, gin_channels = gin_channels) if wn_sharing_parameter is None else wn_sharing_parameter491    self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)492    self.post.weight.data.zero_()493    self.post.bias.data.zero_()494 495  def forward(self, x, x_mask, g=None, reverse=False):496    x0, x1 = torch.split(x, [self.half_channels]*2, 1)497    h = self.pre(x0) * x_mask498    h = self.enc(h, x_mask, g=g)499    stats = self.post(h) * x_mask500    if not self.mean_only:501      m, logs = torch.split(stats, [self.half_channels]*2, 1)502    else:503      m = stats504      logs = torch.zeros_like(m)505 506    if not reverse:507      x1 = m + x1 * torch.exp(logs) * x_mask508      x = torch.cat([x0, x1], 1)509      logdet = torch.sum(logs, [1,2])510      return x, logdet511    else:512      x1 = (x1 - m) * torch.exp(-logs) * x_mask513      x = torch.cat([x0, x1], 1)514      return x