KingNish commited on
Commit
c09ee2a
Β·
verified Β·
1 Parent(s): 0fc9117

Upload ./vocos/modules.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. vocos/modules.py +213 -0
vocos/modules.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple
2
+
3
+ import torch
4
+ from torch import nn
5
+ from torch.nn.utils import weight_norm, remove_weight_norm
6
+
7
+
8
+ class ConvNeXtBlock(nn.Module):
9
+ """ConvNeXt Block adapted from https://github.com/facebookresearch/ConvNeXt to 1D audio signal.
10
+
11
+ Args:
12
+ dim (int): Number of input channels.
13
+ intermediate_dim (int): Dimensionality of the intermediate layer.
14
+ layer_scale_init_value (float, optional): Initial value for the layer scale. None means no scaling.
15
+ Defaults to None.
16
+ adanorm_num_embeddings (int, optional): Number of embeddings for AdaLayerNorm.
17
+ None means non-conditional LayerNorm. Defaults to None.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ dim: int,
23
+ intermediate_dim: int,
24
+ layer_scale_init_value: float,
25
+ adanorm_num_embeddings: Optional[int] = None,
26
+ ):
27
+ super().__init__()
28
+ self.dwconv = nn.Conv1d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
29
+ self.adanorm = adanorm_num_embeddings is not None
30
+ if adanorm_num_embeddings:
31
+ self.norm = AdaLayerNorm(adanorm_num_embeddings, dim, eps=1e-6)
32
+ else:
33
+ self.norm = nn.LayerNorm(dim, eps=1e-6)
34
+ self.pwconv1 = nn.Linear(dim, intermediate_dim) # pointwise/1x1 convs, implemented with linear layers
35
+ self.act = nn.GELU()
36
+ self.pwconv2 = nn.Linear(intermediate_dim, dim)
37
+ self.gamma = (
38
+ nn.Parameter(layer_scale_init_value * torch.ones(dim), requires_grad=True)
39
+ if layer_scale_init_value > 0
40
+ else None
41
+ )
42
+
43
+ def forward(self, x: torch.Tensor, cond_embedding_id: Optional[torch.Tensor] = None) -> torch.Tensor:
44
+ residual = x
45
+ x = self.dwconv(x)
46
+ x = x.transpose(1, 2) # (B, C, T) -> (B, T, C)
47
+ if self.adanorm:
48
+ assert cond_embedding_id is not None
49
+ x = self.norm(x, cond_embedding_id)
50
+ else:
51
+ x = self.norm(x)
52
+ x = self.pwconv1(x)
53
+ x = self.act(x)
54
+ x = self.pwconv2(x)
55
+ if self.gamma is not None:
56
+ x = self.gamma * x
57
+ x = x.transpose(1, 2) # (B, T, C) -> (B, C, T)
58
+
59
+ x = residual + x
60
+ return x
61
+
62
+
63
+ class AdaLayerNorm(nn.Module):
64
+ """
65
+ Adaptive Layer Normalization module with learnable embeddings per `num_embeddings` classes
66
+
67
+ Args:
68
+ num_embeddings (int): Number of embeddings.
69
+ embedding_dim (int): Dimension of the embeddings.
70
+ """
71
+
72
+ def __init__(self, num_embeddings: int, embedding_dim: int, eps: float = 1e-6):
73
+ super().__init__()
74
+ self.eps = eps
75
+ self.dim = embedding_dim
76
+ self.scale = nn.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_dim)
77
+ self.shift = nn.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_dim)
78
+ torch.nn.init.ones_(self.scale.weight)
79
+ torch.nn.init.zeros_(self.shift.weight)
80
+
81
+ def forward(self, x: torch.Tensor, cond_embedding_id: torch.Tensor) -> torch.Tensor:
82
+ scale = self.scale(cond_embedding_id)
83
+ shift = self.shift(cond_embedding_id)
84
+ x = nn.functional.layer_norm(x, (self.dim,), eps=self.eps)
85
+ x = x * scale + shift
86
+ return x
87
+
88
+
89
+ class ResBlock1(nn.Module):
90
+ """
91
+ ResBlock adapted from HiFi-GAN V1 (https://github.com/jik876/hifi-gan) with dilated 1D convolutions,
92
+ but without upsampling layers.
93
+
94
+ Args:
95
+ dim (int): Number of input channels.
96
+ kernel_size (int, optional): Size of the convolutional kernel. Defaults to 3.
97
+ dilation (tuple[int], optional): Dilation factors for the dilated convolutions.
98
+ Defaults to (1, 3, 5).
99
+ lrelu_slope (float, optional): Negative slope of the LeakyReLU activation function.
100
+ Defaults to 0.1.
101
+ layer_scale_init_value (float, optional): Initial value for the layer scale. None means no scaling.
102
+ Defaults to None.
103
+ """
104
+
105
+ def __init__(
106
+ self,
107
+ dim: int,
108
+ kernel_size: int = 3,
109
+ dilation: Tuple[int, int, int] = (1, 3, 5),
110
+ lrelu_slope: float = 0.1,
111
+ layer_scale_init_value: Optional[float] = None,
112
+ ):
113
+ super().__init__()
114
+ self.lrelu_slope = lrelu_slope
115
+ self.convs1 = nn.ModuleList(
116
+ [
117
+ weight_norm(
118
+ nn.Conv1d(
119
+ dim,
120
+ dim,
121
+ kernel_size,
122
+ 1,
123
+ dilation=dilation[0],
124
+ padding=self.get_padding(kernel_size, dilation[0]),
125
+ )
126
+ ),
127
+ weight_norm(
128
+ nn.Conv1d(
129
+ dim,
130
+ dim,
131
+ kernel_size,
132
+ 1,
133
+ dilation=dilation[1],
134
+ padding=self.get_padding(kernel_size, dilation[1]),
135
+ )
136
+ ),
137
+ weight_norm(
138
+ nn.Conv1d(
139
+ dim,
140
+ dim,
141
+ kernel_size,
142
+ 1,
143
+ dilation=dilation[2],
144
+ padding=self.get_padding(kernel_size, dilation[2]),
145
+ )
146
+ ),
147
+ ]
148
+ )
149
+
150
+ self.convs2 = nn.ModuleList(
151
+ [
152
+ weight_norm(nn.Conv1d(dim, dim, kernel_size, 1, dilation=1, padding=self.get_padding(kernel_size, 1))),
153
+ weight_norm(nn.Conv1d(dim, dim, kernel_size, 1, dilation=1, padding=self.get_padding(kernel_size, 1))),
154
+ weight_norm(nn.Conv1d(dim, dim, kernel_size, 1, dilation=1, padding=self.get_padding(kernel_size, 1))),
155
+ ]
156
+ )
157
+
158
+ self.gamma = nn.ParameterList(
159
+ [
160
+ nn.Parameter(layer_scale_init_value * torch.ones(dim, 1), requires_grad=True)
161
+ if layer_scale_init_value is not None
162
+ else None,
163
+ nn.Parameter(layer_scale_init_value * torch.ones(dim, 1), requires_grad=True)
164
+ if layer_scale_init_value is not None
165
+ else None,
166
+ nn.Parameter(layer_scale_init_value * torch.ones(dim, 1), requires_grad=True)
167
+ if layer_scale_init_value is not None
168
+ else None,
169
+ ]
170
+ )
171
+
172
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
173
+ for c1, c2, gamma in zip(self.convs1, self.convs2, self.gamma):
174
+ xt = torch.nn.functional.leaky_relu(x, negative_slope=self.lrelu_slope)
175
+ xt = c1(xt)
176
+ xt = torch.nn.functional.leaky_relu(xt, negative_slope=self.lrelu_slope)
177
+ xt = c2(xt)
178
+ if gamma is not None:
179
+ xt = gamma * xt
180
+ x = xt + x
181
+ return x
182
+
183
+ def remove_weight_norm(self):
184
+ for l in self.convs1:
185
+ remove_weight_norm(l)
186
+ for l in self.convs2:
187
+ remove_weight_norm(l)
188
+
189
+ @staticmethod
190
+ def get_padding(kernel_size: int, dilation: int = 1) -> int:
191
+ return int((kernel_size * dilation - dilation) / 2)
192
+
193
+
194
+ def safe_log(x: torch.Tensor, clip_val: float = 1e-7) -> torch.Tensor:
195
+ """
196
+ Computes the element-wise logarithm of the input tensor with clipping to avoid near-zero values.
197
+
198
+ Args:
199
+ x (Tensor): Input tensor.
200
+ clip_val (float, optional): Minimum value to clip the input tensor. Defaults to 1e-7.
201
+
202
+ Returns:
203
+ Tensor: Element-wise logarithm of the input tensor with clipping applied.
204
+ """
205
+ return torch.log(torch.clip(x, min=clip_val))
206
+
207
+
208
+ def symlog(x: torch.Tensor) -> torch.Tensor:
209
+ return torch.sign(x) * torch.log1p(x.abs())
210
+
211
+
212
+ def symexp(x: torch.Tensor) -> torch.Tensor:
213
+ return torch.sign(x) * (torch.exp(x.abs()) - 1)