hunterFormsBS 0.3.2__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.
hunterFormsBS/loss.py ADDED
@@ -0,0 +1,157 @@
1
+ """Compute multi-resolution training loss for waveform source separation.
2
+
3
+ You can use this module to train a separator that reconstructs waveform audio and matches target
4
+ spectrogram structure at multiple STFT window sizes. `lossComputation` combines a waveform-domain
5
+ mean absolute error term with a multi-resolution complex-STFT term to produce the training
6
+ objective. The loss family follows the BS-RoFormer [1] and Mel-RoFormer [2] formulations and is
7
+ consumed by `hunterFormsBS.bandSplitRotator.BandSplitRotator` [3].
8
+
9
+ Contents
10
+ --------
11
+ Functions
12
+ lossComputation
13
+ Compute waveform MAE and multi-resolution complex-STFT MAE for selected stems and return one
14
+ total loss or an expanded breakdown.
15
+
16
+ References
17
+ ----------
18
+ [1] Lu, W.-T., Wang, J.-C., Kong, Q., & Hung, Y.-N. (2023). Music Source Separation with
19
+ Band-Split RoPE Transformer. https://arxiv.org/abs/2309.02612
20
+ [2] Wang, J.-C., Lu, W.-T., and Chen, J. (2024) Mel-RoFormer for Vocal Separation and Vocal Melody
21
+ Transcription https://arxiv.org/abs/2409.04702
22
+ [3] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
23
+ """
24
+ from __future__ import annotations
25
+
26
+ from einops import rearrange
27
+ from hunterFormsBS.theTypes import ParametersComputeLoss, ParametersSTFT
28
+ from torch import Tensor, tensor
29
+ from typing import Literal, overload
30
+ import torch
31
+ import torch.nn.functional as F
32
+
33
+ @overload
34
+ def lossComputation(recon_audio: Tensor, target: Tensor, stem_ids: list[int], multi_stft: ParametersComputeLoss, *, return_loss_breakdown: Literal[True]) -> tuple[Tensor, tuple[Tensor, Tensor]]: ...
35
+ @overload
36
+ def lossComputation(recon_audio: Tensor, target: Tensor, stem_ids: list[int], multi_stft: ParametersComputeLoss, *, return_loss_breakdown: Literal[False] = False) -> Tensor: ...
37
+ def lossComputation(recon_audio: Tensor, target: Tensor, stem_ids: list[int], multi_stft: ParametersComputeLoss, *, return_loss_breakdown: bool = False) -> Tensor | tuple[Tensor, tuple[Tensor, Tensor]]:
38
+ """Compute waveform and multi-resolution spectrogram loss for selected stems.
39
+
40
+ You can use `lossComputation` to train one separator that reconstructs waveform audio and matches
41
+ target spectrogram structure at multiple STFT window sizes. The loss family follows the
42
+ BS-RoFormer objective [1] and the later Mel-RoFormer formulation family [2]. `lossComputation`
43
+ selects the target stems indicated by `stem_ids`, trims `target` to the reconstructed sample
44
+ count, computes one waveform-domain mean absolute error term, accumulates one complex-STFT mean
45
+ absolute error term across the configured resolutions, and combines both terms into one total
46
+ loss. `lossComputation` is the shared training-loss helper used by
47
+ `hunterFormsBS.bandSplitRotator.BandSplitRotator` [3].
48
+
49
+ Parameters
50
+ ----------
51
+ recon_audio : Tensor
52
+ Reconstructed waveform estimate. `recon_audio` is expected to have shape `(batch, stem,
53
+ audioChannel, time)` or a shape that is broadcast-compatible with `target[:, stem_ids]`.
54
+ target : Tensor
55
+ Reference waveform collection from which `stem_ids` selects the supervised stems. The last
56
+ axis is interpreted as time. When `target.ndim == 2`, `lossComputation` inserts one singleton
57
+ axis before the time axis so mono shorthand remains broadcast-compatible with mono
58
+ reconstructions.
59
+ stem_ids : list[int]
60
+ Stem index list used to select the supervised subset from `target[:, stem_ids]`.
61
+ multi_stft : ParametersComputeLoss
62
+ Multi-resolution STFT configuration. `multi_stft` supplies `window_sizes`, `hop_length`,
63
+ `n_fft`, `normalized`, `window_fn`, and `loss_weight`.
64
+ return_loss_breakdown : bool = False
65
+ When `True`, return both the combined loss and the two uncombined loss terms.
66
+
67
+ Returns
68
+ -------
69
+ total_loss : Tensor
70
+ Returned when `return_loss_breakdown` is `False`. `total_loss` equals the waveform-domain MAE
71
+ plus `multi_stft['loss_weight']` times the accumulated multi-resolution complex-STFT MAE.
72
+ loss_with_breakdown : tuple[Tensor, tuple[Tensor, Tensor]]
73
+ Returned when `return_loss_breakdown` is `True`. The outer `Tensor` is `total_loss`. The inner
74
+ pair contains `loss` and `multi_stft_resolution_loss`. `multi_stft['loss_weight']` is not
75
+ applied to `multi_stft_resolution_loss` in this return value.
76
+
77
+ Mathematics
78
+ -----------
79
+ multi-resolution loss : equation
80
+ ```
81
+ Let y ≜ `target_sel`, ŷ ≜ `recon_audio`,
82
+ W ≜ `multi_stft['window_sizes']`, α ≜ `multi_stft['loss_weight']`,
83
+ Ψ ≜ complex-valued STFT operator,
84
+ Ψ_w ≜ Ψ with length w windowing function
85
+
86
+ ℓₜ = ‖ŷ − y‖₁
87
+ ℓₛ = ∑_{w ∈ W} ‖Ψ_w(ŷ) − Ψ_w(y)‖₁
88
+ ℒ = ℓₜ + α · ℓₛ
89
+
90
+ where ℓₜ ≜ `loss`, ℓₛ ≜ `multi_stft_resolution_loss`,
91
+ ℒ ≜ `total_loss`
92
+ ```
93
+
94
+ PyTorch
95
+ -------
96
+ complex loss semantics : behavior
97
+ `multi_stft_resolution_loss` is accumulated with `torch.nn.functional.l1_loss` [4] on the
98
+ complex STFT tensors returned by `torch.stft` [5]. In PyTorch, `torch.nn.functional.l1_loss`
99
+ is equivalent to `torch.abs(input - target).mean()` [4], so the implemented complex norm uses
100
+ the complex modulus from `torch.abs` [6] rather than an explicit sum of separate real and
101
+ imaginary MAEs.
102
+
103
+ Sequence Alignment
104
+ ------------------
105
+ target shortening : behavior
106
+ `target` is trimmed to `target[..., : recon_audio.shape[-1]]` before stem selection. This
107
+ prevents sample-count mismatch when callers reconstruct waveform audio with `torch.istft` and
108
+ lose trailing samples [3].
109
+
110
+ References
111
+ ----------
112
+ [1] Lu, W.-T., Wang, J.-C., Kong, Q., & Hung, Y.-N. (2023). Music Source Separation with
113
+ Band-Split RoPE Transformer. https://arxiv.org/abs/2309.02612
114
+ [2] Wang, J.-C., Lu, W.-T., and Chen, J. (2024) Mel-RoFormer for Vocal Separation and Vocal Melody
115
+ Transcription https://arxiv.org/abs/2409.04702
116
+ [3] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
117
+
118
+ [4] torch.nn.functional.l1_loss - PyTorch
119
+ https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.l1_loss.html
120
+ [5] torch.stft - PyTorch
121
+ https://docs.pytorch.org/docs/stable/generated/torch.stft.html
122
+ [6] torch.abs - PyTorch
123
+ https://docs.pytorch.org/docs/stable/generated/torch.abs.html
124
+ """
125
+ device: torch.device = recon_audio.device
126
+
127
+ if target.ndim == 2:
128
+ target = rearrange(target, '... t -> ... 1 t')
129
+
130
+ target = target[..., : recon_audio.shape[-1]] # protect against lost length on istft
131
+
132
+ target_sel: Tensor = target[:, stem_ids]
133
+ loss: Tensor = F.l1_loss(recon_audio, target_sel)
134
+
135
+ multi_stft_resolution_loss: Tensor = tensor(0.0, device=device)
136
+
137
+ for window_size in multi_stft['window_sizes']:
138
+ res_stft_kwargs = ParametersSTFT(
139
+ hop_length=multi_stft['hop_length']
140
+ , n_fft=max(window_size, multi_stft['n_fft'])
141
+ , normalized=multi_stft['normalized']
142
+ , win_length=window_size
143
+ )
144
+
145
+ recon_Y: Tensor = torch.stft(input=rearrange(recon_audio, 'b n s t -> (b n s) t'), return_complex=True, window=multi_stft['window_fn'](window_size, device=device), **res_stft_kwargs)
146
+ target_Y: Tensor = torch.stft(input=rearrange(target_sel, 'b n s t -> (b n s) t'), return_complex=True, window=multi_stft['window_fn'](window_size, device=device), **res_stft_kwargs)
147
+
148
+ multi_stft_resolution_loss += F.l1_loss(recon_Y, target_Y)
149
+
150
+ weighted_multi_resolution_loss: Tensor = multi_stft_resolution_loss * multi_stft['loss_weight']
151
+
152
+ total_loss: Tensor = loss + weighted_multi_resolution_loss
153
+
154
+ if not return_loss_breakdown:
155
+ return total_loss
156
+
157
+ return total_loss, (loss, multi_stft_resolution_loss)
hunterFormsBS/mask.py ADDED
@@ -0,0 +1,391 @@
1
+ """Estimate per-band complex subband masks for source separation.
2
+
3
+ You can use this module to build and apply band-local mask-estimation heads. `MaskEstimator`
4
+ converts one stack of band tokens into one concatenated band-local mask representation for a single
5
+ separator head. `MLP` constructs the affine blocks used inside `MaskEstimator`. The
6
+ mask-estimation family is shared by BS-RoFormer [1] and Mel-RoFormer [2] and is consumed by
7
+ `hunterFormsBS.bandSplitRotator.BandSplitRotator` [3].
8
+
9
+ Contents
10
+ --------
11
+ Functions
12
+ MLP
13
+ Build one feedforward projection sequence from an input width to an output width.
14
+
15
+ Classes
16
+ MaskEstimator
17
+ Estimate one concatenated subband mask from a stack of band tokens.
18
+
19
+ References
20
+ ----------
21
+ [1] Lu, W.-T., Wang, J.-C., Kong, Q., & Hung, Y.-N. (2023). Music Source Separation with
22
+ Band-Split RoPE Transformer. https://arxiv.org/abs/2309.02612
23
+ [2] Wang, J.-C., Lu, W.-T., and Chen, J. (2024) Mel-RoFormer for Vocal Separation and Vocal Melody
24
+ Transcription https://arxiv.org/abs/2409.04702
25
+ [3] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
26
+ """
27
+ from __future__ import annotations
28
+
29
+ from einops import rearrange
30
+ from hunterFormsBS.hyperACE import SegmModel
31
+ from torch import nn, Tensor
32
+ from torch.nn import Module, ModuleList
33
+ from torch_einops_kit import default
34
+ from typing import TYPE_CHECKING
35
+ import torch
36
+
37
+ if TYPE_CHECKING:
38
+ from collections.abc import Sequence
39
+
40
+ class MaskEstimator(Module):
41
+ """Estimate one concatenated subband mask from band tokens.
42
+
43
+ You can use this class to convert one stack of band tokens into one concatenated band-local mask
44
+ representation for a single separator head. `MaskEstimator` applies one learned projection head to
45
+ each band on the penultimate axis of the input `Tensor`, then concatenates the band-local outputs
46
+ along the last axis. The surrounding separator `hunterFormsBS.bandSplitRotator.BandSplitRotator`
47
+ [1] later reshapes the concatenated output into real and imaginary mask values and, for
48
+ overlapped band layouts, performs the overlap averaging step outside `MaskEstimator` [1][3].
49
+ `MaskEstimator` corresponds to the multi-band mask-estimation family from BS-RoFormer [2] and the
50
+ embedding-projection family from Mel-RoFormer [3]. Each band head uses `MLP` [4] as the affine
51
+ block before the final gate.
52
+
53
+ Attributes
54
+ ----------
55
+ dim_inputs : list[int]
56
+ Width of each band-local output segment in the concatenated return value.
57
+ to_freqs : ModuleList
58
+ Per-band projection head collection. Each head maps one `dim`-wide band token to one
59
+ band-local output segment whose width is given by `dim_inputs`.
60
+
61
+ Implementation boundary
62
+ -----------------------
63
+ band-head operators : behavior
64
+ `MaskEstimator` stores the band-local affine stack from `MLP` [4] and the final gated output
65
+ stage [6]. Any upstream normalization such as `RMSNorm` [5] must happen before `MaskEstimator`
66
+ receives band token `Tensor` `x`.
67
+ package default head template : behavior
68
+ When `depth = 1`, `mlp_expansion_factor = 4`, and `activation` is the hyperbolic tangent
69
+ activation, `MaskEstimator` matches the default hidden-width and activation pattern used by the
70
+ published model family [2][3][6].
71
+
72
+ References
73
+ ----------
74
+ [1] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
75
+
76
+ [2] Lu, W.-T., Wang, J.-C., Kong, Q., & Hung, Y.-N. (2023). Music Source Separation
77
+ with Band-Split RoPE Transformer. https://arxiv.org/abs/2309.02612
78
+ [3] Wang, J.-C., Lu, W.-T., and Chen, J. (2024) Mel-RoFormer for Vocal Separation and Vocal Melody
79
+ Transcription https://arxiv.org/abs/2409.04702
80
+
81
+ [4] `MLP`
82
+
83
+ [5] Zhang, B., & Sennrich, R. (2019). Root Mean Square Layer Normalization.
84
+ https://papers.nips.cc/paper_files/paper/2019/hash/1e8a19426224ca89e83cef47f1e7f53b-Abstract.html
85
+ [6] Dauphin, Y. N., Fan, A., Auli, M., & Grangier, D. (2017). Language Modeling with
86
+ Gated Convolutional Networks. https://proceedings.mlr.press/v70/dauphin17a.html
87
+ """
88
+ def __init__(
89
+ self,
90
+ dim: int,
91
+ dim_inputs: Sequence[int],
92
+ *,
93
+ depth: int,
94
+ mlp_expansion_factor: int = 4,
95
+ activation: type[nn.Module] = nn.Tanh,
96
+ segm_out_bins: int | None = None,
97
+ segm_out_channels: int = 4,
98
+ segm_base_channels: int = 64,
99
+ segm_base_depth: int = 2,
100
+ segm_num_hyperedges: int = 32,
101
+ segm_num_heads: int = 8,
102
+ segm_backbone_channels: tuple[int, int, int, int, int] | None = None,
103
+ segm_hyperace_k: int = 2,
104
+ segm_hyperace_l: int = 1,
105
+ segm_hyperace_c_h: float = 0.5,
106
+ segm_hyperace_c_l: float = 0.25,
107
+ segm_hyperace_c3ah_expansion: float = 1.0,
108
+ segm_hyperace_low_order_depth: int = 1,
109
+ segm_hyperace_low_order_kernel: int = 3,
110
+ segm_hyperace_low_order_expansion: float = 1.0,
111
+ segm_hyperace_out_channels: int | None = None,
112
+ segm_decoder_channels: list[int] | tuple[int, int, int, int] | None = None,
113
+ segm_decoder_block_depth: int = 1,
114
+ segm_decoder_block_kernel: int = 3,
115
+ segm_decoder_block_expansion: float = 0.5,
116
+ segm_upsample_scales: tuple[int, int, int, int] = (2, 2, 2, 2),
117
+ segm_upsample_tfc_tdf_depth: int = 2,
118
+ segm_upsample_tfc_tdf_bn: int = 4,
119
+ segm_activation: type[nn.Module] = nn.SiLU,
120
+ segm_norm_eps: float = 1e-8,
121
+ segm_norm_affine: bool = True,
122
+ segm_conv_bias: bool = False,
123
+ segm_linear_bias: bool = False,
124
+ use_hyperACE: bool = False,
125
+ ) -> None:
126
+ """Configure one mask-projection head per band.
127
+
128
+ You can use `__init__` to specify how many band heads `MaskEstimator` builds, how wide each
129
+ band-local output segment should be, and how deep the shared head template should be.
130
+ `__init__` stores the per-band output widths in `self.dim_inputs` and creates one band-local
131
+ projection head for each band.
132
+
133
+ Parameters
134
+ ----------
135
+ dim : int
136
+ Feature width of each input band token.
137
+ dim_inputs : Sequence[int]
138
+ Output width sequence for the band-local segments. Entry `dim_inputs[k]` becomes the
139
+ last-axis width emitted by head index `k`.
140
+ depth : int
141
+ Number of hidden-width repeats inside each band-local `MLP`. `depth = 1` yields the
142
+ two-linear-layer pattern used by the paper-default head.
143
+ mlp_expansion_factor : int = 4
144
+ Hidden-width multiplier relative to `dim`. The hidden width becomes `dim *
145
+ mlp_expansion_factor`. The default value `4` matches the hidden-width ratio reported for
146
+ the mask-estimation head.
147
+ activation : type[nn.Module] = nn.Tanh
148
+ Activation class instantiated between non-final linear layers inside each band-local
149
+ `MLP`. The default value corresponds to the hyperbolic tangent activation used by the
150
+ paper-default head.
151
+ """
152
+ super().__init__()
153
+ self.dim_inputs: list[int] = list(dim_inputs)
154
+ self.to_freqs: ModuleList = ModuleList([])
155
+ dim_hidden: int = dim * mlp_expansion_factor
156
+ self.use_hyperACE: bool = use_hyperACE
157
+
158
+ for dim_in in self.dim_inputs:
159
+ mlp: nn.Sequential = nn.Sequential(MLP(dim, dim_in * 2, dim_hidden=dim_hidden, depth=depth, activation=activation), nn.GLU(dim=-1))
160
+ self.to_freqs.append(mlp)
161
+
162
+ if self.use_hyperACE:
163
+ segm_out_bins = sum(dim_inputs) // segm_out_channels if segm_out_bins is None else segm_out_bins
164
+ self.segm = SegmModel(
165
+ in_bands=len(dim_inputs),
166
+ in_dim=dim,
167
+ out_bins=segm_out_bins,
168
+ out_channels=segm_out_channels,
169
+ base_channels=segm_base_channels,
170
+ base_depth=segm_base_depth,
171
+ num_hyperedges=segm_num_hyperedges,
172
+ num_heads=segm_num_heads,
173
+ backbone_channels=segm_backbone_channels,
174
+ hyperace_k=segm_hyperace_k,
175
+ hyperace_l=segm_hyperace_l,
176
+ hyperace_c_h=segm_hyperace_c_h,
177
+ hyperace_c_l=segm_hyperace_c_l,
178
+ hyperace_c3ah_expansion=segm_hyperace_c3ah_expansion,
179
+ hyperace_low_order_depth=segm_hyperace_low_order_depth,
180
+ hyperace_low_order_kernel=segm_hyperace_low_order_kernel,
181
+ hyperace_low_order_expansion=segm_hyperace_low_order_expansion,
182
+ hyperace_out_channels=segm_hyperace_out_channels,
183
+ decoder_channels=segm_decoder_channels,
184
+ decoder_block_depth=segm_decoder_block_depth,
185
+ decoder_block_kernel=segm_decoder_block_kernel,
186
+ decoder_block_expansion=segm_decoder_block_expansion,
187
+ upsample_scales=segm_upsample_scales,
188
+ upsample_tfc_tdf_depth=segm_upsample_tfc_tdf_depth,
189
+ upsample_tfc_tdf_bn=segm_upsample_tfc_tdf_bn,
190
+ activation=segm_activation,
191
+ norm_eps=segm_norm_eps,
192
+ norm_affine=segm_norm_affine,
193
+ conv_bias=segm_conv_bias,
194
+ linear_bias=segm_linear_bias,
195
+ )
196
+
197
+ def forward(self, x: Tensor) -> Tensor:
198
+ """Estimate one concatenated mask from band features `x`.
199
+
200
+ You can use `forward` when `x` contains one learned token per band on the penultimate axis.
201
+ `forward` sends each band token to the matching projection head in `self.to_freqs`, then
202
+ concatenates the band-local outputs along the last axis. The return value keeps band order but
203
+ removes the explicit band axis, so callers can reinterpret contiguous output segments as one
204
+ complex mask layout for later reshaping. `forward` does not average overlapping frequency bins;
205
+ later package code performs any overlap-aware reconstruction step after reshaping.
206
+
207
+ Parameters
208
+ ----------
209
+ x : Tensor
210
+ Band-token tensor. `x.shape[-2]` must equal `len(self.dim_inputs)`. In current callers,
211
+ `x` usually has shape `(batch, time, band, feature)`.
212
+
213
+ Returns
214
+ -------
215
+ concatenated_mask : Tensor
216
+ Concatenated band-local output tensor. If the leading shape of `x` is `leadingShape`, the
217
+ return value has shape `(*leadingShape, sum(self.dim_inputs))`.
218
+
219
+ PyTorch Tensor Shapes
220
+ ---------------------
221
+ input band axis : relation
222
+ `forward` interprets `x[..., k, :]` as the feature tensor for band index `k`.
223
+ per-band output width : relation
224
+ Head index `k` maps `x[..., k, :]` to one tensor whose last-axis width is
225
+ `self.dim_inputs[k]`.
226
+ output concatenation : relation
227
+ `forward` concatenates the projected band outputs in ascending band order along the last
228
+ axis.
229
+
230
+ Mathematics
231
+ -----------
232
+ band-head family : equation
233
+ ```
234
+ Let X ≜ `x`, K ≜ len(`self.dim_inputs`),
235
+ zₖ ≜ `self.dim_inputs[k]`, xₖ ≜ X[..., k, :]
236
+
237
+ Φₖ : ℝ^{…, d} → ℝ^{…, zₖ} ∀ k ∈ {0, …, K − 1}
238
+ yₖ = Φₖ(xₖ) ∀ k ∈ {0, …, K − 1}
239
+ Z = ∑ₖ zₖ
240
+ y = y₀ ‖ y₁ ‖ ⋯ ‖ y_{K−1} ∈ ℝ^{…, Z}
241
+
242
+ where y ≜ `concatenated_mask`
243
+ ```
244
+ default head specialization : equation
245
+ ```
246
+ Let L ≜ `depth`, γ ≜ `mlp_expansion_factor`, φ ≜ `activation`
247
+
248
+ L = 1
249
+ γ = 4
250
+ φ = tanh
251
+
252
+ Wₖ,1 : ℝ^{d} → ℝ^{4d}
253
+ Wₖ,2 : ℝ^{4d} → ℝ^{2zₖ}
254
+ hₖ = φ(Wₖ,1 xₖ + bₖ,1)
255
+ [aₖ ‖ gₖ] = Wₖ,2 hₖ + bₖ,2
256
+ yₖ = aₖ ⊙ σ(gₖ)
257
+ ```
258
+
259
+ Separator integration
260
+ ---------------------
261
+ non-overlapping mask assembly : behavior
262
+ In non-overlapping band layouts, the concatenated output can be reinterpreted as one full
263
+ complex mask by frequency-axis concatenation [1].
264
+ overlap handling outside `MaskEstimator` : behavior
265
+ In overlapped mel-band layouts, `hunterFormsBS.bandSplitRotator.BandSplitRotator` [3]
266
+ performs the later overlap averaging step after reshaping the concatenated output back to
267
+ band-local mask slices [2][3].
268
+ normalization boundary : behavior
269
+ `forward` does not apply per-band `RMSNorm` [4]. `forward` only invokes the stored
270
+ band-local affine block and final gate [5].
271
+
272
+ References
273
+ ----------
274
+ [1] Lu, W.-T., Wang, J.-C., Kong, Q., & Hung, Y.-N. (2023). Music Source Separation
275
+ with Band-Split RoPE Transformer. https://arxiv.org/abs/2309.02612
276
+ [2] Wang, J.-C., Lu, W.-T., and Chen, J. (2024) Mel-RoFormer for Vocal Separation and Vocal Melody
277
+ Transcription https://arxiv.org/abs/2409.04702
278
+ [3] `hunterFormsBS.bandSplitRotator.BandSplitRotator`
279
+
280
+ [4] Zhang, B., & Sennrich, R. (2019). Root Mean Square Layer Normalization.
281
+ https://papers.nips.cc/paper_files/paper/2019/hash/1e8a19426224ca89e83cef47f1e7f53b-Abstract.html
282
+ [5] Dauphin, Y. N., Fan, A., Auli, M., & Grangier, D. (2017). Language Modeling with
283
+ Gated Convolutional Networks. https://proceedings.mlr.press/v70/dauphin17a.html
284
+ """
285
+ if self.use_hyperACE:
286
+ y: Tensor = rearrange(x, 'b t f c -> b c t f')
287
+ y = self.segm(y)
288
+ y = rearrange(y, 'b c t f -> b t (f c)')
289
+
290
+ tensor_unbound: tuple[Tensor, ...] = x.unbind(dim=-2)
291
+
292
+ outs: list[Tensor] = []
293
+
294
+ for band_features, mlp in zip(tensor_unbound, self.to_freqs, strict=True):
295
+ freq_out: Tensor = mlp(band_features)
296
+ outs.append(freq_out)
297
+
298
+ out: Tensor = torch.cat(outs, dim=-1)
299
+
300
+ if self.use_hyperACE:
301
+ out += y # pyright: ignore[reportPossiblyUnboundVariable]
302
+
303
+ return out
304
+
305
+ def MLP(dim_in: int, dim_out: int, dim_hidden: int | None = None, depth: int = 1, activation: type[nn.Module] = nn.Tanh) -> nn.Sequential:
306
+ """Build one feedforward projection from `dim_in` to `dim_out`.
307
+
308
+ You can use `MLP` to create one `nn.Sequential` made of linear layers with one intermediate
309
+ activation after every non-final linear layer. `MLP` does not apply normalization or output gating
310
+ by itself. `MaskEstimator` [1] uses `MLP` as the band-local affine block before the final gate in
311
+ the BS-RoFormer [2] and Mel-RoFormer [3] mask heads.
312
+
313
+ Parameters
314
+ ----------
315
+ dim_in : int
316
+ Input feature width for the first linear layer.
317
+ dim_out : int
318
+ Output feature width for the last linear layer.
319
+ dim_hidden : int | None = None
320
+ Hidden feature width for repeated intermediate linear layers. When `dim_hidden` is `None`,
321
+ `MLP` uses `dim_in`.
322
+ depth : int = 1
323
+ Number of repeated `dim_hidden` stages between the input layer and the output layer. `depth =
324
+ 0` yields a single linear layer. `depth = 1` yields one hidden layer.
325
+ activation : type[nn.Module] = nn.Tanh
326
+ Activation class instantiated after each non-final linear layer.
327
+
328
+ Returns
329
+ -------
330
+ network : nn.Sequential
331
+ Sequential stack of alternating linear layers and instantiated `activation` modules. The last
332
+ module is always linear.
333
+
334
+ Mathematics
335
+ -----------
336
+ linear stack : equation
337
+ ```
338
+ Let x denote the input vector, L ≜ `depth`,
339
+ d₀ ≜ `dim_in`, d_out ≜ `dim_out`, d_h denote the effective hidden width
340
+
341
+ d₁ = ⋯ = d_L = d_h
342
+ h₀ = x
343
+ hᵢ₊₁ = φ(Wᵢ hᵢ + bᵢ) ∀ i ∈ {0, …, L − 1}
344
+ y = W_L h_L + b_L
345
+
346
+ where d_h ≜ hidden width determined from `dim_hidden`, φ ≜ `activation`
347
+ ```
348
+ default mask-head affine block : equation
349
+ ```
350
+ Let x denote one band-local input vector, d ≜ `dim_in`
351
+
352
+ L = 1
353
+ d_h = 4d
354
+ φ = tanh
355
+ h = φ(W₁ x + b₁)
356
+ g = W₂ h + b₂
357
+
358
+ where g ≜ affine output returned by `MLP` before the later gate in `MaskEstimator`
359
+ ```
360
+
361
+ Layer Construction
362
+ ------------------
363
+ activation instantiation : behavior
364
+ `MLP` instantiates a fresh `activation()` module after each non-final linear layer. `MLP` does
365
+ not append an activation after the last linear layer.
366
+
367
+ References
368
+ ----------
369
+ [1] `MaskEstimator`
370
+
371
+ [2] Lu, W.-T., Wang, J.-C., Kong, Q., & Hung, Y.-N. (2023). Music Source Separation
372
+ with Band-Split RoPE Transformer. https://arxiv.org/abs/2309.02612
373
+ [3] Wang, J.-C., Lu, W.-T., and Chen, J. (2024) Mel-RoFormer for Vocal Separation and Vocal Melody
374
+ Transcription https://arxiv.org/abs/2409.04702
375
+ """
376
+ dim_hidden = default(dim_hidden, dim_in)
377
+
378
+ net: list[nn.Module] = []
379
+ dims: tuple[int, ...] = (dim_in, *((dim_hidden,) * depth), dim_out)
380
+
381
+ for ind, (layer_dim_in, layer_dim_out) in enumerate(zip(dims[:-1], dims[1:], strict=True)): # noqa: RUF007
382
+ is_last: bool = ind == (len(dims) - 2)
383
+
384
+ net.append(nn.Linear(layer_dim_in, layer_dim_out))
385
+
386
+ if is_last:
387
+ continue
388
+
389
+ net.append(activation())
390
+
391
+ return nn.Sequential(*net)
hunterFormsBS/py.typed ADDED
File without changes