CoolFace
Apppublic

Kafke/Code-Realize-TTS

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
ONNXVITS_transforms.py197 linesDownload Raw Back to root
1import torch2from torch.nn import functional as F3 4import numpy as np5 6 7DEFAULT_MIN_BIN_WIDTH = 1e-38DEFAULT_MIN_BIN_HEIGHT = 1e-39DEFAULT_MIN_DERIVATIVE = 1e-310 11 12def piecewise_rational_quadratic_transform(inputs, 13                                           unnormalized_widths,14                                           unnormalized_heights,15                                           unnormalized_derivatives,16                                           inverse=False,17                                           tails=None, 18                                           tail_bound=1.,19                                           min_bin_width=DEFAULT_MIN_BIN_WIDTH,20                                           min_bin_height=DEFAULT_MIN_BIN_HEIGHT,21                                           min_derivative=DEFAULT_MIN_DERIVATIVE):22 23    if tails is None:24        spline_fn = rational_quadratic_spline25        spline_kwargs = {}26    else:27        spline_fn = unconstrained_rational_quadratic_spline28        spline_kwargs = {29            'tails': tails,30            'tail_bound': tail_bound31        }32 33    outputs, logabsdet = spline_fn(34            inputs=inputs,35            unnormalized_widths=unnormalized_widths,36            unnormalized_heights=unnormalized_heights,37            unnormalized_derivatives=unnormalized_derivatives,38            inverse=inverse,39            min_bin_width=min_bin_width,40            min_bin_height=min_bin_height,41            min_derivative=min_derivative,42            **spline_kwargs43    )44    return outputs, logabsdet45 46 47def searchsorted(bin_locations, inputs, eps=1e-6):48    bin_locations[..., -1] += eps49    return torch.sum(50        inputs[..., None] >= bin_locations,51        dim=-152    ) - 153 54 55def unconstrained_rational_quadratic_spline(inputs,56                                            unnormalized_widths,57                                            unnormalized_heights,58                                            unnormalized_derivatives,59                                            inverse=False,60                                            tails='linear',61                                            tail_bound=1.,62                                            min_bin_width=DEFAULT_MIN_BIN_WIDTH,63                                            min_bin_height=DEFAULT_MIN_BIN_HEIGHT,64                                            min_derivative=DEFAULT_MIN_DERIVATIVE):65    inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)66    outside_interval_mask = ~inside_interval_mask67 68    outputs = torch.zeros_like(inputs)69    logabsdet = torch.zeros_like(inputs)70 71    if tails == 'linear':72        #unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))73        unnormalized_derivatives_ = torch.zeros((1, 1, unnormalized_derivatives.size(2), unnormalized_derivatives.size(3)+2))74        unnormalized_derivatives_[...,1:-1] = unnormalized_derivatives75        unnormalized_derivatives = unnormalized_derivatives_76        constant = np.log(np.exp(1 - min_derivative) - 1)77        unnormalized_derivatives[..., 0] = constant78        unnormalized_derivatives[..., -1] = constant79 80        outputs[outside_interval_mask] = inputs[outside_interval_mask]81        logabsdet[outside_interval_mask] = 082    else:83        raise RuntimeError('{} tails are not implemented.'.format(tails))84 85    outputs[inside_interval_mask], logabsdet[inside_interval_mask] = rational_quadratic_spline(86        inputs=inputs[inside_interval_mask],87        unnormalized_widths=unnormalized_widths[inside_interval_mask, :],88        unnormalized_heights=unnormalized_heights[inside_interval_mask, :],89        unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],90        inverse=inverse,91        left=-tail_bound, right=tail_bound, bottom=-tail_bound, top=tail_bound,92        min_bin_width=min_bin_width,93        min_bin_height=min_bin_height,94        min_derivative=min_derivative95    )96 97    return outputs, logabsdet98 99def rational_quadratic_spline(inputs,100                              unnormalized_widths,101                              unnormalized_heights,102                              unnormalized_derivatives,103                              inverse=False,104                              left=0., right=1., bottom=0., top=1.,105                              min_bin_width=DEFAULT_MIN_BIN_WIDTH,106                              min_bin_height=DEFAULT_MIN_BIN_HEIGHT,107                              min_derivative=DEFAULT_MIN_DERIVATIVE):108    if torch.min(inputs) < left or torch.max(inputs) > right:109        raise ValueError('Input to a transform is not within its domain')110 111    num_bins = unnormalized_widths.shape[-1]112 113    if min_bin_width * num_bins > 1.0:114        raise ValueError('Minimal bin width too large for the number of bins')115    if min_bin_height * num_bins > 1.0:116        raise ValueError('Minimal bin height too large for the number of bins')117 118    widths = F.softmax(unnormalized_widths, dim=-1)119    widths = min_bin_width + (1 - min_bin_width * num_bins) * widths120    cumwidths = torch.cumsum(widths, dim=-1)121    cumwidths = F.pad(cumwidths, pad=(1, 0), mode='constant', value=0.0)122    cumwidths = (right - left) * cumwidths + left123    cumwidths[..., 0] = left124    cumwidths[..., -1] = right125    widths = cumwidths[..., 1:] - cumwidths[..., :-1]126 127    derivatives = min_derivative + F.softplus(unnormalized_derivatives)128 129    heights = F.softmax(unnormalized_heights, dim=-1)130    heights = min_bin_height + (1 - min_bin_height * num_bins) * heights131    cumheights = torch.cumsum(heights, dim=-1)132    cumheights = F.pad(cumheights, pad=(1, 0), mode='constant', value=0.0)133    cumheights = (top - bottom) * cumheights + bottom134    cumheights[..., 0] = bottom135    cumheights[..., -1] = top136    heights = cumheights[..., 1:] - cumheights[..., :-1]137 138    if inverse:139        bin_idx = searchsorted(cumheights, inputs)[..., None]140    else:141        bin_idx = searchsorted(cumwidths, inputs)[..., None]142 143    input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]144    input_bin_widths = widths.gather(-1, bin_idx)[..., 0]145 146    input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]147    delta = heights / widths148    input_delta = delta.gather(-1, bin_idx)[..., 0]149 150    input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]151    input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]152 153    input_heights = heights.gather(-1, bin_idx)[..., 0]154 155    if inverse:156        a = (((inputs - input_cumheights) * (input_derivatives157                                             + input_derivatives_plus_one158                                             - 2 * input_delta)159              + input_heights * (input_delta - input_derivatives)))160        b = (input_heights * input_derivatives161             - (inputs - input_cumheights) * (input_derivatives162                                              + input_derivatives_plus_one163                                              - 2 * input_delta))164        c = - input_delta * (inputs - input_cumheights)165 166        discriminant = b.pow(2) - 4 * a * c167        assert (discriminant >= 0).all()168 169        root = (2 * c) / (-b - torch.sqrt(discriminant))170        outputs = root * input_bin_widths + input_cumwidths171 172        theta_one_minus_theta = root * (1 - root)173        denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)174                                     * theta_one_minus_theta)175        derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * root.pow(2)176                                                     + 2 * input_delta * theta_one_minus_theta177                                                     + input_derivatives * (1 - root).pow(2))178        logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)179 180        return outputs, -logabsdet181    else:182        theta = (inputs - input_cumwidths) / input_bin_widths183        theta_one_minus_theta = theta * (1 - theta)184 185        numerator = input_heights * (input_delta * theta.pow(2)186                                     + input_derivatives * theta_one_minus_theta)187        denominator = input_delta + ((input_derivatives + input_derivatives_plus_one - 2 * input_delta)188                                     * theta_one_minus_theta)189        outputs = input_cumheights + numerator / denominator190 191        derivative_numerator = input_delta.pow(2) * (input_derivatives_plus_one * theta.pow(2)192                                                     + 2 * input_delta * theta_one_minus_theta193                                                     + input_derivatives * (1 - theta).pow(2))194        logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)195 196        return outputs, logabsdet197