lt-tensor 0.0.1a11__py3-none-any.whl → 0.0.1a13__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.
@@ -0,0 +1,475 @@
1
+ __all__ = ["AudioSettings", "AudioDecoder"]
2
+ import gc
3
+ import math
4
+ import itertools
5
+ from lt_utils.common import *
6
+ import torch.nn.functional as F
7
+ from lt_tensor.torch_commons import *
8
+ from lt_tensor.model_base import Model
9
+ from lt_tensor.misc_utils import log_tensor
10
+ from lt_utils.misc_utils import log_traceback
11
+ from lt_tensor.processors import AudioProcessor
12
+ from lt_tensor.misc_utils import set_seed, clear_cache
13
+ from lt_utils.type_utils import is_dir, is_pathlike, is_file
14
+ from lt_tensor.config_templates import updateDict, ModelConfig
15
+ from lt_tensor.model_zoo.istft.generator import iSTFTGenerator
16
+ from lt_tensor.model_zoo.residual import ResBlock1D, ConvNets, get_weight_norm
17
+ from lt_tensor.model_zoo.discriminator import MultiPeriodDiscriminator, MultiScaleDiscriminator
18
+
19
+
20
+ def feature_loss(fmap_r, fmap_g):
21
+ loss = 0
22
+ for dr, dg in zip(fmap_r, fmap_g):
23
+ for rl, gl in zip(dr, dg):
24
+ loss += torch.mean(torch.abs(rl - gl))
25
+ return loss * 2
26
+
27
+
28
+ def generator_adv_loss(disc_outputs):
29
+ loss = 0
30
+ for dg in disc_outputs:
31
+ l = torch.mean((1 - dg) ** 2)
32
+
33
+ loss += l
34
+ return loss
35
+
36
+
37
+ def discriminator_loss(disc_real_outputs, disc_generated_outputs):
38
+ loss = 0
39
+
40
+ for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
41
+ r_loss = torch.mean((1 - dr) ** 2)
42
+ g_loss = torch.mean(dg**2)
43
+ loss += r_loss + g_loss
44
+ return loss
45
+
46
+
47
+ """def feature_loss(fmap_r, fmap_g):
48
+ loss = 0
49
+ for dr, dg in zip(fmap_r, fmap_g):
50
+ for rl, gl in zip(dr, dg):
51
+ loss += torch.mean(torch.abs(rl - gl))
52
+ return loss * 2
53
+
54
+
55
+ def generator_adv_loss(fake_preds):
56
+ loss = 0.0
57
+ for f in fake_preds:
58
+ loss += torch.mean((f - 1.0) ** 2)
59
+ return loss
60
+
61
+
62
+ def discriminator_loss(real_preds, fake_preds):
63
+ loss = 0.0
64
+ for r, f in zip(real_preds, fake_preds):
65
+ loss += torch.mean((r - 1.0) ** 2) + torch.mean(f**2)
66
+ return loss
67
+ """
68
+
69
+
70
+ class AudioSettings(ModelConfig):
71
+ def __init__(
72
+ self,
73
+ n_mels: int = 80,
74
+ upsample_rates: List[Union[int, List[int]]] = [8, 8],
75
+ upsample_kernel_sizes: List[Union[int, List[int]]] = [16, 16],
76
+ upsample_initial_channel: int = 512,
77
+ resblock_kernel_sizes: List[Union[int, List[int]]] = [3, 7, 11],
78
+ resblock_dilation_sizes: List[Union[int, List[int]]] = [
79
+ [1, 3, 5],
80
+ [1, 3, 5],
81
+ [1, 3, 5],
82
+ ],
83
+ n_fft: int = 16,
84
+ activation: nn.Module = nn.LeakyReLU(0.1),
85
+ msd_layers: int = 3,
86
+ mpd_periods: List[int] = [2, 3, 5, 7, 11],
87
+ seed: Optional[int] = None,
88
+ lr: float = 1e-5,
89
+ adamw_betas: List[float] = [0.75, 0.98],
90
+ scheduler_template: Callable[
91
+ [optim.Optimizer], optim.lr_scheduler.LRScheduler
92
+ ] = lambda optimizer: optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.998),
93
+ ):
94
+ self.in_channels = n_mels
95
+ self.upsample_rates = upsample_rates
96
+ self.upsample_kernel_sizes = upsample_kernel_sizes
97
+ self.upsample_initial_channel = upsample_initial_channel
98
+ self.resblock_kernel_sizes = resblock_kernel_sizes
99
+ self.resblock_dilation_sizes = resblock_dilation_sizes
100
+ self.n_fft = n_fft
101
+ self.activation = activation
102
+ self.mpd_periods = mpd_periods
103
+ self.msd_layers = msd_layers
104
+ self.seed = seed
105
+ self.lr = lr
106
+ self.adamw_betas = adamw_betas
107
+ self.scheduler_template = scheduler_template
108
+
109
+
110
+ class AudioDecoder(Model):
111
+ def __init__(
112
+ self,
113
+ audio_processor: AudioProcessor,
114
+ settings: Optional[AudioSettings] = None,
115
+ generator: Optional[Union[Model, "iSTFTGenerator"]] = None, # non initalized!
116
+ ):
117
+ super().__init__()
118
+ if settings is None:
119
+ self.settings = AudioSettings()
120
+ elif isinstance(settings, dict):
121
+ self.settings = AudioSettings(**settings)
122
+ elif isinstance(settings, AudioSettings):
123
+ self.settings = settings
124
+ else:
125
+ raise ValueError(
126
+ "Cannot initialize the waveDecoder with the given settings. "
127
+ "Use either a dictionary, or the class WaveSettings to setup the settings. "
128
+ "Alternatively, leave it None to use the default values."
129
+ )
130
+ if self.settings.seed is not None:
131
+ set_seed(self.settings.seed)
132
+ if generator is None:
133
+ generator = iSTFTGenerator
134
+ self.generator: iSTFTGenerator = generator(
135
+ in_channels=self.settings.in_channels,
136
+ upsample_rates=self.settings.upsample_rates,
137
+ upsample_kernel_sizes=self.settings.upsample_kernel_sizes,
138
+ upsample_initial_channel=self.settings.upsample_initial_channel,
139
+ resblock_kernel_sizes=self.settings.resblock_kernel_sizes,
140
+ resblock_dilation_sizes=self.settings.resblock_dilation_sizes,
141
+ n_fft=self.settings.n_fft,
142
+ activation=self.settings.activation,
143
+ )
144
+ self.generator.eval()
145
+ self.g_optim = None
146
+ self.d_optim = None
147
+ self.gan_training = False
148
+ self.audio_processor = audio_processor
149
+ self.register_buffer("msd", None, persistent=False)
150
+ self.register_buffer("mpd", None, persistent=False)
151
+
152
+ def setup_training_mode(self, load_weights_from: Optional[PathLike] = None):
153
+ """The location must be path not a file!"""
154
+ self.finish_training_setup()
155
+ if self.msd is None:
156
+ self.msd = MultiScaleDiscriminator(self.settings.msd_layers)
157
+ if self.mpd is None:
158
+ self.mpd = MultiPeriodDiscriminator(self.settings.mpd_periods)
159
+ if load_weights_from is not None:
160
+ if is_dir(path=load_weights_from, validate=False):
161
+ try:
162
+ self.msd.load_weights(Path(load_weights_from, "msd.pt"))
163
+ except Exception as e:
164
+ log_traceback(e, "MSD Loading")
165
+ try:
166
+ self.mpd.load_weights(Path(load_weights_from, "mpd.pt"))
167
+ except Exception as e:
168
+ log_traceback(e, "MPD Loading")
169
+
170
+ self.update_schedulers_and_optimizer()
171
+ self.msd.to(device=self.device)
172
+ self.mpd.to(device=self.device)
173
+
174
+ self.gan_training = True
175
+ return True
176
+
177
+ def update_schedulers_and_optimizer(self):
178
+ self.g_optim = optim.AdamW(
179
+ self.generator.parameters(),
180
+ lr=self.settings.lr,
181
+ betas=self.settings.adamw_betas,
182
+ )
183
+ self.g_scheduler = self.settings.scheduler_template(self.g_optim)
184
+ if any([self.mpd is None, self.msd is None]):
185
+ return
186
+ self.d_optim = optim.AdamW(
187
+ itertools.chain(self.mpd.parameters(), self.msd.parameters()),
188
+ lr=self.settings.lr,
189
+ betas=self.settings.adamw_betas,
190
+ )
191
+ self.d_scheduler = self.settings.scheduler_template(self.d_optim)
192
+
193
+ def set_lr(self, new_lr: float = 1e-4):
194
+ if self.g_optim is not None:
195
+ for groups in self.g_optim.param_groups:
196
+ groups["lr"] = new_lr
197
+
198
+ if self.d_optim is not None:
199
+ for groups in self.d_optim.param_groups:
200
+ groups["lr"] = new_lr
201
+ return self.get_lr()
202
+
203
+ def get_lr(self) -> Tuple[float, float]:
204
+ g = float("nan")
205
+ d = float("nan")
206
+ if self.g_optim is not None:
207
+ g = self.g_optim.param_groups[0]["lr"]
208
+ if self.d_optim is not None:
209
+ d = self.d_optim.param_groups[0]["lr"]
210
+ return g, d
211
+
212
+ def save_weights(self, path, replace=True):
213
+ is_pathlike(path, check_if_empty=True, validate=True)
214
+ if str(path).endswith(".pt"):
215
+ path = Path(path).parent
216
+ else:
217
+ path = Path(path)
218
+ self.generator.save_weights(Path(path, "generator.pt"), replace)
219
+ if self.msd is not None:
220
+ self.msd.save_weights(Path(path, "msp.pt"), replace)
221
+ if self.mpd is not None:
222
+ self.mpd.save_weights(Path(path, "mpd.pt"), replace)
223
+
224
+ def load_weights(
225
+ self,
226
+ path,
227
+ raise_if_not_exists=False,
228
+ strict=True,
229
+ assign=False,
230
+ weights_only=False,
231
+ mmap=None,
232
+ **torch_loader_kwargs
233
+ ):
234
+ is_pathlike(path, check_if_empty=True, validate=True)
235
+ if str(path).endswith(".pt"):
236
+ path = Path(path)
237
+ else:
238
+ path = Path(path, "generator.pt")
239
+
240
+ self.generator.load_weights(
241
+ path,
242
+ raise_if_not_exists,
243
+ strict,
244
+ assign,
245
+ weights_only,
246
+ mmap,
247
+ **torch_loader_kwargs,
248
+ )
249
+
250
+ def finish_training_setup(self):
251
+ gc.collect()
252
+ self.mpd = None
253
+ clear_cache()
254
+ gc.collect()
255
+ self.msd = None
256
+ clear_cache()
257
+ self.gan_training = False
258
+
259
+ def forward(self, mel_spec: Tensor) -> Tuple[Tensor, Tensor]:
260
+ """Returns the generated spec and phase"""
261
+ return self.generator.forward(mel_spec)
262
+
263
+ def inference(
264
+ self,
265
+ mel_spec: Tensor,
266
+ return_dict: bool = False,
267
+ ) -> Union[Dict[str, Tensor], Tensor]:
268
+ spec, phase = super().inference(mel_spec)
269
+ wave = self.audio_processor.inverse_transform(
270
+ spec,
271
+ phase,
272
+ self.settings.n_fft,
273
+ hop_length=4,
274
+ win_length=self.settings.n_fft,
275
+ )
276
+ if not return_dict:
277
+ return wave[:, : wave.shape[-1] - 256]
278
+ return {
279
+ "wave": wave[:, : wave.shape[-1] - 256],
280
+ "spec": spec,
281
+ "phase": phase,
282
+ }
283
+
284
+ def set_device(self, device: str):
285
+ self.to(device=device)
286
+ self.generator.to(device=device)
287
+ self.audio_processor.to(device=device)
288
+ self.msd.to(device=device)
289
+ self.mpd.to(device=device)
290
+
291
+ def train_step(
292
+ self,
293
+ mels: Tensor,
294
+ real_audio: Tensor,
295
+ stft_scale: float = 1.0,
296
+ mel_scale: float = 1.0,
297
+ adv_scale: float = 1.0,
298
+ fm_scale: float = 1.0,
299
+ fm_add: float = 0.0,
300
+ is_discriminator_frozen: bool = False,
301
+ is_generator_frozen: bool = False,
302
+ ):
303
+ if not self.gan_training:
304
+ self.setup_training_mode()
305
+ spec, phase = super().train_step(mels)
306
+ real_audio = real_audio.squeeze(1)
307
+ fake_audio = self.audio_processor.inverse_transform(
308
+ spec,
309
+ phase,
310
+ self.settings.n_fft,
311
+ hop_length=4,
312
+ win_length=self.settings.n_fft,
313
+ # length=real_audio.shape[-1]
314
+ )[:, : real_audio.shape[-1]]
315
+
316
+ disc_kwargs = dict(
317
+ real_audio=real_audio,
318
+ fake_audio=fake_audio.detach(),
319
+ am_i_frozen=is_discriminator_frozen,
320
+ )
321
+ if is_discriminator_frozen:
322
+ with torch.no_grad():
323
+ disc_out = self._discriminator_step(**disc_kwargs)
324
+ else:
325
+ disc_out = self._discriminator_step(**disc_kwargs)
326
+
327
+ generato_kwargs = dict(
328
+ mels=mels,
329
+ real_audio=real_audio,
330
+ fake_audio=fake_audio,
331
+ **disc_out,
332
+ stft_scale=stft_scale,
333
+ mel_scale=mel_scale,
334
+ adv_scale=adv_scale,
335
+ fm_add=fm_add,
336
+ fm_scale=fm_scale,
337
+ am_i_frozen=is_generator_frozen,
338
+ )
339
+
340
+ if is_generator_frozen:
341
+ with torch.no_grad():
342
+ return self._generator_step(**generato_kwargs)
343
+ return self._generator_step(**generato_kwargs)
344
+
345
+ def _discriminator_step(
346
+ self,
347
+ real_audio: Tensor,
348
+ fake_audio: Tensor,
349
+ am_i_frozen: bool = False,
350
+ ):
351
+ # ========== Discriminator Forward Pass ==========
352
+
353
+ # MPD
354
+ real_mpd_preds, _ = self.mpd(real_audio)
355
+ fake_mpd_preds, _ = self.mpd(fake_audio)
356
+ # MSD
357
+ real_msd_preds, _ = self.msd(real_audio)
358
+ fake_msd_preds, _ = self.msd(fake_audio)
359
+
360
+ loss_d_mpd = discriminator_loss(real_mpd_preds, fake_mpd_preds)
361
+ loss_d_msd = discriminator_loss(real_msd_preds, fake_msd_preds)
362
+ loss_d = loss_d_mpd + loss_d_msd
363
+
364
+ if not am_i_frozen:
365
+ self.d_optim.zero_grad()
366
+ loss_d.backward()
367
+ self.d_optim.step()
368
+
369
+ return {
370
+ "loss_d": loss_d.item(),
371
+ }
372
+
373
+ def _generator_step(
374
+ self,
375
+ mels: Tensor,
376
+ real_audio: Tensor,
377
+ fake_audio: Tensor,
378
+ loss_d: float,
379
+ stft_scale: float = 1.0,
380
+ mel_scale: float = 1.0,
381
+ adv_scale: float = 1.0,
382
+ fm_scale: float = 1.0,
383
+ fm_add: float = 0.0,
384
+ am_i_frozen: bool = False,
385
+ ):
386
+ # ========== Generator Loss ==========
387
+ real_mpd_feats = self.mpd(real_audio)[1]
388
+ real_msd_feats = self.msd(real_audio)[1]
389
+
390
+ fake_mpd_preds, fake_mpd_feats = self.mpd(fake_audio)
391
+ fake_msd_preds, fake_msd_feats = self.msd(fake_audio)
392
+
393
+ loss_adv_mpd = generator_adv_loss(fake_mpd_preds)
394
+ loss_adv_msd = generator_adv_loss(fake_msd_preds)
395
+ loss_fm_mpd = feature_loss(real_mpd_feats, fake_mpd_feats)
396
+ loss_fm_msd = feature_loss(real_msd_feats, fake_msd_feats)
397
+
398
+ loss_stft = self.audio_processor.stft_loss(fake_audio, real_audio) * stft_scale
399
+ loss_mel = (
400
+ F.huber_loss(self.audio_processor.compute_mel(fake_audio), mels) * mel_scale
401
+ )
402
+ loss_fm = ((loss_fm_mpd + loss_fm_msd) * fm_scale) + fm_add
403
+
404
+ loss_adv = (loss_adv_mpd + loss_adv_msd) * adv_scale
405
+
406
+ loss_g = loss_adv + loss_fm + loss_stft # + loss_mel
407
+ if not am_i_frozen:
408
+ self.g_optim.zero_grad()
409
+ loss_g.backward()
410
+ self.g_optim.step()
411
+ return {
412
+ "loss_g": loss_g.item(),
413
+ "loss_d": loss_d,
414
+ "loss_adv": loss_adv.item(),
415
+ "loss_fm": loss_fm.item(),
416
+ "loss_stft": loss_stft.item(),
417
+ "loss_mel": loss_mel.item(),
418
+ "lr_g": self.g_optim.param_groups[0]["lr"],
419
+ "lr_d": self.d_optim.param_groups[0]["lr"],
420
+ }
421
+
422
+ def step_scheduler(
423
+ self, is_disc_frozen: bool = False, is_generator_frozen: bool = False
424
+ ):
425
+ if self.d_scheduler is not None and not is_disc_frozen:
426
+ self.d_scheduler.step()
427
+ if self.g_scheduler is not None and not is_generator_frozen:
428
+ self.g_scheduler.step()
429
+
430
+ def reset_schedulers(self, lr: Optional[float] = None):
431
+ """
432
+ In case you have adopted another strategy, with this function,
433
+ it is possible restart the scheduler and set the lr to another value.
434
+ """
435
+ if lr is not None:
436
+ self.set_lr(lr)
437
+ if self.d_optim is not None:
438
+ self.d_scheduler = None
439
+ self.d_scheduler = self.settings.scheduler_template(self.d_optim)
440
+ if self.g_optim is not None:
441
+ self.g_scheduler = None
442
+ self.g_scheduler = self.settings.scheduler_template(self.g_optim)
443
+
444
+
445
+ class ResBlocks(ConvNets):
446
+ def __init__(
447
+ self,
448
+ channels: int,
449
+ resblock_kernel_sizes: List[Union[int, List[int]]] = [3, 7, 11],
450
+ resblock_dilation_sizes: List[Union[int, List[int]]] = [
451
+ [1, 3, 5],
452
+ [1, 3, 5],
453
+ [1, 3, 5],
454
+ ],
455
+ activation: nn.Module = nn.LeakyReLU(0.1),
456
+ ):
457
+ super().__init__()
458
+ self.num_kernels = len(resblock_kernel_sizes)
459
+ self.rb = nn.ModuleList()
460
+ self.activation = activation
461
+
462
+ for k, j in zip(resblock_kernel_sizes, resblock_dilation_sizes):
463
+ self.rb.append(ResBlock1D(channels, k, j, activation))
464
+
465
+ self.rb.apply(self.init_weights)
466
+
467
+ def forward(self, x: torch.Tensor):
468
+ xs = None
469
+ for i, block in enumerate(self.rb):
470
+ if i == 0:
471
+ xs = block(x)
472
+ else:
473
+ xs += block(x)
474
+ x = xs / self.num_kernels
475
+ return self.activation(x)
@@ -5,8 +5,8 @@ __all__ = [
5
5
  ]
6
6
 
7
7
  import math
8
- from ..torch_commons import *
9
- from ..model_base import Model
8
+ from lt_tensor.torch_commons import *
9
+ from lt_tensor.model_base import Model
10
10
 
11
11
 
12
12
  class RotaryEmbedding(nn.Module):
@@ -0,0 +1,217 @@
1
+ __all__ = [
2
+ "spectral_norm_select",
3
+ "get_weight_norm",
4
+ "ResBlock1D",
5
+ "ResBlock2D",
6
+ "ResBlock1DShuffled",
7
+ "AdaResBlock1D",
8
+ ]
9
+ import math
10
+ from lt_utils.common import *
11
+ from lt_tensor.torch_commons import *
12
+ from lt_tensor.model_base import Model
13
+ from lt_tensor.misc_utils import log_tensor
14
+ import torch.nn.functional as F
15
+ from lt_tensor.model_zoo.fusion import AdaFusion1D, AdaIN1D
16
+
17
+
18
+ def spectral_norm_select(module: nn.Module, enabled: bool):
19
+ if enabled:
20
+ return spectral_norm(module)
21
+ return module
22
+
23
+
24
+ def get_weight_norm(norm_type: Optional[Literal["weight", "spectral"]] = None):
25
+ if not norm_type:
26
+ return lambda x: x
27
+ if norm_type == "weight":
28
+ return lambda x: weight_norm(x)
29
+ return lambda x: spectral_norm(x)
30
+
31
+
32
+ class ConvNets(Model):
33
+ def remove_weight_norm(self):
34
+ for module in self.modules():
35
+ try:
36
+ remove_weight_norm(module)
37
+ except ValueError:
38
+ pass
39
+
40
+ @staticmethod
41
+ def init_weights(m, mean=0.0, std=0.01):
42
+ classname = m.__class__.__name__
43
+ if "Conv" in classname:
44
+ m.weight.data.normal_(mean, std)
45
+
46
+
47
+ class ResBlock1D(ConvNets):
48
+ def __init__(
49
+ self,
50
+ channels,
51
+ kernel_size=3,
52
+ dilation=(1, 3, 5),
53
+ activation: nn.Module = nn.LeakyReLU(0.1),
54
+ ):
55
+ super().__init__()
56
+
57
+ self.conv_nets = nn.ModuleList(
58
+ [
59
+ self._get_conv_layer(i, channels, kernel_size, 1, dilation, activation)
60
+ for i in range(3)
61
+ ]
62
+ )
63
+ self.conv_nets.apply(self.init_weights)
64
+ self.last_index = len(self.conv_nets) - 1
65
+
66
+ def _get_conv_layer(self, id, ch, k, stride, d, actv):
67
+ get_padding = lambda ks, d: int((ks * d - d) / 2)
68
+ return nn.Sequential(
69
+ actv, # 1
70
+ weight_norm(
71
+ nn.Conv1d(
72
+ ch, ch, k, stride, dilation=d[id], padding=get_padding(k, d[id])
73
+ )
74
+ ), # 2
75
+ actv, # 3
76
+ weight_norm(
77
+ nn.Conv1d(ch, ch, k, stride, dilation=1, padding=get_padding(k, 1))
78
+ ), # 4
79
+ )
80
+
81
+ def forward(self, x: Tensor):
82
+ for cnn in self.conv_nets:
83
+ x = cnn(x) + x
84
+ return x
85
+
86
+
87
+ class ResBlock1DShuffled(ConvNets):
88
+ def __init__(
89
+ self,
90
+ channels,
91
+ kernel_size=3,
92
+ dilation=(1, 3, 5),
93
+ activation: nn.Module = nn.LeakyReLU(0.1),
94
+ add_channel_shuffle: bool = False, # requires pytorch 2.7.0 +
95
+ channel_shuffle_groups=1,
96
+ ):
97
+ super().__init__()
98
+
99
+ self.channel_shuffle = (
100
+ nn.ChannelShuffle(channel_shuffle_groups)
101
+ if add_channel_shuffle
102
+ else nn.Identity()
103
+ )
104
+
105
+ self.conv_nets = nn.ModuleList(
106
+ [
107
+ self._get_conv_layer(i, channels, kernel_size, 1, dilation, activation)
108
+ for i in range(3)
109
+ ]
110
+ )
111
+ self.conv_nets.apply(self.init_weights)
112
+ self.last_index = len(self.conv_nets) - 1
113
+
114
+ def _get_conv_layer(self, id, ch, k, stride, d, actv):
115
+ get_padding = lambda ks, d: int((ks * d - d) / 2)
116
+ return nn.Sequential(
117
+ actv, # 1
118
+ weight_norm(
119
+ nn.Conv1d(
120
+ ch, ch, k, stride, dilation=d[id], padding=get_padding(k, d[id])
121
+ )
122
+ ), # 2
123
+ actv, # 3
124
+ weight_norm(
125
+ nn.Conv1d(ch, ch, k, stride, dilation=1, padding=get_padding(k, 1))
126
+ ), # 4
127
+ )
128
+
129
+ def forward(self, x: Tensor):
130
+ b = x.clone() * 0.5
131
+ for cnn in self.conv_nets:
132
+ x = cnn(self.channel_shuffle(x)) + b
133
+ return x
134
+
135
+
136
+ class ResBlock2D(Model):
137
+ def __init__(
138
+ self,
139
+ in_channels,
140
+ out_channels,
141
+ downsample=False,
142
+ ):
143
+ super().__init__()
144
+ stride = 2 if downsample else 1
145
+
146
+ self.block = nn.Sequential(
147
+ nn.Conv2d(in_channels, out_channels, 3, stride, 1),
148
+ nn.LeakyReLU(0.2),
149
+ nn.Conv2d(out_channels, out_channels, 3, 1, 1),
150
+ )
151
+
152
+ self.skip = nn.Identity()
153
+ if downsample or in_channels != out_channels:
154
+ self.skip = spectral_norm_select(
155
+ nn.Conv2d(in_channels, out_channels, 1, stride)
156
+ )
157
+ # on less to be handled every cicle
158
+ self.sqrt_2 = math.sqrt(2)
159
+
160
+ def forward(self, x: Tensor):
161
+ return (self.block(x) + self.skip(x)) / self.sqrt_2
162
+
163
+
164
+ class AdaResBlock1D(ConvNets):
165
+ def __init__(
166
+ self,
167
+ res_block_channels: int,
168
+ ada_channel_in: int,
169
+ kernel_size=3,
170
+ dilation=(1, 3, 5),
171
+ activation: nn.Module = nn.LeakyReLU(0.1),
172
+ ):
173
+ super().__init__()
174
+
175
+ self.conv_nets = nn.ModuleList(
176
+ [
177
+ self._get_conv_layer(
178
+ i,
179
+ res_block_channels,
180
+ ada_channel_in,
181
+ kernel_size,
182
+ 1,
183
+ dilation,
184
+ )
185
+ for i in range(3)
186
+ ]
187
+ )
188
+ self.conv_nets.apply(self.init_weights)
189
+ self.last_index = len(self.conv_nets) - 1
190
+ self.activation = activation
191
+
192
+ def _get_conv_layer(self, id, ch, ada_ch, k, stride, d):
193
+ get_padding = lambda ks, d: int((ks * d - d) / 2)
194
+ return nn.ModuleDict(
195
+ dict(
196
+ norm1=AdaFusion1D(ada_ch, ch),
197
+ norm2=AdaFusion1D(ada_ch, ch),
198
+ alpha1=nn.Parameter(torch.ones(1, ada_ch, 1)),
199
+ alpha2=nn.Parameter(torch.ones(1, ada_ch, 1)),
200
+ conv1=weight_norm(
201
+ nn.Conv1d(
202
+ ch, ch, k, stride, dilation=d[id], padding=get_padding(k, d[id])
203
+ )
204
+ ), # 2
205
+ conv2=weight_norm(
206
+ nn.Conv1d(ch, ch, k, stride, dilation=1, padding=get_padding(k, 1))
207
+ ), # 4
208
+ )
209
+ )
210
+
211
+ def forward(self, x: torch.Tensor, y: torch.Tensor):
212
+ for cnn in self.conv_nets:
213
+ xt = self.activation(cnn["norm1"](x, y, cnn["alpha1"]))
214
+ xt = cnn["conv1"](xt)
215
+ xt = self.activation(cnn["norm2"](xt, y, cnn["alpha2"]))
216
+ x = cnn["conv2"](xt) + x
217
+ return x