lt-tensor 0.0.1a15__tar.gz → 0.0.1a17__tar.gz

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.
Files changed (43) hide show
  1. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/PKG-INFO +1 -1
  2. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/config_templates.py +23 -15
  3. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/model_base.py +36 -87
  4. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/model_zoo/__init__.py +8 -6
  5. lt_tensor-0.0.1a17/lt_tensor/model_zoo/audio_models/__init__.py +2 -0
  6. lt_tensor-0.0.1a15/lt_tensor/model_zoo/diffwave/model.py → lt_tensor-0.0.1a17/lt_tensor/model_zoo/audio_models/diffwave/__init__.py +86 -67
  7. lt_tensor-0.0.1a17/lt_tensor/model_zoo/audio_models/hifigan/__init__.py +393 -0
  8. lt_tensor-0.0.1a17/lt_tensor/model_zoo/audio_models/istft/__init__.py +409 -0
  9. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/model_zoo/basic.py +139 -0
  10. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor.egg-info/PKG-INFO +1 -1
  11. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor.egg-info/SOURCES.txt +4 -8
  12. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/setup.py +1 -1
  13. lt_tensor-0.0.1a15/lt_tensor/model_zoo/diffwave/__init__.py +0 -0
  14. lt_tensor-0.0.1a15/lt_tensor/model_zoo/diffwave/params.py +0 -58
  15. lt_tensor-0.0.1a15/lt_tensor/model_zoo/discriminator.py +0 -314
  16. lt_tensor-0.0.1a15/lt_tensor/model_zoo/istft/__init__.py +0 -5
  17. lt_tensor-0.0.1a15/lt_tensor/model_zoo/istft/generator.py +0 -94
  18. lt_tensor-0.0.1a15/lt_tensor/model_zoo/istft/sg.py +0 -142
  19. lt_tensor-0.0.1a15/lt_tensor/model_zoo/istft/trainer.py +0 -627
  20. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/LICENSE +0 -0
  21. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/README.md +0 -0
  22. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/__init__.py +0 -0
  23. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/datasets/__init__.py +0 -0
  24. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/datasets/audio.py +0 -0
  25. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/losses.py +0 -0
  26. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/lr_schedulers.py +0 -0
  27. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/math_ops.py +0 -0
  28. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/misc_utils.py +0 -0
  29. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/model_zoo/features.py +0 -0
  30. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/model_zoo/fusion.py +0 -0
  31. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/model_zoo/pos_encoder.py +0 -0
  32. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/model_zoo/residual.py +0 -0
  33. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/model_zoo/transformer.py +0 -0
  34. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/monotonic_align.py +0 -0
  35. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/noise_tools.py +0 -0
  36. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/processors/__init__.py +0 -0
  37. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/processors/audio.py +0 -0
  38. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/torch_commons.py +0 -0
  39. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor/transform.py +0 -0
  40. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor.egg-info/dependency_links.txt +0 -0
  41. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor.egg-info/requires.txt +0 -0
  42. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/lt_tensor.egg-info/top_level.txt +0 -0
  43. {lt_tensor-0.0.1a15 → lt_tensor-0.0.1a17}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lt-tensor
3
- Version: 0.0.1a15
3
+ Version: 0.0.1a17
4
4
  Summary: General utilities for PyTorch and others. Built for general use.
5
5
  Home-page: https://github.com/gr1336/lt-tensor/
6
6
  Author: gr1336
@@ -7,16 +7,14 @@ from lt_tensor.misc_utils import updateDict
7
7
 
8
8
  class ModelConfig(ABC, OrderedDict):
9
9
  _default_settings: Dict[str, Any] = {}
10
- _forbidden_list: List[str] = [
11
- "_settings",
12
- ]
10
+ _forbidden_list: List[str] = ["_default_settings", "_forbidden_list" "path_name"]
13
11
 
14
12
  def __init__(
15
13
  self,
16
- settings: Dict[str, Any] = None,
14
+ settings: Dict[str, Any] = {},
17
15
  path_name: Optional[Union[str, PathLike]] = None,
18
16
  ):
19
- assert is_dict(settings)
17
+ assert is_dict(settings, False)
20
18
  self._default_settings = settings
21
19
  if path_name is not None and is_pathlike(path_name):
22
20
  if not str(path_name).endswith(".json"):
@@ -37,31 +35,41 @@ class ModelConfig(ABC, OrderedDict):
37
35
  self.path_name += ".json"
38
36
 
39
37
  def reset_settings(self):
38
+ dk_keys = self.__dict__.keys()
40
39
  for s_name, setting in self._default_settings.items():
41
- if s_name in self._forbidden_list:
40
+ if s_name in self._forbidden_list or s_name not in dk_keys:
42
41
  continue
43
42
  updateDict(self, {s_name: setting})
44
43
 
45
44
  def save_config(
46
45
  self,
47
- path_name: Union[PathLike, str],
46
+ path_name: Optional[Union[PathLike, str]] = None,
48
47
  ):
49
- assert is_pathlike(
50
- path_name, True
51
- ), f"path_name should be a non-empty string or pathlike object! received instead: {path_name}"
52
- self._setup_path_name(path_name)
53
- base = {k: y for k, y in self.__dict__.items() if k not in self._forbidden_list}
54
- save_json(self.path_name, base, indent=2)
48
+ if not is_pathlike(path_name, True):
49
+ assert (
50
+ path_name is None
51
+ ), f"path_name should be a non-empty string or pathlike object! received instead: {path_name}."
52
+ path_name = self.path_name
53
+ else:
54
+ self._setup_path_name(path_name)
55
55
 
56
- def to_dict(self):
57
- return {k: y for k, y in self.__dict__.items() if k not in self._forbidden_list}
56
+ base = self.get_state_dict()
57
+ save_json(self.path_name, base, indent=2)
58
58
 
59
59
  def set_value(self, var_name: str, value: str) -> None:
60
+ assert var_name in self.__dict__, "Value not registered!"
61
+ assert var_name not in self._forbidden_list, "Not allowed!"
60
62
  updateDict(self, {var_name: value})
61
63
 
62
64
  def get_value(self, var_name: str) -> Any:
63
65
  return self.__dict__.get(var_name)
64
66
 
67
+ def __getattribute__(self, name):
68
+ return self.__dict__.get(name)
69
+
70
+ def get_state_dict(self):
71
+ return {k: y for k, y in self.__dict__.items() if k not in self._forbidden_list}
72
+
65
73
  @classmethod
66
74
  def from_dict(
67
75
  cls, dictionary: Dict[str, Any], path: Optional[Union[str, PathLike]] = None
@@ -70,16 +70,6 @@ class LossTracker:
70
70
 
71
71
  class _Devices_Base(nn.Module):
72
72
  _device: torch.device = ROOT_DEVICE
73
- _autocast: bool = False
74
- _loss_history: LossTracker = LossTracker(100_000)
75
-
76
- @property
77
- def autocast(self):
78
- return self._autocast
79
-
80
- @autocast.setter
81
- def autocast(self, value: bool):
82
- self._autocast = value
83
73
 
84
74
  @property
85
75
  def device(self):
@@ -90,6 +80,30 @@ class _Devices_Base(nn.Module):
90
80
  assert isinstance(device, (str, torch.device))
91
81
  self._device = torch.device(device) if isinstance(device, str) else device
92
82
 
83
+ def _apply_device(self):
84
+ """Add here components that are needed to have device applied to them,
85
+ that usually the '.to()' function fails to apply
86
+
87
+ example:
88
+ ```
89
+ def _apply_device_to(self):
90
+ self.my_tensor = self.my_tensor.to(device=self.device)
91
+ ```
92
+ """
93
+ pass
94
+
95
+ def _to_dvc(
96
+ self, device_name: str, device_id: Optional[Union[int, torch.device]] = None
97
+ ):
98
+ device = device_name
99
+ if device_id is not None:
100
+ if isinstance(device_id, Number):
101
+ device += ":" + str(int(device_id))
102
+ elif hasattr(device_id, "index"):
103
+ device += ":" + str(device_id.index)
104
+ self.device = device
105
+ self._apply_device()
106
+
93
107
  def to(self, *args, **kwargs):
94
108
  device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(
95
109
  *args, **kwargs
@@ -133,20 +147,9 @@ class _Devices_Base(nn.Module):
133
147
  raise
134
148
 
135
149
  self._apply(convert)
136
- self.device = device
150
+ self._to_dvc(device)
137
151
  return self
138
152
 
139
- def _to_dvc(
140
- self, device_name: str, device_id: Optional[Union[int, torch.device]] = None
141
- ):
142
- device = device_name
143
- if device_id is not None:
144
- if isinstance(device_id, Number):
145
- device += ":" + str(int(device_id))
146
- elif hasattr(device_id, "index"):
147
- device += ":" + str(device_id.index)
148
- self.device = device
149
-
150
153
  def ipu(self, device: Optional[Union[int, torch.device]] = None) -> T:
151
154
  super().ipu(device)
152
155
  self._to_dvc("ipu", device)
@@ -178,11 +181,12 @@ class Model(_Devices_Base, ABC):
178
181
  This makes it easier to assign a device and retrieves it later
179
182
  """
180
183
 
184
+ _autocast: bool = False
181
185
  _is_unfrozen: bool = False
182
186
  # list with modules that can be frozen or unfrozen
183
187
  registered_freezable_modules: List[str] = []
184
188
  is_frozen: bool = False
185
- _is_gradient_freezable: bool = (
189
+ _can_be_frozen: bool = (
186
190
  False # to control if the module can or cannot be freezed by other modules from 'Model' class
187
191
  )
188
192
  # this is to be used on the case of they module requires low-rank adapters
@@ -193,18 +197,15 @@ class Model(_Devices_Base, ABC):
193
197
 
194
198
  # dont save list:
195
199
  _dont_save_items: List[str] = []
200
+ _loss_history: LossTracker = LossTracker(20_000)
196
201
 
197
- def _apply_device_to(self):
198
- """Add here components that are needed to have device applied to them,
199
- that usually the '.to()' function fails to apply
202
+ @property
203
+ def autocast(self):
204
+ return self._autocast
200
205
 
201
- example:
202
- ```
203
- def _apply_device_to(self):
204
- self.my_tensor = self.my_tensor.to(device=self.device)
205
- ```
206
- """
207
- pass
206
+ @autocast.setter
207
+ def autocast(self, value: bool):
208
+ self._autocast = value
208
209
 
209
210
  def freeze_all(self, exclude: Optional[List[str]] = None):
210
211
  no_exclusions = not exclude
@@ -251,7 +252,7 @@ class Model(_Devices_Base, ABC):
251
252
  def change_frozen_state(self, freeze: bool, module: nn.Module):
252
253
  try:
253
254
  if isinstance(module, Model):
254
- if module._is_gradient_freezable:
255
+ if module._can_be_frozen:
255
256
  if freeze:
256
257
  return module.freeze_all()
257
258
  return module.unfreeze_all()
@@ -496,10 +497,7 @@ class Model(_Devices_Base, ABC):
496
497
  return self(*inputs, **kwargs)
497
498
 
498
499
  def __call__(self, *args, **kwds) -> POSSIBLE_OUTPUT_TYPES:
499
- if self.autocast and not self.training:
500
- with torch.autocast(device_type=self.device.type):
501
- return super().__call__(*args, **kwds)
502
- else:
500
+ with torch.autocast(device_type=self.device.type, enabled=self.autocast):
503
501
  return super().__call__(*args, **kwds)
504
502
 
505
503
  @abstractmethod
@@ -541,52 +539,3 @@ class Model(_Devices_Base, ABC):
541
539
  if quantity > 0:
542
540
  t_list = t_list[-quantity:]
543
541
  return sum(t_list) / len(t_list)
544
-
545
- def freeze_unfreeze_loss(
546
- self,
547
- losses: Optional[Union[float, List[float]]] = None,
548
- trigger_loss: Union[float, bool] = 0.1,
549
- excluded_modules: Optional[List[str]] = None,
550
- max_items: int = 1000,
551
- loss_name: str = "train",
552
- ):
553
- """If a certain threshold is reached the weights will freeze or unfreeze the modules.
554
- the biggest use-case for this function is when training GANs where the balance
555
- from the discriminator and generator must be kept.
556
-
557
- Args:
558
- losses (Union[float, List[float]], Optional): The loss value or a list of losses that will be used to determine if it has reached or not the threshold. Defaults to None.
559
- trigger_loss (float, bool, optional): The value where the weights will be either freeze or unfreeze. If set to a boolean it will freeze or unfreeze immediately according to the value (True = Freeze, False = Unfreeze). Defaults to 0.1.
560
- excluded_modules (list[str], optional): The list of modules (names) that is not to be changed by either freezing nor unfreezing. Defaults to None.
561
- max_items (float, optional): The number of previous losses to be locked behind to calculate the current average. Default to 1000.
562
- loss_name (str, optional): Responsible to define with key to recover the loss.
563
- returns:
564
- bool: True when its frozen and false when its trainable.
565
- """
566
- if losses is not None:
567
- self.add_loss(losses, "train")
568
-
569
- if isinstance(trigger_loss, bool):
570
- if trigger_loss:
571
- if self._is_unfrozen:
572
- self.freeze_all(excluded_modules)
573
- self._is_unfrozen = False
574
- return True
575
- # else
576
- if not self._is_unfrozen:
577
- self.unfreeze_all(excluded_modules)
578
- self._is_unfrozen = True
579
- return False
580
-
581
- value = self.get_loss_avg(loss_name, max_items)
582
-
583
- if value <= trigger_loss:
584
- if self._is_unfrozen:
585
- self.freeze_all(excluded_modules)
586
- self._is_unfrozen = False
587
- return True
588
- else:
589
- if not self._is_unfrozen:
590
- self.unfreeze_all(excluded_modules)
591
- self._is_unfrozen = True
592
- return False
@@ -2,18 +2,20 @@ __all__ = [
2
2
  "basic", # basic
3
3
  "residual", # residual
4
4
  "transformer", # transformer
5
- "pos_encoder",
6
- "fusion",
7
- "features",
8
- "discriminator",
5
+ "pos_encoder",
6
+ "fusion",
7
+ "features",
8
+ "discriminator",
9
+ "audio_models",
10
+ "hifigan",
9
11
  "istft",
10
12
  ]
13
+ from .audio_models import hifigan, istft
11
14
  from . import (
12
15
  basic,
13
- discriminator,
14
16
  features,
15
17
  fusion,
16
- istft,
18
+ audio_models,
17
19
  pos_encoder,
18
20
  residual,
19
21
  transformer,
@@ -0,0 +1,2 @@
1
+ from . import diffwave, istft, hifigan
2
+
@@ -1,48 +1,47 @@
1
+ __all__ = ["DiffWave", "SpectrogramUpsampler", "DiffusionEmbedding"]
2
+
1
3
  import numpy as np
2
4
  import torch
3
5
  import torch.nn as nn
4
6
  import torch.nn.functional as F
5
-
7
+ from lt_tensor.config_templates import ModelConfig
8
+ from lt_tensor.torch_commons import *
9
+ from lt_tensor.model_base import Model
6
10
  from math import sqrt
11
+ from lt_utils.common import *
7
12
 
8
-
9
- class AttrDict(dict):
10
- def __init__(self, *args, **kwargs):
11
- super(AttrDict, self).__init__(*args, **kwargs)
12
- self.__dict__ = self
13
-
14
- def override(self, attrs):
15
- if isinstance(attrs, dict):
16
- self.__dict__.update(**attrs)
17
- elif isinstance(attrs, (list, tuple, set)):
18
- for attr in attrs:
19
- self.override(attr)
20
- elif attrs is not None:
21
- raise NotImplementedError
22
- return self
13
+ F.t
23
14
 
24
15
 
25
- params = AttrDict(
16
+ class DiffWaveConfig(ModelConfig):
26
17
  # Training params
27
- batch_size=16,
28
- learning_rate=2e-4,
29
- max_grad_norm=None,
18
+ batch_size = 16
19
+ learning_rate = 2e-4
20
+ max_grad_norm = None
30
21
  # Data params
31
- sample_rate=22050,
32
- n_mels=80,
33
- n_fft=1024,
34
- hop_samples=256,
35
- crop_mel_frames=62, # Probably an error in paper.
22
+ sample_rate = 24000
23
+ n_mels = 80
24
+ n_fft = 1024
25
+ hop_samples = 256
36
26
  # Model params
37
- residual_layers=30,
38
- residual_channels=64,
39
- dilation_cycle_length=10,
40
- unconditional=False,
41
- noise_schedule=np.linspace(1e-4, 0.05, 50).tolist(),
42
- inference_noise_schedule=[0.0001, 0.001, 0.01, 0.05, 0.2, 0.5],
43
- # unconditional sample len
44
- audio_len=22050 * 5, # unconditional_synthesis_samples
45
- )
27
+ residual_layers = 30
28
+ residual_channels = 64
29
+ dilation_cycle_length = 10
30
+ unconditional = False
31
+ noise_schedule: list[int] = np.linspace(1e-4, 0.05, 50).tolist()
32
+ # settings for auto-fixes
33
+ interpolate = False
34
+ interpolation_mode: Literal[
35
+ "nearest", "linear", "bilinear", "bicubic", "trilinear", "area", "nearest-exact"
36
+ ] = "nearest"
37
+
38
+ def __init__(
39
+ self,
40
+ settings: Dict[str, Any] = {},
41
+ path_name: Optional[Union[str, PathLike]] = None,
42
+ ):
43
+ self._forbidden_list.extend()
44
+ super().__init__(settings, path_name)
46
45
 
47
46
 
48
47
  def Conv1d(*args, **kwargs):
@@ -51,8 +50,8 @@ def Conv1d(*args, **kwargs):
51
50
  return layer
52
51
 
53
52
 
54
- class DiffusionEmbedding(nn.Module):
55
- def __init__(self, max_steps):
53
+ class DiffusionEmbedding(Model):
54
+ def __init__(self, max_steps: int):
56
55
  super().__init__()
57
56
  self.register_buffer(
58
57
  "embedding", self._build_embedding(max_steps), persistent=False
@@ -87,23 +86,22 @@ class DiffusionEmbedding(nn.Module):
87
86
  return table
88
87
 
89
88
 
90
- class SpectrogramUpsampler(nn.Module):
91
- def __init__(self, n_mels):
89
+ class SpectrogramUpsampler(Model):
90
+ def __init__(self):
92
91
  super().__init__()
93
92
  self.conv1 = nn.ConvTranspose2d(1, 1, [3, 32], stride=[1, 16], padding=[1, 8])
94
93
  self.conv2 = nn.ConvTranspose2d(1, 1, [3, 32], stride=[1, 16], padding=[1, 8])
94
+ self.activation = nn.LeakyReLU(0.4)
95
95
 
96
96
  def forward(self, x):
97
97
  x = torch.unsqueeze(x, 1)
98
- x = self.conv1(x)
99
- x = F.leaky_relu(x, 0.4)
100
- x = self.conv2(x)
101
- x = F.leaky_relu(x, 0.4)
98
+ x = self.activation(self.conv1(x))
99
+ x = self.activation(self.conv2(x))
102
100
  x = torch.squeeze(x, 1)
103
101
  return x
104
102
 
105
103
 
106
- class ResidualBlock(nn.Module):
104
+ class ResidualBlock(Model):
107
105
  def __init__(self, n_mels, residual_channels, dilation, uncond=False):
108
106
  """
109
107
  :param n_mels: inplanes of conv1x1 for spectrogram conditional
@@ -127,14 +125,18 @@ class ResidualBlock(nn.Module):
127
125
 
128
126
  self.output_projection = Conv1d(residual_channels, 2 * residual_channels, 1)
129
127
 
130
- def forward(self, x, diffusion_step, conditioner=None):
131
- assert (conditioner is None and self.conditioner_projection is None) or (
132
- conditioner is not None and self.conditioner_projection is not None
133
- )
128
+ def forward(
129
+ self,
130
+ x: Tensor,
131
+ diffusion_step: Tensor,
132
+ conditioner: Optional[Tensor] = None,
133
+ ):
134
134
 
135
135
  diffusion_step = self.diffusion_projection(diffusion_step).unsqueeze(-1)
136
136
  y = x + diffusion_step
137
- if self.conditioner_projection is None: # using a unconditional model
137
+ if (
138
+ conditioner is None or self.conditioner_projection is None
139
+ ): # using a unconditional model
138
140
  y = self.dilated_conv(y)
139
141
  else:
140
142
  conditioner = self.conditioner_projection(conditioner)
@@ -148,16 +150,19 @@ class ResidualBlock(nn.Module):
148
150
  return (x + residual) / sqrt(2.0), skip
149
151
 
150
152
 
151
- class DiffWave(nn.Module):
152
- def __init__(self, params):
153
+ class DiffWave(Model):
154
+ def __init__(self, params: DiffWaveConfig = DiffWaveConfig()):
153
155
  super().__init__()
154
156
  self.params = params
157
+ self.n_hop = self.params.hop_samples
158
+ self.interpolate = self.params.interpolate
159
+ self.interpolate_mode = self.params.interpolation_mode
155
160
  self.input_projection = Conv1d(1, params.residual_channels, 1)
156
161
  self.diffusion_embedding = DiffusionEmbedding(len(params.noise_schedule))
157
162
  if self.params.unconditional: # use unconditional model
158
- self.spectrogram_upsampler = None
163
+ self.spectrogram_upsample = None
159
164
  else:
160
- self.spectrogram_upsampler = SpectrogramUpsampler(params.n_mels)
165
+ self.spectrogram_upsample = SpectrogramUpsampler()
161
166
 
162
167
  self.residual_layers = nn.ModuleList(
163
168
  [
@@ -174,27 +179,41 @@ class DiffWave(nn.Module):
174
179
  params.residual_channels, params.residual_channels, 1
175
180
  )
176
181
  self.output_projection = Conv1d(params.residual_channels, 1, 1)
182
+ self.activation = nn.LeakyReLU(0.1)
183
+ self.r_sqrt = sqrt(len(self.residual_layers))
177
184
  nn.init.zeros_(self.output_projection.weight)
178
185
 
179
- def forward(self, audio, diffusion_step, spectrogram=None):
180
- assert (spectrogram is None and self.spectrogram_upsampler is None) or (
181
- spectrogram is not None and self.spectrogram_upsampler is not None
182
- )
183
- x = audio.unsqueeze(1)
184
- x = self.input_projection(x)
185
- x = F.relu(x)
186
+ def forward(
187
+ self,
188
+ audio: Tensor,
189
+ diffusion_step: Tensor,
190
+ spectrogram: Optional[Tensor] = None,
191
+ ):
192
+ T = x.shape[-1]
193
+ if x.ndim == 2:
194
+ x = audio.unsqueeze(1)
195
+ x = self.activation(self.input_projection(x))
186
196
 
187
197
  diffusion_step = self.diffusion_embedding(diffusion_step)
188
- if self.spectrogram_upsampler: # use conditional model
189
- spectrogram = self.spectrogram_upsampler(spectrogram)
198
+ if spectrogram is not None and self.spectrogram_upsample is not None:
199
+ if self.auto_interpolate:
200
+ # a little heavy, but helps a lot to fix mismatched shapes,
201
+ # not always recommended due to data loss
202
+ spectrogram = F.interpolate(
203
+ input=spectrogram,
204
+ size=int(T * self.n_hop),
205
+ mode=self.interpolate_mode,
206
+ )
207
+ spectrogram = self.spectrogram_upsample(spectrogram)
190
208
 
191
209
  skip = None
192
- for layer in self.residual_layers:
210
+ for i, layer in enumerate(self.residual_layers):
193
211
  x, skip_connection = layer(x, diffusion_step, spectrogram)
194
- skip = skip_connection if skip is None else skip_connection + skip
195
-
196
- x = skip / sqrt(len(self.residual_layers))
197
- x = self.skip_projection(x)
198
- x = F.relu(x)
212
+ if i == 0:
213
+ skip = skip_connection
214
+ else:
215
+ skip = skip_connection + skip
216
+ x = skip / self.r_sqrt
217
+ x = self.activation(self.skip_projection(x))
199
218
  x = self.output_projection(x)
200
219
  return x