CoolFace
Apppublic

6Simple9/ChatTTS-OpenVoice

sourceHugging Facemitupdated 2y agoView on Hugging Face
9likes
attentions.py466 linesDownload Raw Back to OpenVoice
1import math2import torch3from torch import nn4from torch.nn import functional as F5 6from . import commons7import logging8 9logger = logging.getLogger(__name__)10 11 12class LayerNorm(nn.Module):13    def __init__(self, channels, eps=1e-5):14        super().__init__()15        self.channels = channels16        self.eps = eps17 18        self.gamma = nn.Parameter(torch.ones(channels))19        self.beta = nn.Parameter(torch.zeros(channels))20 21    def forward(self, x):22        x = x.transpose(1, -1)23        x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)24        return x.transpose(1, -1)25 26 27@torch.jit.script28def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):29    n_channels_int = n_channels[0]30    in_act = input_a + input_b31    t_act = torch.tanh(in_act[:, :n_channels_int, :])32    s_act = torch.sigmoid(in_act[:, n_channels_int:, :])33    acts = t_act * s_act34    return acts35 36 37class Encoder(nn.Module):38    def __init__(39        self,40        hidden_channels,41        filter_channels,42        n_heads,43        n_layers,44        kernel_size=1,45        p_dropout=0.0,46        window_size=4,47        isflow=True,48        **kwargs49    ):50        super().__init__()51        self.hidden_channels = hidden_channels52        self.filter_channels = filter_channels53        self.n_heads = n_heads54        self.n_layers = n_layers55        self.kernel_size = kernel_size56        self.p_dropout = p_dropout57        self.window_size = window_size58        # if isflow:59        #  cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)60        #  self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)61        #  self.cond_layer = weight_norm(cond_layer, name='weight')62        #  self.gin_channels = 25663        self.cond_layer_idx = self.n_layers64        if "gin_channels" in kwargs:65            self.gin_channels = kwargs["gin_channels"]66            if self.gin_channels != 0:67                self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)68                # vits2 says 3rd block, so idx is 2 by default69                self.cond_layer_idx = (70                    kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 271                )72                # logging.debug(self.gin_channels, self.cond_layer_idx)73                assert (74                    self.cond_layer_idx < self.n_layers75                ), "cond_layer_idx should be less than n_layers"76        self.drop = nn.Dropout(p_dropout)77        self.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 82        for i in range(self.n_layers):83            self.attn_layers.append(84                MultiHeadAttention(85                    hidden_channels,86                    hidden_channels,87                    n_heads,88                    p_dropout=p_dropout,89                    window_size=window_size,90                )91            )92            self.norm_layers_1.append(LayerNorm(hidden_channels))93            self.ffn_layers.append(94                FFN(95                    hidden_channels,96                    hidden_channels,97                    filter_channels,98                    kernel_size,99                    p_dropout=p_dropout,100                )101            )102            self.norm_layers_2.append(LayerNorm(hidden_channels))103 104    def forward(self, x, x_mask, g=None):105        attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)106        x = x * x_mask107        for i in range(self.n_layers):108            if i == self.cond_layer_idx and g is not None:109                g = self.spk_emb_linear(g.transpose(1, 2))110                g = g.transpose(1, 2)111                x = x + g112                x = x * x_mask113            y = self.attn_layers[i](x, x, attn_mask)114            y = self.drop(y)115            x = self.norm_layers_1[i](x + y)116 117            y = self.ffn_layers[i](x, x_mask)118            y = self.drop(y)119            x = self.norm_layers_2[i](x + y)120        x = x * x_mask121        return x122 123 124class Decoder(nn.Module):125    def __init__(126        self,127        hidden_channels,128        filter_channels,129        n_heads,130        n_layers,131        kernel_size=1,132        p_dropout=0.0,133        proximal_bias=False,134        proximal_init=True,135        **kwargs136    ):137        super().__init__()138        self.hidden_channels = hidden_channels139        self.filter_channels = filter_channels140        self.n_heads = n_heads141        self.n_layers = n_layers142        self.kernel_size = kernel_size143        self.p_dropout = p_dropout144        self.proximal_bias = proximal_bias145        self.proximal_init = proximal_init146 147        self.drop = nn.Dropout(p_dropout)148        self.self_attn_layers = nn.ModuleList()149        self.norm_layers_0 = nn.ModuleList()150        self.encdec_attn_layers = nn.ModuleList()151        self.norm_layers_1 = nn.ModuleList()152        self.ffn_layers = nn.ModuleList()153        self.norm_layers_2 = nn.ModuleList()154        for i in range(self.n_layers):155            self.self_attn_layers.append(156                MultiHeadAttention(157                    hidden_channels,158                    hidden_channels,159                    n_heads,160                    p_dropout=p_dropout,161                    proximal_bias=proximal_bias,162                    proximal_init=proximal_init,163                )164            )165            self.norm_layers_0.append(LayerNorm(hidden_channels))166            self.encdec_attn_layers.append(167                MultiHeadAttention(168                    hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout169                )170            )171            self.norm_layers_1.append(LayerNorm(hidden_channels))172            self.ffn_layers.append(173                FFN(174                    hidden_channels,175                    hidden_channels,176                    filter_channels,177                    kernel_size,178                    p_dropout=p_dropout,179                    causal=True,180                )181            )182            self.norm_layers_2.append(LayerNorm(hidden_channels))183 184    def forward(self, x, x_mask, h, h_mask):185        """186        x: decoder input187        h: encoder output188        """189        self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(190            device=x.device, dtype=x.dtype191        )192        encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)193        x = x * x_mask194        for i in range(self.n_layers):195            y = self.self_attn_layers[i](x, x, self_attn_mask)196            y = self.drop(y)197            x = self.norm_layers_0[i](x + y)198 199            y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)200            y = self.drop(y)201            x = self.norm_layers_1[i](x + y)202 203            y = self.ffn_layers[i](x, x_mask)204            y = self.drop(y)205            x = self.norm_layers_2[i](x + y)206        x = x * x_mask207        return x208 209 210class MultiHeadAttention(nn.Module):211    def __init__(212        self,213        channels,214        out_channels,215        n_heads,216        p_dropout=0.0,217        window_size=None,218        heads_share=True,219        block_length=None,220        proximal_bias=False,221        proximal_init=False,222    ):223        super().__init__()224        assert channels % n_heads == 0225 226        self.channels = channels227        self.out_channels = out_channels228        self.n_heads = n_heads229        self.p_dropout = p_dropout230        self.window_size = window_size231        self.heads_share = heads_share232        self.block_length = block_length233        self.proximal_bias = proximal_bias234        self.proximal_init = proximal_init235        self.attn = None236 237        self.k_channels = channels // n_heads238        self.conv_q = nn.Conv1d(channels, channels, 1)239        self.conv_k = nn.Conv1d(channels, channels, 1)240        self.conv_v = nn.Conv1d(channels, channels, 1)241        self.conv_o = nn.Conv1d(channels, out_channels, 1)242        self.drop = nn.Dropout(p_dropout)243 244        if window_size is not None:245            n_heads_rel = 1 if heads_share else n_heads246            rel_stddev = self.k_channels**-0.5247            self.emb_rel_k = nn.Parameter(248                torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)249                * rel_stddev250            )251            self.emb_rel_v = nn.Parameter(252                torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)253                * rel_stddev254            )255 256        nn.init.xavier_uniform_(self.conv_q.weight)257        nn.init.xavier_uniform_(self.conv_k.weight)258        nn.init.xavier_uniform_(self.conv_v.weight)259        if proximal_init:260            with torch.no_grad():261                self.conv_k.weight.copy_(self.conv_q.weight)262                self.conv_k.bias.copy_(self.conv_q.bias)263 264    def forward(self, x, c, attn_mask=None):265        q = self.conv_q(x)266        k = self.conv_k(c)267        v = self.conv_v(c)268 269        x, self.attn = self.attention(q, k, v, mask=attn_mask)270 271        x = self.conv_o(x)272        return x273 274    def attention(self, query, key, value, mask=None):275        # reshape [b, d, t] -> [b, n_h, t, d_k]276        b, d, t_s, t_t = (*key.size(), query.size(2))277        query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)278        key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)279        value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)280 281        scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))282        if self.window_size is not None:283            assert (284                t_s == t_t285            ), "Relative attention is only available for self-attention."286            key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)287            rel_logits = self._matmul_with_relative_keys(288                query / math.sqrt(self.k_channels), key_relative_embeddings289            )290            scores_local = self._relative_position_to_absolute_position(rel_logits)291            scores = scores + scores_local292        if self.proximal_bias:293            assert t_s == t_t, "Proximal bias is only available for self-attention."294            scores = scores + self._attention_bias_proximal(t_s).to(295                device=scores.device, dtype=scores.dtype296            )297        if mask is not None:298            scores = scores.masked_fill(mask == 0, -1e4)299            if self.block_length is not None:300                assert (301                    t_s == t_t302                ), "Local attention is only available for self-attention."303                block_mask = (304                    torch.ones_like(scores)305                    .triu(-self.block_length)306                    .tril(self.block_length)307                )308                scores = scores.masked_fill(block_mask == 0, -1e4)309        p_attn = F.softmax(scores, dim=-1)  # [b, n_h, t_t, t_s]310        p_attn = self.drop(p_attn)311        output = torch.matmul(p_attn, value)312        if self.window_size is not None:313            relative_weights = self._absolute_position_to_relative_position(p_attn)314            value_relative_embeddings = self._get_relative_embeddings(315                self.emb_rel_v, t_s316            )317            output = output + self._matmul_with_relative_values(318                relative_weights, value_relative_embeddings319            )320        output = (321            output.transpose(2, 3).contiguous().view(b, d, t_t)322        )  # [b, n_h, t_t, d_k] -> [b, d, t_t]323        return output, p_attn324 325    def _matmul_with_relative_values(self, x, y):326        """327        x: [b, h, l, m]328        y: [h or 1, m, d]329        ret: [b, h, l, d]330        """331        ret = torch.matmul(x, y.unsqueeze(0))332        return ret333 334    def _matmul_with_relative_keys(self, x, y):335        """336        x: [b, h, l, d]337        y: [h or 1, m, d]338        ret: [b, h, l, m]339        """340        ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))341        return ret342 343    def _get_relative_embeddings(self, relative_embeddings, length):344        2 * self.window_size + 1345        # Pad first before slice to avoid using cond ops.346        pad_length = max(length - (self.window_size + 1), 0)347        slice_start_position = max((self.window_size + 1) - length, 0)348        slice_end_position = slice_start_position + 2 * length - 1349        if pad_length > 0:350            padded_relative_embeddings = F.pad(351                relative_embeddings,352                commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),353            )354        else:355            padded_relative_embeddings = relative_embeddings356        used_relative_embeddings = padded_relative_embeddings[357            :, slice_start_position:slice_end_position358        ]359        return used_relative_embeddings360 361    def _relative_position_to_absolute_position(self, x):362        """363        x: [b, h, l, 2*l-1]364        ret: [b, h, l, l]365        """366        batch, heads, length, _ = x.size()367        # Concat columns of pad to shift from relative to absolute indexing.368        x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))369 370        # Concat extra elements so to add up to shape (len+1, 2*len-1).371        x_flat = x.view([batch, heads, length * 2 * length])372        x_flat = F.pad(373            x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])374        )375 376        # Reshape and slice out the padded elements.377        x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[378            :, :, :length, length - 1 :379        ]380        return x_final381 382    def _absolute_position_to_relative_position(self, x):383        """384        x: [b, h, l, l]385        ret: [b, h, l, 2*l-1]386        """387        batch, heads, length, _ = x.size()388        # pad along column389        x = F.pad(390            x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])391        )392        x_flat = x.view([batch, heads, length**2 + length * (length - 1)])393        # add 0's in the beginning that will skew the elements after reshape394        x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))395        x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]396        return x_final397 398    def _attention_bias_proximal(self, length):399        """Bias for self-attention to encourage attention to close positions.400        Args:401          length: an integer scalar.402        Returns:403          a Tensor with shape [1, 1, length, length]404        """405        r = torch.arange(length, dtype=torch.float32)406        diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)407        return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)408 409 410class FFN(nn.Module):411    def __init__(412        self,413        in_channels,414        out_channels,415        filter_channels,416        kernel_size,417        p_dropout=0.0,418        activation=None,419        causal=False,420    ):421        super().__init__()422        self.in_channels = in_channels423        self.out_channels = out_channels424        self.filter_channels = filter_channels425        self.kernel_size = kernel_size426        self.p_dropout = p_dropout427        self.activation = activation428        self.causal = causal429 430        if causal:431            self.padding = self._causal_padding432        else:433            self.padding = self._same_padding434 435        self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)436        self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)437        self.drop = nn.Dropout(p_dropout)438 439    def forward(self, x, x_mask):440        x = self.conv_1(self.padding(x * x_mask))441        if self.activation == "gelu":442            x = x * torch.sigmoid(1.702 * x)443        else:444            x = torch.relu(x)445        x = self.drop(x)446        x = self.conv_2(self.padding(x * x_mask))447        return x * x_mask448 449    def _causal_padding(self, x):450        if self.kernel_size == 1:451            return x452        pad_l = self.kernel_size - 1453        pad_r = 0454        padding = [[0, 0], [0, 0], [pad_l, pad_r]]455        x = F.pad(x, commons.convert_pad_shape(padding))456        return x457 458    def _same_padding(self, x):459        if self.kernel_size == 1:460            return x461        pad_l = (self.kernel_size - 1) // 2462        pad_r = self.kernel_size // 2463        padding = [[0, 0], [0, 0], [pad_l, pad_r]]464        x = F.pad(x, commons.convert_pad_shape(padding))465        return x466