lt-tensor 0.0.1a14__py3-none-any.whl → 0.0.1a16__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,196 +0,0 @@
1
- from lt_tensor.torch_commons import *
2
- import torch.nn.functional as F
3
- from lt_tensor.model_base import Model
4
- from lt_utils.common import *
5
-
6
-
7
- class PeriodDiscriminator(Model):
8
- def __init__(
9
- self,
10
- period: int,
11
- use_spectral_norm=False,
12
- kernel_size: int = 5,
13
- stride: int = 3,
14
- ):
15
- super().__init__()
16
- self.period = period
17
- self.stride = stride
18
- self.kernel_size = kernel_size
19
- self.norm_f = weight_norm if use_spectral_norm == False else spectral_norm
20
-
21
- self.channels = [32, 128, 512, 1024, 1024]
22
- self.first_pass = nn.Sequential(
23
- self.norm_f(
24
- nn.Conv2d(
25
- 1, self.channels[0], (kernel_size, 1), (stride, 1), padding=(2, 0)
26
- )
27
- ),
28
- nn.LeakyReLU(0.1),
29
- )
30
-
31
- self.convs = nn.ModuleList(
32
- [
33
- self._get_next(self.channels[i + 1], self.channels[i], i == 3)
34
- for i in range(4)
35
- ]
36
- )
37
-
38
- self.post_conv = nn.Conv2d(1024, 1, (stride, 1), 1, padding=(1, 0))
39
-
40
- def _get_next(self, out_dim: int, last_in: int, is_last: bool = False):
41
- stride = (self.stride, 1) if not is_last else 1
42
-
43
- return nn.Sequential(
44
- self.norm_f(
45
- nn.Conv2d(
46
- last_in,
47
- out_dim,
48
- (self.kernel_size, 1),
49
- stride,
50
- padding=(2, 0),
51
- )
52
- ),
53
- nn.LeakyReLU(0.1),
54
- )
55
-
56
- def forward(self, x: torch.Tensor):
57
- """
58
- x: (B, T)
59
- """
60
- b, t = x.shape
61
- if t % self.period != 0:
62
- pad_len = self.period - (t % self.period)
63
- x = F.pad(x, (0, pad_len), mode="reflect")
64
- t = t + pad_len
65
-
66
- x = x.view(b, 1, t // self.period, self.period) # (B, 1, T//P, P)
67
-
68
- f_map = []
69
- x = self.first_pass(x)
70
- f_map.append(x)
71
- for conv in self.convs:
72
- x = conv(x)
73
- f_map.append(x)
74
- x = self.post_conv(x)
75
- f_map.append(x)
76
- return x.flatten(1, -1), f_map
77
-
78
-
79
- class ScaleDiscriminator(nn.Module):
80
- def __init__(self, use_spectral_norm=False):
81
- super().__init__()
82
- norm_f = weight_norm if use_spectral_norm == False else spectral_norm
83
- self.activation = nn.LeakyReLU(0.1)
84
- self.convs = nn.ModuleList(
85
- [
86
- norm_f(nn.Conv1d(1, 128, 15, 1, padding=7)),
87
- norm_f(nn.Conv1d(128, 128, 41, 2, groups=4, padding=20)),
88
- norm_f(nn.Conv1d(128, 256, 41, 2, groups=16, padding=20)),
89
- norm_f(nn.Conv1d(256, 512, 41, 4, groups=16, padding=20)),
90
- norm_f(nn.Conv1d(512, 1024, 41, 4, groups=16, padding=20)),
91
- norm_f(nn.Conv1d(1024, 1024, 41, 1, groups=16, padding=20)),
92
- norm_f(nn.Conv1d(1024, 1024, 5, 1, padding=2)),
93
- ]
94
- )
95
- self.post_conv = norm_f(nn.Conv1d(1024, 1, 3, 1, padding=1))
96
-
97
- def forward(self, x: torch.Tensor):
98
- """
99
- x: (B, T)
100
- """
101
- f_map = []
102
- x = x.unsqueeze(1) # (B, 1, T)
103
- for conv in self.convs:
104
- x = self.activation(conv(x))
105
- f_map.append(x)
106
- x = self.post_conv(x)
107
- f_map.append(x)
108
- return x.flatten(1, -1), f_map
109
-
110
-
111
- class MultiScaleDiscriminator(Model):
112
- def __init__(self, layers: int = 3):
113
- super().__init__()
114
- self.pooling = nn.AvgPool1d(4, 2, padding=2)
115
- self.discriminators = nn.ModuleList(
116
- [ScaleDiscriminator(i == 0) for i in range(layers)]
117
- )
118
-
119
- def forward(self, x: torch.Tensor):
120
- """
121
- x: (B, T)
122
- Returns: list of outputs from each scale discriminator
123
- """
124
- outputs = []
125
- features = []
126
- for i, d in enumerate(self.discriminators):
127
- if i != 0:
128
- x = self.pooling(x)
129
- out, f_map = d(x)
130
- outputs.append(out)
131
- features.append(f_map)
132
- return outputs, features
133
-
134
-
135
- class MultiPeriodDiscriminator(Model):
136
- def __init__(self, periods: List[int] = [2, 3, 5, 7, 11]):
137
- super().__init__()
138
- self.discriminators = nn.ModuleList([PeriodDiscriminator(p) for p in periods])
139
-
140
- def forward(self, x: torch.Tensor):
141
- """
142
- x: (B, T)
143
- Returns: list of tuples of outputs from each period discriminator and the f_map.
144
- """
145
- # torch.log(torch.clip(x, min=clip_val))
146
- out_map = []
147
- feat_map = []
148
- for d in self.discriminators:
149
- out, feat = d(x)
150
- out_map.append(out)
151
- feat_map.append(feat)
152
- return out_map, feat_map
153
-
154
-
155
- def discriminator_loss(real_out_map, fake_out_map):
156
- loss = 0.0
157
- rl, fl = [], []
158
- for real_out, fake_out in zip(real_out_map, fake_out_map):
159
- real_loss = torch.mean((1.0 - real_out) ** 2)
160
- fake_loss = torch.mean(fake_out**2)
161
- loss += real_loss + fake_loss
162
- rl.append(real_loss.item())
163
- fl.append(fake_loss.item())
164
- return loss, sum(rl), sum(fl)
165
-
166
-
167
- def generator_adv_loss(fake_disc_outputs: List[Tensor]):
168
- loss = 0.0
169
- for fake_out in fake_disc_outputs:
170
- fake_score = fake_out[0]
171
- loss += -torch.mean(fake_score)
172
- return loss
173
-
174
-
175
- def feature_loss(
176
- fmap_r,
177
- fmap_g,
178
- weight=2.0,
179
- loss_fn: Callable[[Tensor, Tensor], Tensor] = F.l1_loss,
180
- ):
181
- loss = 0.0
182
- for dr, dg in zip(fmap_r, fmap_g):
183
- for rl, gl in zip(dr, dg):
184
- loss += loss_fn(rl - gl)
185
- return loss * weight
186
-
187
-
188
- def generator_loss(disc_generated_outputs):
189
- loss = 0.0
190
- gen_losses = []
191
- for dg in disc_generated_outputs:
192
- l = torch.mean((1.0 - dg) ** 2)
193
- gen_losses.append(l.item())
194
- loss += l
195
-
196
- return loss, gen_losses
@@ -1,5 +0,0 @@
1
- from .generator import iSTFTGenerator
2
- from . import trainer
3
-
4
-
5
- __all__ = ["iSTFTGenerator", "trainer"]
@@ -1,90 +0,0 @@
1
- __all__ = ["iSTFTGenerator"]
2
- from lt_utils.common import *
3
- from lt_tensor.torch_commons import *
4
- from lt_tensor.model_zoo.residual import ConvNets, ResBlocks
5
-
6
-
7
- class iSTFTGenerator(ConvNets):
8
- def __init__(
9
- self,
10
- in_channels: int = 80,
11
- upsample_rates: List[Union[int, List[int]]] = [8, 8],
12
- upsample_kernel_sizes: List[Union[int, List[int]]] = [16, 16],
13
- upsample_initial_channel: int = 512,
14
- resblock_kernel_sizes: List[Union[int, List[int]]] = [3, 7, 11],
15
- resblock_dilation_sizes: List[Union[int, List[int]]] = [
16
- [1, 3, 5],
17
- [1, 3, 5],
18
- [1, 3, 5],
19
- ],
20
- n_fft: int = 16,
21
- activation: nn.Module = nn.LeakyReLU(0.1),
22
- hop_length: int = 256,
23
- ):
24
- super().__init__()
25
- self.num_kernels = len(resblock_kernel_sizes)
26
- self.num_upsamples = len(upsample_rates)
27
- self.hop_length = hop_length
28
- self.conv_pre = weight_norm(
29
- nn.Conv1d(in_channels, upsample_initial_channel, 7, 1, padding=3)
30
- )
31
- self.blocks = nn.ModuleList()
32
- self.activation = activation
33
- for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
34
- self.blocks.append(
35
- self._make_blocks(
36
- (i, k, u),
37
- upsample_initial_channel,
38
- resblock_kernel_sizes,
39
- resblock_dilation_sizes,
40
- )
41
- )
42
-
43
- ch = upsample_initial_channel // (2 ** (i + 1))
44
- self.post_n_fft = n_fft // 2 + 1
45
- self.conv_post = weight_norm(nn.Conv1d(ch, n_fft + 2, 7, 1, padding=3))
46
- self.conv_post.apply(self.init_weights)
47
- self.reflection_pad = nn.ReflectionPad1d((1, 0))
48
-
49
- def _make_blocks(
50
- self,
51
- state: Tuple[int, int, int],
52
- upsample_initial_channel: int,
53
- resblock_kernel_sizes: List[Union[int, List[int]]],
54
- resblock_dilation_sizes: List[int | List[int]],
55
- ):
56
- i, k, u = state
57
- channels = upsample_initial_channel // (2 ** (i + 1))
58
- return nn.ModuleDict(
59
- dict(
60
- up=nn.Sequential(
61
- self.activation,
62
- weight_norm(
63
- nn.ConvTranspose1d(
64
- upsample_initial_channel // (2**i),
65
- channels,
66
- k,
67
- u,
68
- padding=(k - u) // 2,
69
- )
70
- ).apply(self.init_weights),
71
- ),
72
- residual=ResBlocks(
73
- channels,
74
- resblock_kernel_sizes,
75
- resblock_dilation_sizes,
76
- self.activation,
77
- ),
78
- )
79
- )
80
-
81
- def forward(self, x):
82
- x = self.conv_pre(x)
83
- for block in self.blocks:
84
- x = block["up"](x)
85
- x = block["residual"](x)
86
-
87
- x = self.conv_post(self.activation(self.reflection_pad(x)))
88
- spec = torch.exp(x[:, : self.post_n_fft, :])
89
- phase = torch.sin(x[:, self.post_n_fft :, :])
90
- return spec, phase
@@ -1,142 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import math
4
- from einops import repeat
5
-
6
-
7
- class SineGen(nn.Module):
8
- def __init__(
9
- self,
10
- samp_rate,
11
- upsample_scale,
12
- harmonic_num=0,
13
- sine_amp=0.1,
14
- noise_std=0.003,
15
- voiced_threshold=0,
16
- flag_for_pulse=False,
17
- ):
18
- super().__init__()
19
- self.sampling_rate = samp_rate
20
- self.upsample_scale = upsample_scale
21
- self.harmonic_num = harmonic_num
22
- self.sine_amp = sine_amp
23
- self.noise_std = noise_std
24
- self.voiced_threshold = voiced_threshold
25
- self.flag_for_pulse = flag_for_pulse
26
- self.dim = self.harmonic_num + 1 # fundamental + harmonics
27
-
28
- def _f02uv_b(self, f0):
29
- return (f0 > self.voiced_threshold).float() # [B, T]
30
-
31
- def _f02uv(self, f0):
32
- return (f0 > self.voiced_threshold).float().unsqueeze(-1) # -> (B, T, 1)
33
-
34
- @torch.no_grad()
35
- def _f02sine(self, f0_values):
36
- """
37
- f0_values: (B, T, 1)
38
- Output: sine waves (B, T * upsample, dim)
39
- """
40
- B, T, _ = f0_values.size()
41
- f0_upsampled = repeat(
42
- f0_values, "b t d -> b (t r) d", r=self.upsample_scale
43
- ) # (B, T_up, 1)
44
-
45
- # Create harmonics
46
- harmonics = (
47
- torch.arange(1, self.dim + 1, device=f0_values.device)
48
- .float()
49
- .view(1, 1, -1)
50
- )
51
- f0_harm = f0_upsampled * harmonics # (B, T_up, dim)
52
-
53
- # Convert Hz to radians (2πf/sr), then integrate to get phase
54
- rad_values = f0_harm / self.sampling_rate # normalized freq
55
- rad_values = rad_values % 1.0 # remove multiples of 2π
56
-
57
- # Random initial phase for each harmonic (except 0th if pulse mode)
58
- if self.flag_for_pulse:
59
- rand_ini = torch.zeros((B, 1, self.dim), device=f0_values.device)
60
- else:
61
- rand_ini = torch.rand((B, 1, self.dim), device=f0_values.device)
62
-
63
- rand_ini = rand_ini * 2 * math.pi
64
-
65
- # Compute cumulative phase
66
- rad_values = rad_values * 2 * math.pi
67
- phase = torch.cumsum(rad_values, dim=1) + rand_ini # (B, T_up, dim)
68
-
69
- sine_waves = torch.sin(phase) # (B, T_up, dim)
70
- return sine_waves
71
-
72
- def _forward(self, f0):
73
- """
74
- f0: (B, T, 1)
75
- returns: sine signal with harmonics and noise added
76
- """
77
- sine_waves = self._f02sine(f0) # (B, T_up, dim)
78
- uv = self._f02uv_b(f0) # (B, T, 1)
79
- uv = repeat(uv, "b t d -> b (t r) d", r=self.upsample_scale) # (B, T_up, 1)
80
-
81
- # voiced sine + unvoiced noise
82
- sine_signal = self.sine_amp * sine_waves * uv # (B, T_up, dim)
83
- noise = torch.randn_like(sine_signal) * self.noise_std
84
- output = sine_signal + noise * (1.0 - uv) # noise added only on unvoiced
85
-
86
- return output # (B, T_up, dim)
87
-
88
- def forward(self, f0):
89
- """
90
- Args:
91
- f0: (B, T) in Hz (before upsampling)
92
- Returns:
93
- sine_waves: (B, T_up, dim)
94
- uv: (B, T_up, 1)
95
- noise: (B, T_up, 1)
96
- """
97
- B, T = f0.shape
98
- device = f0.device
99
-
100
- # Get uv mask (before upsampling)
101
- uv = self._f02uv(f0) # (B, T, 1)
102
-
103
- # Expand f0 to include harmonics: (B, T, dim)
104
- f0 = f0.unsqueeze(-1) # (B, T, 1)
105
- harmonics = (
106
- torch.arange(1, self.dim + 1, device=device).float().view(1, 1, -1)
107
- ) # (1, 1, dim)
108
- f0_harm = f0 * harmonics # (B, T, dim)
109
-
110
- # Upsample
111
- f0_harm_up = repeat(
112
- f0_harm, "b t d -> b (t r) d", r=self.upsample_scale
113
- ) # (B, T_up, dim)
114
- uv_up = repeat(uv, "b t d -> b (t r) d", r=self.upsample_scale) # (B, T_up, 1)
115
-
116
- # Convert to radians
117
- rad_per_sample = f0_harm_up / self.sampling_rate # Hz → cycles/sample
118
- rad_per_sample = rad_per_sample * 2 * math.pi # cycles → radians/sample
119
-
120
- # Random phase init for each sample
121
- B, T_up, D = rad_per_sample.shape
122
- rand_phase = torch.rand(B, D, device=device) * 2 * math.pi # (B, D)
123
-
124
- # Compute cumulative phase
125
- phase = torch.cumsum(rad_per_sample, dim=1) + rand_phase.unsqueeze(
126
- 1
127
- ) # (B, T_up, D)
128
-
129
- # Apply sine
130
- sine_waves = torch.sin(phase) * self.sine_amp # (B, T_up, D)
131
-
132
- # Handle unvoiced: create noise only for fundamental
133
- noise = torch.randn(B, T_up, 1, device=device) * self.noise_std
134
- if self.flag_for_pulse:
135
- # If pulse mode is on, align phase at start of voiced segments
136
- # Optional and tricky to implement — may require segmenting uv
137
- pass
138
-
139
- # Replace sine by noise for unvoiced (only on fundamental)
140
- sine_waves[:, :, 0:1] = sine_waves[:, :, 0:1] * uv_up + noise * (1 - uv_up)
141
-
142
- return sine_waves, uv_up, noise