CoolFace
Apppublic

goathead777/Zero_Shot_Inference

sourceHugging Facemitupdated 3y agoView on Hugging Face
0likes
modules.py924 linesDownload Raw Back to module
1import math2import numpy as np3import torch4from torch import nn5from torch.nn import functional as F6 7from torch.nn import Conv1d8from torch.nn.utils import weight_norm, remove_weight_norm9 10from module import commons11from module.commons import init_weights, get_padding12from module.transforms import piecewise_rational_quadratic_transform13import torch.distributions as D14 15 16LRELU_SLOPE = 0.117 18 19class LayerNorm(nn.Module):20    def __init__(self, channels, eps=1e-5):21        super().__init__()22        self.channels = channels23        self.eps = eps24 25        self.gamma = nn.Parameter(torch.ones(channels))26        self.beta = nn.Parameter(torch.zeros(channels))27 28    def forward(self, x):29        x = x.transpose(1, -1)30        x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)31        return x.transpose(1, -1)32 33 34class ConvReluNorm(nn.Module):35    def __init__(36        self,37        in_channels,38        hidden_channels,39        out_channels,40        kernel_size,41        n_layers,42        p_dropout,43    ):44        super().__init__()45        self.in_channels = in_channels46        self.hidden_channels = hidden_channels47        self.out_channels = out_channels48        self.kernel_size = kernel_size49        self.n_layers = n_layers50        self.p_dropout = p_dropout51        assert n_layers > 1, "Number of layers should be larger than 0."52 53        self.conv_layers = nn.ModuleList()54        self.norm_layers = nn.ModuleList()55        self.conv_layers.append(56            nn.Conv1d(57                in_channels, hidden_channels, kernel_size, padding=kernel_size // 258            )59        )60        self.norm_layers.append(LayerNorm(hidden_channels))61        self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))62        for _ in range(n_layers - 1):63            self.conv_layers.append(64                nn.Conv1d(65                    hidden_channels,66                    hidden_channels,67                    kernel_size,68                    padding=kernel_size // 2,69                )70            )71            self.norm_layers.append(LayerNorm(hidden_channels))72        self.proj = nn.Conv1d(hidden_channels, out_channels, 1)73        self.proj.weight.data.zero_()74        self.proj.bias.data.zero_()75 76    def forward(self, x, x_mask):77        x_org = x78        for i in range(self.n_layers):79            x = self.conv_layers[i](x * x_mask)80            x = self.norm_layers[i](x)81            x = self.relu_drop(x)82        x = x_org + self.proj(x)83        return x * x_mask84 85 86class DDSConv(nn.Module):87    """88    Dialted and Depth-Separable Convolution89    """90 91    def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):92        super().__init__()93        self.channels = channels94        self.kernel_size = kernel_size95        self.n_layers = n_layers96        self.p_dropout = p_dropout97 98        self.drop = nn.Dropout(p_dropout)99        self.convs_sep = nn.ModuleList()100        self.convs_1x1 = nn.ModuleList()101        self.norms_1 = nn.ModuleList()102        self.norms_2 = nn.ModuleList()103        for i in range(n_layers):104            dilation = kernel_size**i105            padding = (kernel_size * dilation - dilation) // 2106            self.convs_sep.append(107                nn.Conv1d(108                    channels,109                    channels,110                    kernel_size,111                    groups=channels,112                    dilation=dilation,113                    padding=padding,114                )115            )116            self.convs_1x1.append(nn.Conv1d(channels, channels, 1))117            self.norms_1.append(LayerNorm(channels))118            self.norms_2.append(LayerNorm(channels))119 120    def forward(self, x, x_mask, g=None):121        if g is not None:122            x = x + g123        for i in range(self.n_layers):124            y = self.convs_sep[i](x * x_mask)125            y = self.norms_1[i](y)126            y = F.gelu(y)127            y = self.convs_1x1[i](y)128            y = self.norms_2[i](y)129            y = F.gelu(y)130            y = self.drop(y)131            x = x + y132        return x * x_mask133 134 135class WN(torch.nn.Module):136    def __init__(137        self,138        hidden_channels,139        kernel_size,140        dilation_rate,141        n_layers,142        gin_channels=0,143        p_dropout=0,144    ):145        super(WN, self).__init__()146        assert kernel_size % 2 == 1147        self.hidden_channels = hidden_channels148        self.kernel_size = (kernel_size,)149        self.dilation_rate = dilation_rate150        self.n_layers = n_layers151        self.gin_channels = gin_channels152        self.p_dropout = p_dropout153 154        self.in_layers = torch.nn.ModuleList()155        self.res_skip_layers = torch.nn.ModuleList()156        self.drop = nn.Dropout(p_dropout)157 158        if gin_channels != 0:159            cond_layer = torch.nn.Conv1d(160                gin_channels, 2 * hidden_channels * n_layers, 1161            )162            self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")163 164        for i in range(n_layers):165            dilation = dilation_rate**i166            padding = int((kernel_size * dilation - dilation) / 2)167            in_layer = torch.nn.Conv1d(168                hidden_channels,169                2 * hidden_channels,170                kernel_size,171                dilation=dilation,172                padding=padding,173            )174            in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")175            self.in_layers.append(in_layer)176 177            # last one is not necessary178            if i < n_layers - 1:179                res_skip_channels = 2 * hidden_channels180            else:181                res_skip_channels = hidden_channels182 183            res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)184            res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")185            self.res_skip_layers.append(res_skip_layer)186 187    def forward(self, x, x_mask, g=None, **kwargs):188        output = torch.zeros_like(x)189        n_channels_tensor = torch.IntTensor([self.hidden_channels])190 191        if g is not None:192            g = self.cond_layer(g)193 194        for i in range(self.n_layers):195            x_in = self.in_layers[i](x)196            if g is not None:197                cond_offset = i * 2 * self.hidden_channels198                g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]199            else:200                g_l = torch.zeros_like(x_in)201 202            acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)203            acts = self.drop(acts)204 205            res_skip_acts = self.res_skip_layers[i](acts)206            if i < self.n_layers - 1:207                res_acts = res_skip_acts[:, : self.hidden_channels, :]208                x = (x + res_acts) * x_mask209                output = output + res_skip_acts[:, self.hidden_channels :, :]210            else:211                output = output + res_skip_acts212        return output * x_mask213 214    def remove_weight_norm(self):215        if self.gin_channels != 0:216            torch.nn.utils.remove_weight_norm(self.cond_layer)217        for l in self.in_layers:218            torch.nn.utils.remove_weight_norm(l)219        for l in self.res_skip_layers:220            torch.nn.utils.remove_weight_norm(l)221 222 223class ResBlock1(torch.nn.Module):224    def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):225        super(ResBlock1, self).__init__()226        self.convs1 = nn.ModuleList(227            [228                weight_norm(229                    Conv1d(230                        channels,231                        channels,232                        kernel_size,233                        1,234                        dilation=dilation[0],235                        padding=get_padding(kernel_size, dilation[0]),236                    )237                ),238                weight_norm(239                    Conv1d(240                        channels,241                        channels,242                        kernel_size,243                        1,244                        dilation=dilation[1],245                        padding=get_padding(kernel_size, dilation[1]),246                    )247                ),248                weight_norm(249                    Conv1d(250                        channels,251                        channels,252                        kernel_size,253                        1,254                        dilation=dilation[2],255                        padding=get_padding(kernel_size, dilation[2]),256                    )257                ),258            ]259        )260        self.convs1.apply(init_weights)261 262        self.convs2 = nn.ModuleList(263            [264                weight_norm(265                    Conv1d(266                        channels,267                        channels,268                        kernel_size,269                        1,270                        dilation=1,271                        padding=get_padding(kernel_size, 1),272                    )273                ),274                weight_norm(275                    Conv1d(276                        channels,277                        channels,278                        kernel_size,279                        1,280                        dilation=1,281                        padding=get_padding(kernel_size, 1),282                    )283                ),284                weight_norm(285                    Conv1d(286                        channels,287                        channels,288                        kernel_size,289                        1,290                        dilation=1,291                        padding=get_padding(kernel_size, 1),292                    )293                ),294            ]295        )296        self.convs2.apply(init_weights)297 298    def forward(self, x, x_mask=None):299        for c1, c2 in zip(self.convs1, self.convs2):300            xt = F.leaky_relu(x, LRELU_SLOPE)301            if x_mask is not None:302                xt = xt * x_mask303            xt = c1(xt)304            xt = F.leaky_relu(xt, LRELU_SLOPE)305            if x_mask is not None:306                xt = xt * x_mask307            xt = c2(xt)308            x = xt + x309        if x_mask is not None:310            x = x * x_mask311        return x312 313    def remove_weight_norm(self):314        for l in self.convs1:315            remove_weight_norm(l)316        for l in self.convs2:317            remove_weight_norm(l)318 319 320class ResBlock2(torch.nn.Module):321    def __init__(self, channels, kernel_size=3, dilation=(1, 3)):322        super(ResBlock2, self).__init__()323        self.convs = nn.ModuleList(324            [325                weight_norm(326                    Conv1d(327                        channels,328                        channels,329                        kernel_size,330                        1,331                        dilation=dilation[0],332                        padding=get_padding(kernel_size, dilation[0]),333                    )334                ),335                weight_norm(336                    Conv1d(337                        channels,338                        channels,339                        kernel_size,340                        1,341                        dilation=dilation[1],342                        padding=get_padding(kernel_size, dilation[1]),343                    )344                ),345            ]346        )347        self.convs.apply(init_weights)348 349    def forward(self, x, x_mask=None):350        for c in self.convs:351            xt = F.leaky_relu(x, LRELU_SLOPE)352            if x_mask is not None:353                xt = xt * x_mask354            xt = c(xt)355            x = xt + x356        if x_mask is not None:357            x = x * x_mask358        return x359 360    def remove_weight_norm(self):361        for l in self.convs:362            remove_weight_norm(l)363 364 365class Log(nn.Module):366    def forward(self, x, x_mask, reverse=False, **kwargs):367        if not reverse:368            y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask369            logdet = torch.sum(-y, [1, 2])370            return y, logdet371        else:372            x = torch.exp(x) * x_mask373            return x374 375 376class Flip(nn.Module):377    def forward(self, x, *args, reverse=False, **kwargs):378        x = torch.flip(x, [1])379        if not reverse:380            logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)381            return x, logdet382        else:383            return x384 385 386class ElementwiseAffine(nn.Module):387    def __init__(self, channels):388        super().__init__()389        self.channels = channels390        self.m = nn.Parameter(torch.zeros(channels, 1))391        self.logs = nn.Parameter(torch.zeros(channels, 1))392 393    def forward(self, x, x_mask, reverse=False, **kwargs):394        if not reverse:395            y = self.m + torch.exp(self.logs) * x396            y = y * x_mask397            logdet = torch.sum(self.logs * x_mask, [1, 2])398            return y, logdet399        else:400            x = (x - self.m) * torch.exp(-self.logs) * x_mask401            return x402 403 404class ResidualCouplingLayer(nn.Module):405    def __init__(406        self,407        channels,408        hidden_channels,409        kernel_size,410        dilation_rate,411        n_layers,412        p_dropout=0,413        gin_channels=0,414        mean_only=False,415    ):416        assert channels % 2 == 0, "channels should be divisible by 2"417        super().__init__()418        self.channels = channels419        self.hidden_channels = hidden_channels420        self.kernel_size = kernel_size421        self.dilation_rate = dilation_rate422        self.n_layers = n_layers423        self.half_channels = channels // 2424        self.mean_only = mean_only425 426        self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)427        self.enc = WN(428            hidden_channels,429            kernel_size,430            dilation_rate,431            n_layers,432            p_dropout=p_dropout,433            gin_channels=gin_channels,434        )435        self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)436        self.post.weight.data.zero_()437        self.post.bias.data.zero_()438 439    def forward(self, x, x_mask, g=None, reverse=False):440        x0, x1 = torch.split(x, [self.half_channels] * 2, 1)441        h = self.pre(x0) * x_mask442        h = self.enc(h, x_mask, g=g)443        stats = self.post(h) * x_mask444        if not self.mean_only:445            m, logs = torch.split(stats, [self.half_channels] * 2, 1)446        else:447            m = stats448            logs = torch.zeros_like(m)449 450        if not reverse:451            x1 = m + x1 * torch.exp(logs) * x_mask452            x = torch.cat([x0, x1], 1)453            logdet = torch.sum(logs, [1, 2])454            return x, logdet455        else:456            x1 = (x1 - m) * torch.exp(-logs) * x_mask457            x = torch.cat([x0, x1], 1)458            return x459 460 461class ConvFlow(nn.Module):462    def __init__(463        self,464        in_channels,465        filter_channels,466        kernel_size,467        n_layers,468        num_bins=10,469        tail_bound=5.0,470    ):471        super().__init__()472        self.in_channels = in_channels473        self.filter_channels = filter_channels474        self.kernel_size = kernel_size475        self.n_layers = n_layers476        self.num_bins = num_bins477        self.tail_bound = tail_bound478        self.half_channels = in_channels // 2479 480        self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)481        self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)482        self.proj = nn.Conv1d(483            filter_channels, self.half_channels * (num_bins * 3 - 1), 1484        )485        self.proj.weight.data.zero_()486        self.proj.bias.data.zero_()487 488    def forward(self, x, x_mask, g=None, reverse=False):489        x0, x1 = torch.split(x, [self.half_channels] * 2, 1)490        h = self.pre(x0)491        h = self.convs(h, x_mask, g=g)492        h = self.proj(h) * x_mask493 494        b, c, t = x0.shape495        h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2)  # [b, cx?, t] -> [b, c, t, ?]496 497        unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)498        unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(499            self.filter_channels500        )501        unnormalized_derivatives = h[..., 2 * self.num_bins :]502 503        x1, logabsdet = piecewise_rational_quadratic_transform(504            x1,505            unnormalized_widths,506            unnormalized_heights,507            unnormalized_derivatives,508            inverse=reverse,509            tails="linear",510            tail_bound=self.tail_bound,511        )512 513        x = torch.cat([x0, x1], 1) * x_mask514        logdet = torch.sum(logabsdet * x_mask, [1, 2])515        if not reverse:516            return x, logdet517        else:518            return x519 520 521class LinearNorm(nn.Module):522    def __init__(523        self,524        in_channels,525        out_channels,526        bias=True,527        spectral_norm=False,528    ):529        super(LinearNorm, self).__init__()530        self.fc = nn.Linear(in_channels, out_channels, bias)531 532        if spectral_norm:533            self.fc = nn.utils.spectral_norm(self.fc)534 535    def forward(self, input):536        out = self.fc(input)537        return out538 539 540class Mish(nn.Module):541    def __init__(self):542        super(Mish, self).__init__()543 544    def forward(self, x):545        return x * torch.tanh(F.softplus(x))546 547 548class Conv1dGLU(nn.Module):549    """550    Conv1d + GLU(Gated Linear Unit) with residual connection.551    For GLU refer to https://arxiv.org/abs/1612.08083 paper.552    """553 554    def __init__(self, in_channels, out_channels, kernel_size, dropout):555        super(Conv1dGLU, self).__init__()556        self.out_channels = out_channels557        self.conv1 = ConvNorm(in_channels, 2 * out_channels, kernel_size=kernel_size)558        self.dropout = nn.Dropout(dropout)559 560    def forward(self, x):561        residual = x562        x = self.conv1(x)563        x1, x2 = torch.split(x, split_size_or_sections=self.out_channels, dim=1)564        x = x1 * torch.sigmoid(x2)565        x = residual + self.dropout(x)566        return x567 568 569class ConvNorm(nn.Module):570    def __init__(571        self,572        in_channels,573        out_channels,574        kernel_size=1,575        stride=1,576        padding=None,577        dilation=1,578        bias=True,579        spectral_norm=False,580    ):581        super(ConvNorm, self).__init__()582 583        if padding is None:584            assert kernel_size % 2 == 1585            padding = int(dilation * (kernel_size - 1) / 2)586 587        self.conv = torch.nn.Conv1d(588            in_channels,589            out_channels,590            kernel_size=kernel_size,591            stride=stride,592            padding=padding,593            dilation=dilation,594            bias=bias,595        )596 597        if spectral_norm:598            self.conv = nn.utils.spectral_norm(self.conv)599 600    def forward(self, input):601        out = self.conv(input)602        return out603 604 605class MultiHeadAttention(nn.Module):606    """Multi-Head Attention module"""607 608    def __init__(self, n_head, d_model, d_k, d_v, dropout=0.0, spectral_norm=False):609        super().__init__()610 611        self.n_head = n_head612        self.d_k = d_k613        self.d_v = d_v614 615        self.w_qs = nn.Linear(d_model, n_head * d_k)616        self.w_ks = nn.Linear(d_model, n_head * d_k)617        self.w_vs = nn.Linear(d_model, n_head * d_v)618 619        self.attention = ScaledDotProductAttention(620            temperature=np.power(d_model, 0.5), dropout=dropout621        )622 623        self.fc = nn.Linear(n_head * d_v, d_model)624        self.dropout = nn.Dropout(dropout)625 626        if spectral_norm:627            self.w_qs = nn.utils.spectral_norm(self.w_qs)628            self.w_ks = nn.utils.spectral_norm(self.w_ks)629            self.w_vs = nn.utils.spectral_norm(self.w_vs)630            self.fc = nn.utils.spectral_norm(self.fc)631 632    def forward(self, x, mask=None):633        d_k, d_v, n_head = self.d_k, self.d_v, self.n_head634        sz_b, len_x, _ = x.size()635 636        residual = x637 638        q = self.w_qs(x).view(sz_b, len_x, n_head, d_k)639        k = self.w_ks(x).view(sz_b, len_x, n_head, d_k)640        v = self.w_vs(x).view(sz_b, len_x, n_head, d_v)641        q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_x, d_k)  # (n*b) x lq x dk642        k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_x, d_k)  # (n*b) x lk x dk643        v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_x, d_v)  # (n*b) x lv x dv644 645        if mask is not None:646            slf_mask = mask.repeat(n_head, 1, 1)  # (n*b) x .. x ..647        else:648            slf_mask = None649        output, attn = self.attention(q, k, v, mask=slf_mask)650 651        output = output.view(n_head, sz_b, len_x, d_v)652        output = (653            output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_x, -1)654        )  # b x lq x (n*dv)655 656        output = self.fc(output)657 658        output = self.dropout(output) + residual659        return output, attn660 661 662class ScaledDotProductAttention(nn.Module):663    """Scaled Dot-Product Attention"""664 665    def __init__(self, temperature, dropout):666        super().__init__()667        self.temperature = temperature668        self.softmax = nn.Softmax(dim=2)669        self.dropout = nn.Dropout(dropout)670 671    def forward(self, q, k, v, mask=None):672        attn = torch.bmm(q, k.transpose(1, 2))673        attn = attn / self.temperature674 675        if mask is not None:676            attn = attn.masked_fill(mask, -np.inf)677 678        attn = self.softmax(attn)679        p_attn = self.dropout(attn)680 681        output = torch.bmm(p_attn, v)682        return output, attn683 684 685class MelStyleEncoder(nn.Module):686    """MelStyleEncoder"""687 688    def __init__(689        self,690        n_mel_channels=80,691        style_hidden=128,692        style_vector_dim=256,693        style_kernel_size=5,694        style_head=2,695        dropout=0.1,696    ):697        super(MelStyleEncoder, self).__init__()698        self.in_dim = n_mel_channels699        self.hidden_dim = style_hidden700        self.out_dim = style_vector_dim701        self.kernel_size = style_kernel_size702        self.n_head = style_head703        self.dropout = dropout704 705        self.spectral = nn.Sequential(706            LinearNorm(self.in_dim, self.hidden_dim),707            Mish(),708            nn.Dropout(self.dropout),709            LinearNorm(self.hidden_dim, self.hidden_dim),710            Mish(),711            nn.Dropout(self.dropout),712        )713 714        self.temporal = nn.Sequential(715            Conv1dGLU(self.hidden_dim, self.hidden_dim, self.kernel_size, self.dropout),716            Conv1dGLU(self.hidden_dim, self.hidden_dim, self.kernel_size, self.dropout),717        )718 719        self.slf_attn = MultiHeadAttention(720            self.n_head,721            self.hidden_dim,722            self.hidden_dim // self.n_head,723            self.hidden_dim // self.n_head,724            self.dropout,725        )726 727        self.fc = LinearNorm(self.hidden_dim, self.out_dim)728 729    def temporal_avg_pool(self, x, mask=None):730        if mask is None:731            out = torch.mean(x, dim=1)732        else:733            len_ = (~mask).sum(dim=1).unsqueeze(1)734            x = x.masked_fill(mask.unsqueeze(-1), 0)735            x = x.sum(dim=1)736            out = torch.div(x, len_)737        return out738 739    def forward(self, x, mask=None):740        x = x.transpose(1, 2)741        if mask is not None:742            mask = (mask.int() == 0).squeeze(1)743        max_len = x.shape[1]744        slf_attn_mask = (745            mask.unsqueeze(1).expand(-1, max_len, -1) if mask is not None else None746        )747 748        # spectral749        x = self.spectral(x)750        # temporal751        x = x.transpose(1, 2)752        x = self.temporal(x)753        x = x.transpose(1, 2)754        # self-attention755        if mask is not None:756            x = x.masked_fill(mask.unsqueeze(-1), 0)757        x, _ = self.slf_attn(x, mask=slf_attn_mask)758        # fc759        x = self.fc(x)760        # temoral average pooling761        w = self.temporal_avg_pool(x, mask=mask)762 763        return w.unsqueeze(-1)764 765 766class MelStyleEncoderVAE(nn.Module):767    def __init__(self, spec_channels, z_latent_dim, emb_dim):768        super().__init__()769        self.ref_encoder = MelStyleEncoder(spec_channels, style_vector_dim=emb_dim)770        self.fc1 = nn.Linear(emb_dim, z_latent_dim)771        self.fc2 = nn.Linear(emb_dim, z_latent_dim)772        self.fc3 = nn.Linear(z_latent_dim, emb_dim)773        self.z_latent_dim = z_latent_dim774 775    def reparameterize(self, mu, logvar):776        if self.training:777            std = torch.exp(0.5 * logvar)778            eps = torch.randn_like(std)779            return eps.mul(std).add_(mu)780        else:781            return mu782 783    def forward(self, inputs, mask=None):784        enc_out = self.ref_encoder(inputs.squeeze(-1), mask).squeeze(-1)785        mu = self.fc1(enc_out)786        logvar = self.fc2(enc_out)787        posterior = D.Normal(mu, torch.exp(logvar))788        kl_divergence = D.kl_divergence(789            posterior, D.Normal(torch.zeros_like(mu), torch.ones_like(logvar))790        )791        loss_kl = kl_divergence.mean()792 793        z = posterior.rsample()794        style_embed = self.fc3(z)795 796        return style_embed.unsqueeze(-1), loss_kl797 798    def infer(self, inputs=None, random_sample=False, manual_latent=None):799        if manual_latent is None:800            if random_sample:801                dev = next(self.parameters()).device802                posterior = D.Normal(803                    torch.zeros(1, self.z_latent_dim, device=dev),804                    torch.ones(1, self.z_latent_dim, device=dev),805                )806                z = posterior.rsample()807            else:808                enc_out = self.ref_encoder(inputs.transpose(1, 2))809                mu = self.fc1(enc_out)810                z = mu811        else:812            z = manual_latent813        style_embed = self.fc3(z)814        return style_embed.unsqueeze(-1), z815 816 817class ActNorm(nn.Module):818    def __init__(self, channels, ddi=False, **kwargs):819        super().__init__()820        self.channels = channels821        self.initialized = not ddi822 823        self.logs = nn.Parameter(torch.zeros(1, channels, 1))824        self.bias = nn.Parameter(torch.zeros(1, channels, 1))825 826    def forward(self, x, x_mask=None, g=None, reverse=False, **kwargs):827        if x_mask is None:828            x_mask = torch.ones(x.size(0), 1, x.size(2)).to(829                device=x.device, dtype=x.dtype830            )831        x_len = torch.sum(x_mask, [1, 2])832        if not self.initialized:833            self.initialize(x, x_mask)834            self.initialized = True835 836        if reverse:837            z = (x - self.bias) * torch.exp(-self.logs) * x_mask838            logdet = None839            return z840        else:841            z = (self.bias + torch.exp(self.logs) * x) * x_mask842            logdet = torch.sum(self.logs) * x_len  # [b]843            return z, logdet844 845    def store_inverse(self):846        pass847 848    def set_ddi(self, ddi):849        self.initialized = not ddi850 851    def initialize(self, x, x_mask):852        with torch.no_grad():853            denom = torch.sum(x_mask, [0, 2])854            m = torch.sum(x * x_mask, [0, 2]) / denom855            m_sq = torch.sum(x * x * x_mask, [0, 2]) / denom856            v = m_sq - (m**2)857            logs = 0.5 * torch.log(torch.clamp_min(v, 1e-6))858 859            bias_init = (860                (-m * torch.exp(-logs)).view(*self.bias.shape).to(dtype=self.bias.dtype)861            )862            logs_init = (-logs).view(*self.logs.shape).to(dtype=self.logs.dtype)863 864            self.bias.data.copy_(bias_init)865            self.logs.data.copy_(logs_init)866 867 868class InvConvNear(nn.Module):869    def __init__(self, channels, n_split=4, no_jacobian=False, **kwargs):870        super().__init__()871        assert n_split % 2 == 0872        self.channels = channels873        self.n_split = n_split874        self.no_jacobian = no_jacobian875 876        w_init = torch.linalg.qr(877            torch.FloatTensor(self.n_split, self.n_split).normal_()878        )[0]879        if torch.det(w_init) < 0:880            w_init[:, 0] = -1 * w_init[:, 0]881        self.weight = nn.Parameter(w_init)882 883    def forward(self, x, x_mask=None, g=None, reverse=False, **kwargs):884        b, c, t = x.size()885        assert c % self.n_split == 0886        if x_mask is None:887            x_mask = 1888            x_len = torch.ones((b,), dtype=x.dtype, device=x.device) * t889        else:890            x_len = torch.sum(x_mask, [1, 2])891 892        x = x.view(b, 2, c // self.n_split, self.n_split // 2, t)893        x = (894            x.permute(0, 1, 3, 2, 4)895            .contiguous()896            .view(b, self.n_split, c // self.n_split, t)897        )898 899        if reverse:900            if hasattr(self, "weight_inv"):901                weight = self.weight_inv902            else:903                weight = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype)904            logdet = None905        else:906            weight = self.weight907            if self.no_jacobian:908                logdet = 0909            else:910                logdet = torch.logdet(self.weight) * (c / self.n_split) * x_len  # [b]911 912        weight = weight.view(self.n_split, self.n_split, 1, 1)913        z = F.conv2d(x, weight)914 915        z = z.view(b, 2, self.n_split // 2, c // self.n_split, t)916        z = z.permute(0, 1, 3, 2, 4).contiguous().view(b, c, t) * x_mask917        if reverse:918            return z919        else:920            return z, logdet921 922    def store_inverse(self):923        self.weight_inv = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype)924