To combine Test Time Augmentation (TTA) techniques—specifically, shifting, phase inversion, and stereo inversion—in your demix_wrapper function, you can modify the function to apply these transformations systematically across different passes. Here's how you can achieve this:
-
Shifting (bigshifts): The existing functionality where the mix is shifted by a certain number of samples.
-
Phase Inversion: For one of the passes (e.g., the first pass), invert the phase by multiplying the mix by -1.
-
Stereo Inversion: For the remaining passes, invert the stereo channels by swapping the left and right channels.
After applying these transformations, ensure that you reverse them before averaging the results to maintain the correct audio orientation.
Here's the modified version of your demix_wrapper function incorporating these enhancements:
import numpy as np
from typing import Dict
from numpy.typing import NDArray
def demix_wrapper(
config,
model,
mix: NDArray,
device,
pbar: bool = False,
model_type: str = None,
bigshifts: int = 1
) -> Dict[str, NDArray]:
"""
Perform source separation with Test Time Augmentation (TTA) by applying shifting,
phase inversion, and stereo inversion.
Args:
config: Configuration object containing training details.
model: The source separation model.
mix (NDArray): Input mixed audio array with shape (channels, samples).
device: Computation device (e.g., CPU or GPU).
pbar (bool, optional): Whether to display a progress bar. Defaults to False.
model_type (str, optional): Type of model to use. Defaults to None.
bigshifts (int, optional): Number of shift passes. Defaults to 1.
Returns:
Dict[str, NDArray]: Averaged separated sources for each instrument.
"""
if bigshifts <= 0:
bigshifts = 1
channels, total_samples = mix.shape
shift_in_samples = total_samples // bigshifts
shifts = [x * shift_in_samples for x in range(bigshifts)]
# Initialize a dictionary to store results for each instrument
results = {instrument: [] for instrument in config.training.instruments}
for i, shift in enumerate(shifts):
print(f"Processing shift {i + 1} of {len(shifts)}")
# Shift the mix circularly
shifted_mix = np.concatenate((mix[:, -shift:], mix[:, :-shift]), axis=-1)
# Apply TTA transformations based on the pass index
if i == 0:
# Phase inversion for the first pass
transformed_mix = -shifted_mix
reverse_transform = lambda x: -x # Function to reverse phase inversion
else:
# Stereo inversion for other passes
if channels == 2:
transformed_mix = shifted_mix[[1, 0], :] # Swap left and right channels
reverse_transform = lambda x: x[[1, 0], :] # Swap back to original
else:
# If not stereo, you might define another inversion or skip
transformed_mix = shifted_mix
reverse_transform = lambda x: x
# Perform source separation on the transformed mix
sources = demix_track(config, model, transformed_mix, device, pbar)
# Reverse the TTA transformations on each separated source and unshift
for instrument, source in sources.items():
# Reverse the shift
unshifted_source = np.concatenate((source[:, -shift:], source[:, :-shift]), axis=-1)
# Reverse the applied transformation
unshifted_source = reverse_transform(unshifted_source)
# Append the result for averaging later
results[instrument].append(unshifted_source)
# Averaging the results across all TTA passes
averaged_results = {}
for instrument, sources in results.items():
# Stack along a new axis and compute the mean
stacked_sources = np.stack(sources, axis=0)
averaged_source = np.mean(stacked_sources, axis=0)
averaged_results[instrument] = averaged_source
return averaged_results
Detailed Explanation:
-
Shifting Mechanism:
- Shift Calculation: The number of samples to shift (
shift_in_samples) is determined by dividing the total number of samples by bigshifts.
- Shifting the Mix: For each shift value in
shifts, the mix is circularly shifted using np.concatenate.
-
Applying TTA Transformations:
- Phase Inversion:
- Applied only to the first pass (
i == 0).
- The entire mix is multiplied by
-1 to invert the phase.
- A
reverse_transform lambda function is defined to revert this inversion after source separation.
- Stereo Inversion:
- Applied to all subsequent passes (
i > 0).
- Only applicable if the mix is stereo (
channels == 2).
- The left and right channels are swapped.
- A corresponding
reverse_transform is defined to swap them back after separation.
- Non-Stereo Cases:
- If the mix isn't stereo, you can decide to skip stereo inversion or define another type of inversion based on your requirements.
-
Reversing Transformations After Separation:
- After source separation with
demix_track, each separated source is:
- Unshifted: The reverse shift is applied to align it back to the original timing.
- Transformation Reversal: The previously applied transformation (phase or stereo inversion) is reversed using the
reverse_transform function.
-
Averaging Results:
- For each instrument, all the reversed and unshifted sources from different TTA passes are stacked and averaged to produce the final separated source.
Notes:
-
Flexibility: This implementation assumes that mix is a 2-channel (stereo) audio signal. If you have multi-channel audio (more than 2 channels), you'll need to adjust the stereo inversion logic accordingly.
-
Reverse Transformation Functions: By using lambda functions (reverse_transform), the code cleanly separates the transformation and its reversal, making it easier to manage and extend if more transformations are added in the future.
-
Error Handling: You might want to add error handling to manage cases where the mix isn't stereo or doesn't meet expected dimensions.
Example Usage:
# Assuming you have the necessary objects and data
averaged_sources = demix_wrapper(
config=config,
model=model,
mix=mixed_audio_np_array, # Shape: (2, num_samples)
device='cuda',
pbar=True,
model_type='your_model_type',
bigshifts=3 # For example, applying 1 phase inversion and 2 stereo inversions
)
# `averaged_sources` will be a dictionary with averaged separated sources for each instrument
This approach ensures that your model benefits from the robustness introduced by multiple TTA techniques, potentially leading to better separation performance.