|
| 1 | +import numpy as np |
| 2 | +import torch |
| 3 | +import torch.nn.functional as F |
| 4 | +import torch.nn as nn |
| 5 | + |
| 6 | + |
| 7 | +def combine_frames(x, n): |
| 8 | + B, L, C = x.shape |
| 9 | + num_groups = L // n |
| 10 | + if num_groups == 0: |
| 11 | + return torch.empty(B, 0, n * C, device=x.device, dtype=x.dtype) |
| 12 | + x = x[:, :num_groups * n, :].reshape(B, num_groups, n * C) |
| 13 | + return x |
| 14 | + |
| 15 | + |
| 16 | +class Transpose(nn.Module): |
| 17 | + def __init__(self, dims): |
| 18 | + super().__init__() |
| 19 | + assert len(dims) == 2, 'dims must be a tuple of two dimensions' |
| 20 | + self.dims = dims |
| 21 | + |
| 22 | + def forward(self, x): |
| 23 | + return x.transpose(*self.dims) |
| 24 | + |
| 25 | + |
| 26 | +class LeakyHardFunction(torch.autograd.Function): |
| 27 | + @staticmethod |
| 28 | + def forward(ctx, x, min_val, max_val, leak_slope): |
| 29 | + if not (min_val < max_val): |
| 30 | + raise ValueError("min_val must be < max_val") |
| 31 | + if leak_slope < 0: |
| 32 | + raise ValueError("leak_slope must be >= 0") |
| 33 | + ctx.min_val = min_val |
| 34 | + ctx.max_val = max_val |
| 35 | + ctx.leak_slope = leak_slope |
| 36 | + below_mask = x < min_val |
| 37 | + any_below = torch.any(below_mask) |
| 38 | + if any_below: |
| 39 | + x[below_mask] = leak_slope * x[below_mask] + (1 - leak_slope) * min_val |
| 40 | + above_mask = x > max_val |
| 41 | + any_above = torch.any(above_mask) |
| 42 | + if any_above: |
| 43 | + x[above_mask] = leak_slope * x[above_mask] + (1 - leak_slope) * max_val |
| 44 | + if any_below or any_above: |
| 45 | + ctx.save_for_backward(below_mask | above_mask) |
| 46 | + return x |
| 47 | + |
| 48 | + @staticmethod |
| 49 | + def backward(ctx, grad_output): |
| 50 | + if len(ctx.saved_tensors) > 0: |
| 51 | + mask, = ctx.saved_tensors |
| 52 | + grad_output[mask] *= ctx.leak_slope |
| 53 | + return grad_output, None, None, None |
| 54 | + |
| 55 | + |
| 56 | +class ATanGLU(nn.Module): |
| 57 | + # ArcTan-Applies the gated linear unit function. |
| 58 | + def __init__(self, dim=-1, hard_limit=False): |
| 59 | + super().__init__() |
| 60 | + self.dim = dim |
| 61 | + self.hard_limit = hard_limit |
| 62 | + |
| 63 | + def forward(self, x): |
| 64 | + if self.hard_limit: |
| 65 | + x = LeakyHardFunction.apply(x, -100, 100, 0.01) |
| 66 | + # out, gate = x.chunk(2, dim=self.dim) |
| 67 | + # Using torch.split instead of chunk for ONNX export compatibility. |
| 68 | + out, gate = torch.split(x, x.size(self.dim) // 2, dim=self.dim) |
| 69 | + return out * torch.atan(gate) |
| 70 | + |
| 71 | + |
| 72 | +class LYNXNet2Block(nn.Module): |
| 73 | + def __init__(self, dim, expansion_factor, kernel_size=31, dropout=0.): |
| 74 | + super().__init__() |
| 75 | + inner_dim = int(dim * expansion_factor) |
| 76 | + if float(dropout) > 0.: |
| 77 | + _dropout = nn.Dropout(dropout) |
| 78 | + else: |
| 79 | + _dropout = nn.Identity() |
| 80 | + self.net = nn.Sequential( |
| 81 | + Transpose((1, 2)), |
| 82 | + nn.Conv1d(dim, dim, kernel_size=kernel_size, padding=kernel_size // 2, groups=dim), |
| 83 | + Transpose((1, 2)), |
| 84 | + nn.Linear(dim, inner_dim * 2), |
| 85 | + ATanGLU(), |
| 86 | + nn.Linear(inner_dim, inner_dim * 2), |
| 87 | + ATanGLU(hard_limit=True), |
| 88 | + nn.Linear(inner_dim, dim), |
| 89 | + _dropout |
| 90 | + ) |
| 91 | + |
| 92 | + def forward(self, x): |
| 93 | + norm_x = F.rms_norm(x, (x.size(-1), )) |
| 94 | + x = x + self.net(norm_x) |
| 95 | + return x, norm_x |
| 96 | + |
| 97 | + |
| 98 | +class FastPD(torch.nn.Module): |
| 99 | + def __init__(self, period, init_channel=8, strides=[4, 4, 4], kernel_size=11): |
| 100 | + super(FastPD, self).__init__() |
| 101 | + self.period = period |
| 102 | + self.strides = strides |
| 103 | + self.pre = nn.Linear(1, init_channel) |
| 104 | + self.residual_layers = nn.ModuleList( |
| 105 | + [ |
| 106 | + LYNXNet2Block( |
| 107 | + dim=init_channel * np.prod(strides[: i + 1]), |
| 108 | + expansion_factor=1, |
| 109 | + kernel_size=kernel_size, |
| 110 | + dropout=0 |
| 111 | + ) |
| 112 | + for i in range(len(strides)) |
| 113 | + ] |
| 114 | + ) |
| 115 | + self.post = nn.Linear(init_channel * np.prod(strides), 1) |
| 116 | + |
| 117 | + def forward(self, x): |
| 118 | + fmap = [] |
| 119 | + |
| 120 | + # 1d to 2d |
| 121 | + b, _, t = x.shape |
| 122 | + if t % self.period != 0: # pad first |
| 123 | + n_pad = self.period - (t % self.period) |
| 124 | + x = F.pad(x, (0, n_pad), "reflect") |
| 125 | + t = t + n_pad |
| 126 | + x = x.view(b, 1, t // self.period, self.period) |
| 127 | + x = x.permute(0, 3, 2, 1).reshape(b * self.period, t // self.period, 1) |
| 128 | + |
| 129 | + x = self.pre(x) |
| 130 | + for i, layer in enumerate(self.residual_layers): |
| 131 | + if self.strides[i] > 1: |
| 132 | + x = combine_frames(x, self.strides[i]) |
| 133 | + x, norm_x = layer(x) |
| 134 | + if i > 0: |
| 135 | + fmap.append(norm_x.reshape(b, -1)) |
| 136 | + x = self.post(F.rms_norm(x, (x.size(-1), ))) |
| 137 | + x = x.reshape(b, -1) |
| 138 | + |
| 139 | + return x, fmap |
| 140 | + |
| 141 | + |
| 142 | +class FastMPD(torch.nn.Module): |
| 143 | + def __init__(self,periods=None, init_channel=8, strides=[1, 2, 4, 4, 2], kernel_size=31): |
| 144 | + super(FastMPD, self).__init__() |
| 145 | + self.periods = periods if periods is not None else [2, 3, 5, 7, 11] |
| 146 | + self.discriminators = nn.ModuleList() |
| 147 | + for period in self.periods: |
| 148 | + self.discriminators.append( |
| 149 | + FastPD(period, init_channel=init_channel, strides=strides, kernel_size=kernel_size)) |
| 150 | + |
| 151 | + def forward(self, y,): |
| 152 | + y_d_rs = [] |
| 153 | + fmap_rs = [] |
| 154 | + |
| 155 | + for i, d in enumerate(self.discriminators): |
| 156 | + y_d_r, fmap_r = d(y) |
| 157 | + y_d_rs.append(y_d_r) |
| 158 | + fmap_rs.append(fmap_r) |
| 159 | + |
| 160 | + return y_d_rs, fmap_rs |
0 commit comments