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.
@@ -0,0 +1,830 @@
1
+ """Use one converged waveform separator with configurable band layouts.
2
+
3
+ You can use this module to instantiate one configurable waveform-to-waveform music source separator
4
+ that supports non-overlapping BS-style bands, automatic mel-band layouts built with
5
+ `torchaudio.functional.melscale_fbanks` [1], and explicit custom `mask_filter_bank` definitions.
6
+ The public `class` `BandSplitRotator` surfaces downstream attention, transformer, mask-estimator,
7
+ optional segmentation-branch, STFT, and loss parameters on one constructor.
8
+
9
+ When `sage_attention=True`, downstream attention blocks attempt to call the separately installed
10
+ `SageAttention` package [2][3]. `hunterFormsBS` does not install `SageAttention` automatically.
11
+
12
+ Contents
13
+ --------
14
+ Classes
15
+ BandSplitRotator
16
+ Unified waveform separator with converged constructor arguments, optional `SageAttention`
17
+ backend selection, and multi-resolution STFT training loss.
18
+
19
+ References
20
+ ----------
21
+ [1] torchaudio.functional.melscale_fbanks - torchaudio
22
+ https://docs.pytorch.org/audio/stable/generated/torchaudio.functional.melscale_fbanks.html
23
+ [2] thu-ml/SageAttention
24
+ https://github.com/thu-ml/SageAttention
25
+ [3] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., & Chen, J. (2025).
26
+ SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
27
+ https://arxiv.org/abs/2410.02367
28
+ """
29
+ from __future__ import annotations
30
+
31
+ from einops import pack, rearrange, reduce, repeat, unpack # pyright: ignore[reportUnknownVariableType]
32
+ from functools import partial
33
+ from hunterFormsBS.bands import BandSplit, DEFAULT_FREQS_PER_BANDS
34
+ from hunterFormsBS.loss import lossComputation
35
+ from hunterFormsBS.mask import MaskEstimator
36
+ from hunterFormsBS.theTypes import ParametersComputeLoss, ParametersMaskEstimator, ParametersSTFT, ParametersTransformer
37
+ from hunterFormsBS.transform import Transformer
38
+ from hunterMakesPy import raiseIfNone
39
+ from more_itertools import loops
40
+ from operator import mul
41
+ from PoPE_pytorch import PoPE
42
+ from rotary_embedding_torch import RotaryEmbedding
43
+ from torch import arange, hann_window, nn, repeat_interleave, tensor, Tensor
44
+ from torch.nn import Module, ModuleList
45
+ from torch.utils.checkpoint import checkpoint # pyright: ignore[reportUnknownVariableType]
46
+ from torch_einops_kit import exists
47
+ from torch_einops_kit.einops import pack_one, unpack_one
48
+ from torch_einops_kit.scaleValues import RMSNorm
49
+ from torchaudio.functional import melscale_fbanks
50
+ from typing import cast, TYPE_CHECKING
51
+ import torch
52
+
53
+ if TYPE_CHECKING:
54
+ from collections.abc import Callable
55
+
56
+ class BandSplitRotator(Module):
57
+ """Separate a raw-audio mixture into stem audio with one converged separator.
58
+
59
+ You can use this class to instantiate one waveform-to-waveform separator that accepts mixture
60
+ waveform `Tensor` `raw_audio`, computes one complex short-time Fourier transform (STFT)
61
+ representation, groups frequency bins into band token `Tensor` `x`, applies repeated time-axis
62
+ and frequency-axis transformer blocks, predicts one complex mask for each configured stem, and
63
+ returns reconstructed stem waveform `Tensor` `recon_audio` or training loss through
64
+ `hunterFormsBS.bandSplit.lossComputation` [1]. The band front end can use one non-overlapping
65
+ BS-style partition or one overlapped mel-band layout built with
66
+ `torchaudio.functional.melscale_fbanks` [2].
67
+
68
+ `BandSplitRotator` keeps the full user-configurable surface on one constructor.
69
+ `BandSplitRotator` can select RoPE [3] or PoPE [4], request the optional `SageAttention`
70
+ backend [5][6], and preserve compatibility sentinels for older configuration files.
71
+
72
+ Attributes
73
+ ----------
74
+ audio_channels : int
75
+ Number of waveform channels expected at the input and reconstructed at the output.
76
+ band_split : BandSplit
77
+ Front-end projection module that converts gathered STFT band slices to model-width band token
78
+ `Tensor` `x`.
79
+ final_norm : RMSNorm | nn.Identity
80
+ Final normalization module applied to band token `Tensor` `x` after the hierarchical attention
81
+ stack.
82
+ freq_indices : Tensor
83
+ Gather index map that lists the frequency members belonging to each band. `forward` uses
84
+ `freq_indices` to gather band-local STFT slices.
85
+ layers : ModuleList
86
+ Hierarchical attention stack. Each entry stores one time-axis transformer block and one
87
+ frequency-axis transformer block.
88
+ mask_filter_bank : Tensor
89
+ Band-membership map registered as a non-persistent buffer. Entry `(bandIndex, frequencyIndex)`
90
+ is `True` when that frequency bin belongs to that band.
91
+ mask_estimators : ModuleList
92
+ One mask-estimator head per configured output source estimate. Each head predicts one complex
93
+ mask from band token `Tensor` `x`.
94
+ match_input_audio_length : bool
95
+ Whether inverse STFT reconstruction is forced back to the input waveform length.
96
+ multi_stft : ParametersComputeLoss
97
+ Internal multi-resolution STFT loss configuration consumed only when `forward` receives
98
+ `target`.
99
+ num_bands_per_freq : Tensor
100
+ Overlap count per frequency bin in `mask_filter_bank`. The count lets `forward` average
101
+ repeated complex-mask estimates when one frequency bin belongs to more than one band.
102
+ num_freqs_per_band : Tensor
103
+ Frequency-bin count for each band in `mask_filter_bank`. The count sizes the band front end
104
+ and each mask-estimator head.
105
+ num_stems : int
106
+ Number of configured output sources.
107
+ skip_connection : bool
108
+ Whether later hierarchical blocks add stored band token `Tensor` output from earlier
109
+ hierarchical blocks.
110
+ stereo : bool
111
+ Whether `forward` expects stereo waveform `Tensor` `raw_audio` instead of mono waveform
112
+ `Tensor` `raw_audio`.
113
+ stft_kwargs : ParametersSTFT
114
+ Keyword record shared by the forward and inverse STFT calls.
115
+ stft_window_fn : Callable[..., Tensor]
116
+ Partially applied window constructor used by the forward and inverse STFT calls.
117
+ use_torch_checkpoint : bool
118
+ Whether selected modules are executed through activation checkpointing [7].
119
+ zero_dc : bool
120
+ Whether the DC (zero-frequency) bin is zeroed before inverse STFT reconstruction.
121
+
122
+ Configuration modes
123
+ -------------------
124
+ automatic front-end selection : behavior
125
+ When `mask_filter_bank` is `None` and both `sample_rate` and `num_bands` are provided, the
126
+ constructor builds one overlapped mel-band front end with
127
+ `torchaudio.functional.melscale_fbanks` [2]. Otherwise the constructor derives one
128
+ non-overlapping band layout from `freqs_per_bands`.
129
+ compatibility parameters : behavior
130
+ `dim_freqs_in` and `linear_transformer_depth` remain in `__init__` for configuration
131
+ compatibility. `dim_freqs_in` is ignored because the effective frequency layout comes from the
132
+ STFT settings and band definitions. `linear_transformer_depth` is passed through as a
133
+ compatibility flag, but the current implementation no longer inserts a separate
134
+ `LinearAttention` block.
135
+ effective default selection : behavior
136
+ `final_norm`, `norm_output`, and `zero_dc` accept `None` only to preserve historical behavior
137
+ from earlier package releases. In mel-band mode the effective defaults are
138
+ `final_norm=False`, `norm_output=True`, and `zero_dc=False`. In non-overlapping band-split
139
+ mode the effective defaults are `final_norm=True`,
140
+ `norm_output=False`, and `zero_dc=True`. New configuration files are easier to reason about
141
+ when all three values are set explicitly.
142
+
143
+ Attention backends
144
+ ------------------
145
+ position encoding and attention backend : behavior
146
+ `use_pope` chooses between RoPE [3] and PoPE [4]. `sage_attention` asks downstream attention
147
+ blocks to call `sageattention.sageattn` from `SageAttention` [5][6]. When `sage_attention` is
148
+ `False`, `flash_attn` continues to request the standard PyTorch scaled-dot-product-attention
149
+ path through the downstream attention stack.
150
+
151
+ Downstream integration
152
+ ----------------------
153
+ downstream parameter passthrough : behavior
154
+ `BandSplitRotator.__init__` exposes parameters that are forwarded to downstream transformer,
155
+ attention, mask-estimator, STFT, and loss components. The forwarded identifiers stay
156
+ consistent across the downstream classes, including `activation`, `attn_dropout`,
157
+ `ff_dropout`, `sage_attention`, and `scale`.
158
+ stem selection : behavior
159
+ `forward` accepts `active_stem_ids`. The selected mask-estimator head index list becomes the
160
+ `stem_ids` value passed to `hunterFormsBS.bandSplit.lossComputation` [1], so an external
161
+ training loop can request the configured target stem index list [1].
162
+ checkpointing : behavior
163
+ `use_torch_checkpoint` applies activation checkpointing to `self.band_split`, the time
164
+ transformer block, the frequency transformer block, and each mask-estimator head [7]. This
165
+ behavior is practical for memory-constrained training, but it is not a defining architectural
166
+ requirement.
167
+
168
+ References
169
+ ----------
170
+ [1] `hunterFormsBS.bandSplit.lossComputation`
171
+
172
+ [2] torchaudio.functional.melscale_fbanks - torchaudio
173
+ https://docs.pytorch.org/audio/stable/generated/torchaudio.functional.melscale_fbanks.html
174
+ [3] Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., & Liu, Y. (2021). RoFormer: Enhanced
175
+ Transformer with Rotary Position Embedding. https://arxiv.org/abs/2104.09864
176
+ [4] Gopalakrishnan, A., Csordás, R., Schmidhuber, J., & Mozer, M. C. (2025). Decoupling the
177
+ "What" and "Where" With Polar Coordinate Positional Embeddings.
178
+ https://arxiv.org/abs/2509.10534
179
+ [5] thu-ml/SageAttention
180
+ https://github.com/thu-ml/SageAttention
181
+ [6] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., & Chen, J. (2025).
182
+ SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
183
+ https://arxiv.org/abs/2410.02367
184
+ [7] torch.utils.checkpoint.checkpoint
185
+ https://docs.pytorch.org/docs/stable/checkpoint.html
186
+ """
187
+ def __init__(
188
+ self
189
+ , dim: int
190
+ , *
191
+ , depth: int
192
+ , activation: type[nn.Module] = nn.Tanh
193
+ , attn_dropout: float = 0.0
194
+ , dim_freqs_in: int = 1025 # noqa: ARG002
195
+ , dim_head: int = 64
196
+ , ff_dropout: float = 0.0
197
+ , ff_mult: float = 4.0
198
+ , final_norm: bool | None = None
199
+ , flash_attn: bool = True
200
+ , freq_transformer_depth: int = 2
201
+ , freqs_per_bands: tuple[int, ...] = DEFAULT_FREQS_PER_BANDS
202
+ , heads: int = 8
203
+ , linear_transformer_depth: int = 0
204
+ , mask_estimator_depth: int = 1
205
+ , mask_filter_bank: Tensor | None = None
206
+ , match_input_audio_length: bool = True
207
+ , melscale_fbanks_mel_scale: str = 'slaney'
208
+ , melscale_fbanks_norm: str | None = 'slaney'
209
+ , mlp_expansion_factor: int = 4
210
+ , multi_stft_hop_size: int = 147
211
+ , multi_stft_normalized: bool = False
212
+ , multi_stft_resolution_loss_weight: float = 1.0
213
+ , multi_stft_resolutions_window_sizes: tuple[int, ...] = (4096, 2048, 1024, 512, 256)
214
+ , multi_stft_window_fn: Callable[..., Tensor] = hann_window
215
+ , norm_output: bool | None = None
216
+ , num_bands: int | None = None
217
+ , num_stems: int = 1
218
+ , sage_attention: bool = False
219
+ , sample_rate: float | None = None
220
+ , scale: float | None = None
221
+ , segm_out_bins: int | None = None
222
+ , segm_out_channels: int = 4
223
+ , segm_base_channels: int = 64
224
+ , segm_base_depth: int = 2
225
+ , segm_num_hyperedges: int = 32
226
+ , segm_num_heads: int = 8
227
+ , segm_backbone_channels: tuple[int, int, int, int, int] | None = None
228
+ , segm_hyperace_k: int = 2
229
+ , segm_hyperace_l: int = 1
230
+ , segm_hyperace_c_h: float = 0.5
231
+ , segm_hyperace_c_l: float = 0.25
232
+ , segm_hyperace_c3ah_expansion: float = 1.0
233
+ , segm_hyperace_low_order_depth: int = 1
234
+ , segm_hyperace_low_order_kernel: int = 3
235
+ , segm_hyperace_low_order_expansion: float = 1.0
236
+ , segm_hyperace_out_channels: int | None = None
237
+ , segm_decoder_channels: list[int] | tuple[int, int, int, int] | None = None
238
+ , segm_decoder_block_depth: int = 1
239
+ , segm_decoder_block_kernel: int = 3
240
+ , segm_decoder_block_expansion: float = 0.5
241
+ , segm_upsample_scales: tuple[int, int, int, int] = (2, 2, 2, 2)
242
+ , segm_upsample_tfc_tdf_depth: int = 2
243
+ , segm_upsample_tfc_tdf_bn: int = 4
244
+ , segm_activation: type[nn.Module] = nn.SiLU
245
+ , segm_norm_eps: float = 1e-8
246
+ , segm_norm_affine: bool = True
247
+ , segm_conv_bias: bool = False
248
+ , segm_linear_bias: bool = False
249
+ , skip_connection: bool = False
250
+ , stereo: bool = False
251
+ , stft_hop_length: int = 512
252
+ , stft_n_fft: int = 2048
253
+ , stft_normalized: bool = False
254
+ , stft_win_length: int = 1024
255
+ , stft_window_fn: Callable[..., Tensor] = hann_window
256
+ , time_transformer_depth: int = 2
257
+ , use_hyperACE: bool = False
258
+ , use_pope: bool = False
259
+ , use_torch_checkpoint: bool = False
260
+ , zero_dc: bool | None = None
261
+ ) -> None:
262
+ """Configure the converged separator and its band-split front end.
263
+
264
+ You can use `__init__` to choose the band layout, the hierarchical attention layout, the
265
+ attention backend, the forward and inverse STFT settings, the internal multi-resolution STFT
266
+ loss settings, and the optional segmentation-style mask-estimator branch. `__init__` keeps
267
+ parameter identifiers aligned with downstream components so one configuration record can pass
268
+ through the package without renaming. `__init__` still accepts several compatibility fields
269
+ from earlier package releases.
270
+
271
+ Parameters
272
+ ----------
273
+ dim : int
274
+ Feature width of each band token after the front-end projection.
275
+ depth : int
276
+ Number of top-level layer groups. Each group contains one time-axis transformer block and
277
+ one frequency-axis transformer block.
278
+ activation : type[nn.Module] = nn.Tanh
279
+ Activation class instantiated between non-final linear layers inside each downstream
280
+ mask-estimator feedforward block. The default value keeps the hyperbolic tangent activation
281
+ used by the package defaults.
282
+ attn_dropout : float = 0.0
283
+ Dropout probability forwarded to each downstream attention block.
284
+ dim_freqs_in : int = 1025
285
+ Vestigial field retained for external configuration files. Current code derives the
286
+ effective frequency-bin layout from `stft_n_fft`, `mask_filter_bank`, `freqs_per_bands`,
287
+ and the automatic front-end selection logic instead of reading `dim_freqs_in`.
288
+ dim_head : int = 64
289
+ Per-head feature width for the downstream time-axis and frequency-axis attention blocks.
290
+ ff_dropout : float = 0.0
291
+ Dropout probability forwarded to each downstream feedforward block.
292
+ ff_mult : float = 4.0
293
+ Feedforward hidden-width expansion factor forwarded to downstream transformer blocks.
294
+ `None` keeps the downstream default.
295
+ final_norm : bool | None = None
296
+ Toggle the final normalization module. `None` is a compatibility sentinel for
297
+ configuration files that relied on earlier mode-specific defaults, not a distinct modeling
298
+ mode. The effective default is `True` in non-overlapping band-split mode and `False` in
299
+ mel-band mode. New configuration files should set `final_norm` explicitly.
300
+ flash_attn : bool = True
301
+ Request the flash-attention or scaled-dot-product-attention path inside downstream
302
+ attention blocks when `sage_attention` is `False` and the backend supports that path.
303
+ freq_transformer_depth : int = 2
304
+ Depth of the per-layer frequency-axis transformer block.
305
+ freqs_per_bands : tuple[int, ...] = DEFAULT_FREQS_PER_BANDS
306
+ Non-overlapping frequency-bin counts used when the constructor builds the BS-style band
307
+ front end.
308
+ heads : int = 8
309
+ Number of attention heads in each downstream attention block.
310
+ linear_transformer_depth : int = 0
311
+ Vestigial parameter retained after removal of the dedicated `LinearAttention` block.
312
+ Nonzero values still set the downstream compatibility flag, but current transformer code
313
+ does not insert a separate linear-attention sublayer.
314
+ mask_estimator_depth : int = 1
315
+ Depth of the per-band MLP inside each mask-estimator head. This unified implementation
316
+ defaults to `1`. Ports from older configuration files that assumed `2` should set
317
+ `mask_estimator_depth=1` explicitly.
318
+ mask_filter_bank : Tensor | None = None
319
+ Custom band-membership `Tensor` with shape `(band, freq)`. Entry `(bandIndex,
320
+ frequencyIndex)` is truthy when that frequency bin belongs to that band. When
321
+ `mask_filter_bank` is provided, `__init__` skips automatic band construction. When
322
+ `mask_filter_bank` is `None` and mel-band mode is selected, `__init__` calls
323
+ `torchaudio.functional.melscale_fbanks` [1], converts the returned filter bank to one
324
+ Boolean membership map, and forces the first and last frequency bins into the first and
325
+ last bands. When `mask_filter_bank` is `None` and non-overlapping band-split mode is
326
+ selected, `__init__` derives the Boolean membership map from `freqs_per_bands`.
327
+ match_input_audio_length : bool = True
328
+ When `True`, inverse STFT reconstruction is forced back to the original waveform length.
329
+ melscale_fbanks_mel_scale : str = 'slaney'
330
+ Mel-scale formula name forwarded to `torchaudio.functional.melscale_fbanks` [1] during
331
+ automatic mel-band construction. `melscale_fbanks_mel_scale` is ignored when
332
+ `mask_filter_bank` is provided or non-overlapping band-split mode is selected.
333
+ melscale_fbanks_norm : str | None = 'slaney'
334
+ Mel-filter normalization rule forwarded to `torchaudio.functional.melscale_fbanks` [1]
335
+ during automatic mel-band construction. `None` disables normalization.
336
+ `melscale_fbanks_norm` is ignored when `mask_filter_bank` is provided or
337
+ non-overlapping band-split mode is selected.
338
+ mlp_expansion_factor : int = 4
339
+ Hidden-width expansion factor inside each mask-estimator MLP.
340
+ multi_stft_hop_size : int = 147
341
+ Hop size for the internal multi-resolution STFT loss.
342
+ multi_stft_normalized : bool = False
343
+ Normalization flag for the internal multi-resolution STFT transforms.
344
+ multi_stft_resolution_loss_weight : float = 1.0
345
+ Weight applied to the multi-resolution STFT term before `forward` adds that term to the
346
+ waveform-domain loss.
347
+ multi_stft_resolutions_window_sizes : tuple[int, ...] = (4096, 2048, 1024, 512, 256)
348
+ Window-size sequence used by the internal multi-resolution STFT loss.
349
+ multi_stft_window_fn : Callable[..., Tensor] = halfsineTensor
350
+ Window constructor used by the internal multi-resolution STFT loss.
351
+ norm_output : bool | None = None
352
+ Output-normalization toggle inside each downstream transformer block. `None` is a
353
+ compatibility sentinel for configuration files that depended on historical mode-specific
354
+ defaults. The effective default is `False` in non-overlapping band-split mode and `True`
355
+ in mel-band mode. New configuration files should set `norm_output` explicitly.
356
+ num_bands : int | None = None
357
+ Number of bands for automatic front-end construction. When `mask_filter_bank` is omitted,
358
+ `sample_rate` together with `num_bands` selects mel-band mode. When `mask_filter_bank` is
359
+ provided and `num_bands` is `None`, `__init__` infers `num_bands` from
360
+ `mask_filter_bank.shape[0]`. When non-overlapping band-split mode is active, `__init__`
361
+ does not silently correct mismatches between `num_bands` and `freqs_per_bands`.
362
+ num_stems : int = 1
363
+ Number of configured output sources.
364
+ sage_attention : bool = False
365
+ Request `sageattention.sageattn` from `SageAttention` [2][3] inside downstream attention
366
+ blocks. `hunterFormsBS` does not install `SageAttention`, so install the package manually
367
+ before setting `sage_attention=True`.
368
+ sample_rate : float | None = None
369
+ Sample-rate value used only when automatic mel-band construction is active. When
370
+ `mask_filter_bank` is `None`, `sample_rate` together with `num_bands` selects mel-band
371
+ mode.
372
+ scale : float | None = None
373
+ Optional attention-score scale override forwarded to downstream attention blocks. `None`
374
+ keeps the standard per-head scale.
375
+ skip_connection : bool = False
376
+ If `True`, each hierarchical layer adds stored band token `Tensor` output from every
377
+ earlier hierarchical layer before the current layer runs.
378
+ stereo : bool = False
379
+ Expect stereo waveform input and reconstruct stereo waveform output. When `stereo` is
380
+ `False`, the class expects mono waveform input.
381
+ stft_hop_length : int = 512
382
+ Hop length for the forward and inverse STFT.
383
+ stft_n_fft : int = 2048
384
+ FFT size for the forward and inverse STFT.
385
+ stft_normalized : bool = False
386
+ Normalization flag for the forward and inverse STFT.
387
+ stft_win_length : int = 1024
388
+ Length of the windowing function for the forward and inverse STFT.
389
+ stft_window_fn : Callable[..., Tensor] = halfsineTensor
390
+ Callable Python function to construct the windowing function used by the forward and
391
+ inverse STFT.
392
+ time_transformer_depth : int = 2
393
+ Depth of the per-layer time-axis transformer block.
394
+ use_hyperACE : bool = False
395
+ Whether each mask-estimator head adds the optional segmentation-style branch described by
396
+ `hunterFormsBS.hyperACE.SegmModel.__init__` [4].
397
+ use_pope : bool = False
398
+ Replace RoPE with PoPE in the downstream time-axis and frequency-axis attention
399
+ blocks.
400
+ use_torch_checkpoint : bool = False
401
+ Enable activation checkpointing for `self.band_split`, each transformer block, and each
402
+ mask-estimator head.
403
+ zero_dc : bool | None = None
404
+ Toggle zeroing of the DC (zero-frequency) bin before inverse STFT reconstruction. `None`
405
+ is a compatibility sentinel for configuration files that relied on historical
406
+ mode-specific defaults. The effective default is `True` in non-overlapping band-split mode
407
+ and `False` in mel-band mode. New configuration files should set `zero_dc`
408
+ explicitly.
409
+
410
+ Other Parameters
411
+ ----------------
412
+ segmentation output geometry : forwarded parameter family
413
+ See `hunterFormsBS.hyperACE.SegmModel.__init__` [4]. `BandSplitRotator` forwards
414
+ `segm_out_bins` and `segm_out_channels`.
415
+ backbone parameters : forwarded parameter family
416
+ See `hunterFormsBS.hyperACE.Backbone.__init__` [5]. `BandSplitRotator` forwards
417
+ `segm_base_channels`, `segm_base_depth`, and `segm_backbone_channels`.
418
+ hypergraph size and branch parameters : forwarded parameter family
419
+ See `hunterFormsBS.hyperACE.HyperACE.__init__` [6]. `BandSplitRotator` forwards
420
+ `segm_num_hyperedges`, `segm_num_heads`, and the `segm_hyperace_*` family.
421
+ decoder parameters : forwarded parameter family
422
+ See `hunterFormsBS.hyperACE.Decoder.__init__` [7]. `BandSplitRotator` forwards
423
+ `segm_decoder_channels`, `segm_decoder_block_depth`, `segm_decoder_block_kernel`, and
424
+ `segm_decoder_block_expansion`.
425
+ upsample and shared layer settings : forwarded parameter family
426
+ See `hunterFormsBS.hyperACE.ProgressiveUpsampleHead.__init__` [8]. `BandSplitRotator`
427
+ forwards `segm_upsample_scales`, `segm_upsample_tfc_tdf_depth`,
428
+ `segm_upsample_tfc_tdf_bn`, `segm_activation`, `segm_norm_eps`,
429
+ `segm_norm_affine`, `segm_conv_bias`, and `segm_linear_bias`.
430
+
431
+ Size-mismatch error when loading weights
432
+ ----------------------------------------
433
+ If you are using a checkpoint and configuration file copied from an earlier non-overlapping
434
+ release, and you get a size-mismatch error when loading the checkpoint, check
435
+ `mask_estimator_depth` in the configuration file. The earlier release behavior effectively
436
+ used `mask_estimator_depth=1` even when configuration files stored `2`, because a later
437
+ subtraction was applied. This package eliminates that subtraction, so the direct equivalent is
438
+ `mask_estimator_depth=1`.
439
+
440
+ References
441
+ ----------
442
+ [1] torchaudio.functional.melscale_fbanks - torchaudio
443
+ https://docs.pytorch.org/audio/stable/generated/torchaudio.functional.melscale_fbanks.html
444
+ [2] thu-ml/SageAttention
445
+ https://github.com/thu-ml/SageAttention
446
+ [3] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., & Chen, J. (2025).
447
+ SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
448
+ https://arxiv.org/abs/2410.02367
449
+ [4] `hunterFormsBS.hyperACE.SegmModel.__init__`
450
+
451
+ [5] `hunterFormsBS.hyperACE.Backbone.__init__`
452
+
453
+ [6] `hunterFormsBS.hyperACE.HyperACE.__init__`
454
+
455
+ [7] `hunterFormsBS.hyperACE.Decoder.__init__`
456
+
457
+ [8] `hunterFormsBS.hyperACE.ProgressiveUpsampleHead.__init__`
458
+ """
459
+ super().__init__()
460
+
461
+ #======== class attributes, including backward compatibility =========
462
+
463
+ self.stereo: bool = stereo
464
+ self.audio_channels: int = 2 if self.stereo else 1
465
+ self.num_stems: int = num_stems
466
+ self.skip_connection: bool = skip_connection
467
+ self.use_torch_checkpoint: bool = use_torch_checkpoint
468
+
469
+ if mask_filter_bank is None:
470
+ if (num_bands is not None) and (sample_rate is not None):
471
+ # Tantamount to `MelBandRoformer = True`.
472
+ filter_bank: Tensor = melscale_fbanks(n_freqs=stft_n_fft // 2 + 1
473
+ , f_min=0.0
474
+ , f_max=sample_rate / 2.0
475
+ , n_mels=num_bands
476
+ , sample_rate=int(sample_rate)
477
+ , norm=melscale_fbanks_norm
478
+ , mel_scale=melscale_fbanks_mel_scale)
479
+ filter_bank = filter_bank.T
480
+ mask_filter_bank = 0 < filter_bank
481
+ mask_filter_bank[0, 0] = True
482
+ mask_filter_bank[-1, -1] = True
483
+
484
+ if final_norm is None:
485
+ final_norm = False
486
+ if norm_output is None:
487
+ norm_output = True
488
+ if zero_dc is None:
489
+ zero_dc = False
490
+ else:
491
+ # Tantamount to `BSRoformer = True`, by default.
492
+ num_bands = num_bands or len(freqs_per_bands)
493
+ filter_bank: Tensor = repeat_interleave(arange(num_bands), tensor(freqs_per_bands))
494
+ mask_filter_bank = filter_bank[None, :] == arange(num_bands)[:, None]
495
+ if final_norm is None:
496
+ final_norm = True
497
+ if norm_output is None:
498
+ norm_output = False
499
+ if zero_dc is None:
500
+ zero_dc = True
501
+ elif num_bands is None:
502
+ num_bands = mask_filter_bank.shape[0]
503
+
504
+ self.zero_dc: bool = raiseIfNone(zero_dc, f'I received {zero_dc = }, but I need a type `bool` value or a "truthy" value.')
505
+ self.final_norm: RMSNorm | nn.Identity = RMSNorm(dim) if raiseIfNone(final_norm, f'I received {final_norm = }, but I need a type `bool` value or a "truthy" value.') else nn.Identity()
506
+
507
+ #======== rotator and transformer =========================
508
+
509
+ transformer_kwargs: ParametersTransformer = ParametersTransformer(
510
+ attn_dropout=attn_dropout
511
+ , dim_head=dim_head
512
+ , dim=dim
513
+ , ff_dropout=ff_dropout
514
+ , ff_mult=ff_mult
515
+ , flash_attn=flash_attn
516
+ , heads=heads
517
+ , linear_attn=(0 < linear_transformer_depth)
518
+ , norm_output=raiseIfNone(norm_output, f'I received {norm_output = }, but I need a type `bool` value or a "truthy" value.')
519
+ , sage_attention=sage_attention
520
+ , scale=scale
521
+ )
522
+
523
+ if use_pope:
524
+ time_pope_embed: PoPE | None = PoPE(dim=dim_head, heads=heads)
525
+ freq_pope_embed: PoPE | None = PoPE(dim=dim_head, heads=heads)
526
+ time_rotary_embed: RotaryEmbedding | None = None
527
+ freq_rotary_embed: RotaryEmbedding | None = None
528
+ else:
529
+ time_rotary_embed = RotaryEmbedding(dim=dim_head)
530
+ freq_rotary_embed = RotaryEmbedding(dim=dim_head)
531
+ time_pope_embed = None
532
+ freq_pope_embed = None
533
+
534
+ self.layers: ModuleList = ModuleList([
535
+ nn.ModuleList([
536
+ Transformer(depth=time_transformer_depth, rotary_embed=time_rotary_embed, pope_embed=time_pope_embed, **transformer_kwargs)
537
+ , Transformer(depth=freq_transformer_depth, rotary_embed=freq_rotary_embed, pope_embed=freq_pope_embed, **transformer_kwargs)
538
+ ]) for _layer in loops(depth)
539
+ ])
540
+
541
+ #======== stft ============================================
542
+
543
+ self.stft_kwargs: ParametersSTFT = ParametersSTFT(n_fft=stft_n_fft, hop_length=stft_hop_length, win_length=stft_win_length, normalized=stft_normalized)
544
+ self.stft_window_fn: Callable[..., Tensor] = partial(stft_window_fn, stft_win_length)
545
+ self.match_input_audio_length: bool = match_input_audio_length
546
+
547
+ #======== band split and mask estimator ===================
548
+
549
+ parametersMaskEstimator = ParametersMaskEstimator(activation=activation, dim=dim, depth=mask_estimator_depth, mlp_expansion_factor=mlp_expansion_factor
550
+ , segm_out_bins=segm_out_bins, segm_out_channels=segm_out_channels, segm_base_channels=segm_base_channels, segm_base_depth=segm_base_depth
551
+ , segm_num_hyperedges=segm_num_hyperedges, segm_num_heads=segm_num_heads, segm_backbone_channels=segm_backbone_channels, segm_hyperace_k=segm_hyperace_k
552
+ , segm_hyperace_l=segm_hyperace_l, segm_hyperace_c_h=segm_hyperace_c_h, segm_hyperace_c_l=segm_hyperace_c_l, segm_hyperace_c3ah_expansion=segm_hyperace_c3ah_expansion
553
+ , segm_hyperace_low_order_depth=segm_hyperace_low_order_depth, segm_hyperace_low_order_kernel=segm_hyperace_low_order_kernel
554
+ , segm_hyperace_low_order_expansion=segm_hyperace_low_order_expansion, segm_hyperace_out_channels=segm_hyperace_out_channels
555
+ , segm_decoder_channels=segm_decoder_channels, segm_decoder_block_depth=segm_decoder_block_depth, segm_decoder_block_kernel=segm_decoder_block_kernel
556
+ , segm_decoder_block_expansion=segm_decoder_block_expansion, segm_upsample_scales=segm_upsample_scales, segm_upsample_tfc_tdf_depth=segm_upsample_tfc_tdf_depth
557
+ , segm_upsample_tfc_tdf_bn=segm_upsample_tfc_tdf_bn, segm_activation=segm_activation, segm_norm_eps=segm_norm_eps
558
+ , segm_norm_affine=segm_norm_affine, segm_conv_bias=segm_conv_bias, segm_linear_bias=segm_linear_bias, use_hyperACE=use_hyperACE)
559
+ self.register_buffer('mask_filter_bank', mask_filter_bank, persistent=False)
560
+ num_freqs_per_band: Tensor = reduce(mask_filter_bank, 'b f -> b', 'sum')
561
+ self.register_buffer('num_freqs_per_band', num_freqs_per_band, persistent=False)
562
+
563
+ freqs_per_bands_with_complex: tuple[int, ...] = tuple(map(partial(mul, 2 * self.audio_channels), num_freqs_per_band.tolist())) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType]
564
+ self.band_split: BandSplit = BandSplit(dim=dim, dim_inputs=freqs_per_bands_with_complex)
565
+ self.mask_estimators: ModuleList = nn.ModuleList([MaskEstimator(dim_inputs=freqs_per_bands_with_complex, **parametersMaskEstimator)
566
+ for _stem_index in loops(self.num_stems)])
567
+
568
+ freqs: int = stft_n_fft // 2 + 1
569
+ repeated_freq_indices: Tensor = repeat(torch.arange(freqs), 'f -> b f', b=num_bands)
570
+ freq_indices: Tensor = repeated_freq_indices[mask_filter_bank]
571
+
572
+ if self.stereo:
573
+ freq_indices = repeat(freq_indices, 'f -> f s', s=2)
574
+ freq_indices = freq_indices * 2 + torch.arange(2)
575
+ freq_indices = rearrange(freq_indices, 'f s -> (f s)')
576
+
577
+ self.register_buffer('freq_indices', freq_indices, persistent=False)
578
+ num_bands_per_freq: Tensor = reduce(mask_filter_bank, 'b f -> f', 'sum')
579
+ self.register_buffer('num_bands_per_freq', num_bands_per_freq, persistent=False)
580
+
581
+ self.multi_stft: ParametersComputeLoss = ParametersComputeLoss(hop_length=multi_stft_hop_size, loss_weight=multi_stft_resolution_loss_weight
582
+ , n_fft=stft_n_fft, normalized=multi_stft_normalized, window_fn=multi_stft_window_fn, window_sizes=multi_stft_resolutions_window_sizes)
583
+
584
+ def forward(self, raw_audio: Tensor, target: Tensor | None = None, active_stem_ids: list[int] | None = None, *, return_loss_breakdown: bool = False) -> Tensor | tuple[Tensor, tuple[Tensor, Tensor]]:
585
+ """Separate `raw_audio` into stem waveform output or training loss.
586
+
587
+ You can use `forward` for both inference and training. `forward` accepts mixture waveform
588
+ `Tensor` `raw_audio`, computes one complex STFT representation `Tensor` `stft_repr`, gathers
589
+ band-local slices into band token `Tensor` `x`, routes band token `Tensor` `x` through the
590
+ hierarchical time-axis and frequency-axis attention core used by BS-RoFormer [1] and Mel-Band
591
+ RoFormer [2], estimates one complex mask `Tensor` `masks` for each configured stem, and
592
+ reconstructs stem waveform `Tensor` `recon_audio` with the inverse STFT. When `target` exists,
593
+ `forward` instead returns loss from `hunterFormsBS.bandSplit.lossComputation` [5].
594
+
595
+ The downstream attention stack uses RoPE [3] or PoPE [4] according to `__init__`. When
596
+ `sage_attention` was enabled at construction time, downstream `Attend` blocks request
597
+ `sageattention.sageattn` from `SageAttention` [6][7]. `active_stem_ids` lets one external
598
+ training loop keep one multi-stem model while selecting the supervised stem index list passed
599
+ to `hunterFormsBS.bandSplit.lossComputation` [5][8], and `self.use_torch_checkpoint` can trade
600
+ compute for activation memory with activation checkpointing [9].
601
+
602
+ Parameters
603
+ ----------
604
+ raw_audio : Tensor
605
+ Input mixture waveform `Tensor` `raw_audio`. `forward` accepts shape `(batch, time)` for
606
+ mono shorthand or shape `(batch, channel, time)` for explicit channel layout. The
607
+ `channel` axis must match `self.stereo`.
608
+ target : Tensor | None = None
609
+ Reference stem waveform `Tensor` `target` used only for loss computation. When `target` is
610
+ `None`, `forward` returns reconstructed stem waveform `Tensor` `recon_audio`. When
611
+ `target` exists, `forward` returns the loss from `hunterFormsBS.bandSplit.lossComputation`
612
+ [5].
613
+ active_stem_ids : list[int] | None = None
614
+ Optional stem index list selecting which mask-estimator heads contribute to complex mask
615
+ `Tensor` `masks` and which target stems `stem_ids` supervise [5]. When `active_stem_ids`
616
+ is `None`, the default behavior is to use every configured head. This behavior is mainly
617
+ intended for framework adapters such as Music-Source-Separation-Training [8].
618
+ return_loss_breakdown : bool = False
619
+ Request the expanded loss return path with both the waveform-domain term and the
620
+ multi-resolution STFT term. `return_loss_breakdown` matters only when `target` exists.
621
+
622
+ Returns
623
+ -------
624
+ recon_audio : Tensor
625
+ `recon_audio` contains reconstructed stem waveform with axis order batch, stem, audio
626
+ channel, time. `recon_audio` is returned when `target` is `None`.
627
+ total_loss : Tensor
628
+ Returned when `target` exists and `return_loss_breakdown` is `False`.
629
+ loss_with_breakdown : tuple[Tensor, tuple[Tensor, Tensor]]
630
+ Returned when `target` exists and `return_loss_breakdown` is `True`. The outer `Tensor` is
631
+ the total loss. The inner pair contains the waveform L1 term and the unweighted
632
+ multi-resolution STFT loss term from `hunterFormsBS.bandSplit.lossComputation` [5].
633
+
634
+ Execution stages
635
+ ----------------
636
+ spectral analysis and band gathering : behavior
637
+ `forward` computes one complex STFT representation `Tensor` `stft_repr` from waveform
638
+ `Tensor` `raw_audio`, converts the complex axis to one real-imaginary pair layout, merges
639
+ the audio-channel axis into the frequency axis, and gathers the frequency members listed
640
+ by `self.freq_indices`. The gathered view becomes band token `Tensor` `x`, where each time
641
+ step carries the concatenated real and imaginary values for one band.
642
+ hierarchical attention core : behavior
643
+ Each top-level layer group applies one time-axis transformer block and one frequency-axis
644
+ transformer block. When `self.skip_connection` is `True`, each layer group adds stored
645
+ outputs from earlier layer groups before running the current group.
646
+ mask accumulation : behavior
647
+ Each active mask-estimator head predicts one complex mask `Tensor` `masks` over the
648
+ gathered band view. When the front end uses overlapped mel bands [2], `forward`
649
+ scatter-adds repeated frequency-bin estimates back to the full frequency layout and
650
+ divides by `self.num_bands_per_freq`, so overlapped frequency bins receive the average
651
+ complex mask instead of the sum.
652
+ waveform reconstruction : behavior
653
+ `forward` multiplies the original complex STFT representation by complex mask `Tensor`
654
+ `masks`, applies the optional DC (zero-frequency) bin zeroing rule, and reconstructs
655
+ waveform `Tensor` `recon_audio` with the inverse STFT. When
656
+ `self.match_input_audio_length` is `True`, the inverse STFT is asked to match the original
657
+ sample count.
658
+
659
+ Framework adaptation
660
+ --------------------
661
+ activation checkpointing : behavior
662
+ When `self.use_torch_checkpoint` is `True`, `forward` applies activation checkpointing to
663
+ `self.band_split`, the time transformer block, the frequency transformer block, and each
664
+ mask-estimator head [9]. Activation checkpointing recomputes intermediate activations
665
+ during the backward pass, which lowers activation memory use at the cost of extra compute
666
+ [9].
667
+ stem-target interoperability : behavior
668
+ `active_stem_ids` exists so one external training loop can keep one multi-stem model while
669
+ still computing loss only for the configured target stem index list [8]. `forward`
670
+ preserves the selected `stem_ids` list and passes `stem_ids` to
671
+ `hunterFormsBS.bandSplit.lossComputation` [5].
672
+
673
+ Device fallback
674
+ ---------------
675
+ MPS retry path : behavior
676
+ On `device.type == 'mps'`, where MPS means Apple Metal Performance Shaders, `forward`
677
+ retries the forward STFT and inverse STFT on CPU when the direct call fails.
678
+
679
+ References
680
+ ----------
681
+ [1] Lu, W.-T., Wang, J.-C., Kong, Q., & Hung, Y.-N. (2023). Music Source Separation with
682
+ Band-Split RoPE Transformer. https://arxiv.org/abs/2309.02612
683
+ [2] Wang, J.-C., Lu, W.-T., and Chen, J. (2024) Mel-RoFormer for Vocal Separation and Vocal Melody
684
+ Transcription https://arxiv.org/abs/2409.04702
685
+ [3] Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., & Liu, Y. (2021). RoFormer: Enhanced
686
+ Transformer with Rotary Position Embedding. https://arxiv.org/abs/2104.09864
687
+ [4] Gopalakrishnan, A., Csordás, R., Schmidhuber, J., & Mozer, M. C. (2025). Decoupling
688
+ the "What" and "Where" With Polar Coordinate Positional Embeddings.
689
+ https://arxiv.org/abs/2509.10534
690
+ [5] `hunterFormsBS.bandSplit.lossComputation`
691
+
692
+ [6] thu-ml/SageAttention
693
+ https://github.com/thu-ml/SageAttention
694
+ [7] Zhang, J., Wei, J., Huang, H., Zhang, P., Zhu, J., & Chen, J. (2025).
695
+ SageAttention: Accurate 8-Bit Attention for Plug-and-play Inference Acceleration.
696
+ https://arxiv.org/abs/2410.02367
697
+ [8] ZFTurbo/Music-Source-Separation-Training
698
+ https://github.com/ZFTurbo/Music-Source-Separation-Training
699
+ [9] torch.utils.checkpoint.checkpoint
700
+ https://docs.pytorch.org/docs/stable/checkpoint.html
701
+ """ # noqa: DOC501
702
+ if raw_audio.ndim == 2:
703
+ raw_audio = rearrange(raw_audio, 'b t -> b 1 t')
704
+
705
+ batch, channels, raw_audio_length = raw_audio.shape
706
+
707
+ istft_length: int | None = raw_audio_length if self.match_input_audio_length else None
708
+
709
+ if not ((not self.stereo and channels == 1) or (self.stereo and channels == 2)):
710
+ message: str = f'I received `{channels = }` audio channel(s) but `{self.stereo = }`. I need `channels == 1` when `stereo` is `False`, or `channels == 2` when `stereo` is `True`.'
711
+ raise ValueError(message)
712
+
713
+ # to stft
714
+ raw_audio, batch_audio_channel_packed_shape = pack_one(raw_audio, '* t')
715
+ stft_window: Tensor = self.stft_window_fn(device=raw_audio.device)
716
+
717
+ # RuntimeError: FFT operations are only supported on MacOS 14+
718
+ try:
719
+ stft_repr: Tensor = torch.stft(raw_audio, **self.stft_kwargs, window=stft_window, return_complex=True)
720
+ except RuntimeError:
721
+ stft_repr = torch.stft(raw_audio.cpu(), **self.stft_kwargs, window=stft_window.cpu(), return_complex=True).to(raw_audio.device)
722
+ stft_repr = torch.view_as_real(stft_repr)
723
+
724
+ stft_repr = unpack_one(stft_repr, batch_audio_channel_packed_shape, '* f t c')
725
+
726
+ # merge stereo / mono into the frequency, with frequency leading dimension, for band splitting
727
+ stft_repr = rearrange(stft_repr, 'b s f t c -> b (f s) t c')
728
+
729
+ # index out all frequencies for all frequency ranges across bands ascending in one go
730
+
731
+ batch_arange: Tensor = torch.arange(batch, device=raw_audio.device)[..., None]
732
+
733
+ # account for stereo
734
+
735
+ x: Tensor = stft_repr[batch_arange, cast('Tensor', self.freq_indices)]
736
+
737
+ # fold the complex (real and imag) into the frequencies dimension
738
+
739
+ x = rearrange(x, 'b f t c -> b t (f c)')
740
+
741
+ if self.use_torch_checkpoint:
742
+ x = checkpoint(self.band_split, x, use_reentrant=False) # pyright: ignore[reportUnknownVariableType, reportAssignmentType]
743
+ else:
744
+ x = self.band_split(x)
745
+
746
+ # axial / hierarchical attention
747
+ store: list[Tensor] = [tensor([])] * len(self.layers)
748
+ for index, transformer_block in enumerate(self.layers):
749
+ layer: ModuleList = cast('ModuleList', transformer_block)
750
+ time_transformer: Transformer = cast('Transformer', layer[-2])
751
+ freq_transformer: Transformer = cast('Transformer', layer[-1])
752
+
753
+ if self.skip_connection:
754
+ x += sum(store[0:index])
755
+
756
+ x = rearrange(x, 'b t f d -> b f t d')
757
+ x, ps = pack([x], '* t d')
758
+
759
+ if self.use_torch_checkpoint:
760
+ x = checkpoint(time_transformer, x, use_reentrant=False) # pyright: ignore[reportUnknownVariableType, reportAssignmentType]
761
+ else:
762
+ x = time_transformer(x)
763
+
764
+ (x,) = unpack(x, ps, '* t d')
765
+ x = rearrange(x, 'b f t d -> b t f d')
766
+ x, ps = pack([x], '* f d')
767
+
768
+ if self.use_torch_checkpoint:
769
+ x = checkpoint(freq_transformer, x, use_reentrant=False) # pyright: ignore[reportUnknownVariableType, reportAssignmentType]
770
+ else:
771
+ x = freq_transformer(x)
772
+
773
+ (x,) = unpack(x, ps, '* f d')
774
+
775
+ if self.skip_connection:
776
+ store[index] = x
777
+
778
+ x = self.final_norm(x)
779
+
780
+ if active_stem_ids is None:
781
+ heads: ModuleList = self.mask_estimators
782
+ stem_ids: list[int] = list(range(len(self.mask_estimators)))
783
+ else:
784
+ heads = ModuleList([self.mask_estimators[stem_id] for stem_id in active_stem_ids])
785
+ stem_ids = active_stem_ids
786
+
787
+ if self.use_torch_checkpoint:
788
+ masks: Tensor = torch.stack([checkpoint(fn, x, use_reentrant=False) for fn in heads], dim=1) # pyright: ignore[reportArgumentType]
789
+ else:
790
+ masks = torch.stack([mask_estimator(x) for mask_estimator in heads], dim=1)
791
+ masks = rearrange(masks, 'b n t (f c) -> b n f t c', c=2)
792
+
793
+ # modulate frequency representation
794
+ stft_repr = rearrange(stft_repr, 'b f t c -> b 1 f t c')
795
+
796
+ # complex number multiplication
797
+ stft_repr = torch.view_as_complex(stft_repr)
798
+ masks = torch.view_as_complex(masks)
799
+ masks = masks.type(stft_repr.dtype)
800
+
801
+ # average the estimated mask for the overlapped frequencies
802
+ scatter_indices: Tensor = repeat(cast('Tensor', self.freq_indices), 'f -> b n f t', b=batch, n=self.num_stems, t=stft_repr.shape[-1])
803
+
804
+ stft_repr_expanded_stems: Tensor = repeat(stft_repr, 'b 1 ... -> b n ...', n=self.num_stems)
805
+ masks_summed: Tensor = torch.zeros_like(stft_repr_expanded_stems).scatter_add_(2, scatter_indices, masks)
806
+
807
+ denom: Tensor = repeat(cast('Tensor', self.num_bands_per_freq), 'f -> (f r) 1', r=channels)
808
+
809
+ masks = masks_summed / denom.clamp(min=1e-8)
810
+
811
+ # modulate stft repr with estimated mask
812
+ stft_repr *= masks
813
+
814
+ # istft
815
+
816
+ stft_repr = rearrange(stft_repr, 'b n (f s) t -> (b n s) f t', s=self.audio_channels)
817
+
818
+ if self.zero_dc:
819
+ stft_repr = stft_repr.index_fill(1, tensor(0, device=raw_audio.device), 0.0)
820
+
821
+ try:
822
+ recon_audio: Tensor = cast('Callable[..., Tensor]', torch.istft)(stft_repr, **self.stft_kwargs, window=stft_window, return_complex=False, length=istft_length) # pyright: ignore[reportUnknownMemberType]
823
+ except RuntimeError:
824
+ recon_audio = cast('Callable[..., Tensor]', torch.istft)(stft_repr.cpu(), **self.stft_kwargs, window=stft_window.cpu(), return_complex=False, length=istft_length).to(raw_audio.device) # pyright: ignore[reportUnknownMemberType]
825
+
826
+ recon_audio = rearrange(recon_audio, '(b n s) t -> b n s t', b=batch, s=self.audio_channels, n=self.num_stems)
827
+
828
+ if exists(target):
829
+ return lossComputation(recon_audio=recon_audio, target=target, stem_ids=stem_ids, multi_stft=self.multi_stft, return_loss_breakdown=return_loss_breakdown)
830
+ return recon_audio