nnAudio Documentation

repository·master·Indexed 22 days ago

https://github.com/kinwaicheuk/nnaudio

A PyTorch-based audio processing toolbox that uses 1D convolutional neural networks for audio-to-spectrogram conversions. It enables differentiable and trainable audio features, such as CQT, VQT, and Mel spectrograms, allowing for on-the-fly spectrogram generation and GPU acceleration directly within neural network training pipelines.

Tokens
3.7K
Snippets
9
Records
14
Agent score
78%

What's inside nnAudio

  1. Overview of nnAudio capabilities

    master

    nnAudio is an audio processing toolbox that uses PyTorch convolutional neural networks (1D CNNs) as its backend. This approach allows for:

    • On-the-fly spectrogram generation during neural network training.
    • Trainable Fourier kernels (e.g., CQT kernels), which is not possible with standard non-neural network approaches.
    • GPU support for high-performance audio-to-spectrogram conversion.
    • Cross-platform compatibility, as it relies on PyTorch rather than external dependencies like sox (which can make torchaudio difficult to install on Windows).
  2. Use nnAudio.features for spectrogram generation

    master

    In recent versions, the nnAudio.Spectrogram module is being replaced by the nnAudio.features module. Users should transition to using nnAudio.features for feature extraction tasks.

    Available features include:

    • nnAudio.features.STFT
    • nnAudio.features.vqt.VQT (available in current versions)
  3. Make Fourier bases and Mel filter banks trainable

    master

    nnAudio allows you to make the underlying kernels/bases trainable during backpropagation by setting specific arguments in the feature layers:

    • STFT: Set trainable=True in nnAudio.features.stft.STFT to make the Fourier basis trainable.
    • MelSpectrogram: Set trainable_STFT=True to make the Fourier basis trainable, and trainable_mel=True (note: the docs mention trainable_mel=False in a context that implies it controls the Mel filter banks) to make Mel filter banks trainable.
    • CQT: The trainable argument is also available in nnAudio.features.cqt.CQT.
  4. Choose between different CQT versions

    master

    nnAudio provides several versions of the Constant-Q Transform (CQT) to balance smoothness and speed:

    • CQT1992: Smoother results, but may exhibit artifacts due to the downsampling approach used in the original 1992 algorithm.
    • CQT2010: Similar to the 1992 version, uses a downsampling approach and may show similar artifacts.
    • CQT1992v2 and CQT2010v2: These versions are computed directly in the time domain without transforming both input waveforms and kernels to the frequency domain. They are faster than the original 1992 version.

    Default: The default CQT in nnAudio is CQT1992v2.

    To select a specific version, refer to the CQT API documentation.

  5. Integrate nnAudio for on-the-fly audio processing in neural networks

    master

    You can integrate nnAudio layers directly into a torch.nn.Module. This allows your model to accept raw waveforms as input and perform spectrogram extraction automatically during the forward pass. This is useful for end-to-end trainable audio models.

    Example of a model that performs on-the-fly STFT extraction followed by CNN layers:

    from nnAudio import features
    import torch
    import torch.nn as nn    
    
    class Model(torch.nn.Module):
        def __init__(self, n_fft, output_dim):
            super().__init__()
            self.epsilon = 1e-10
            # Getting Mel Spectrogram on the fly
            self.spec_layer = features.STFT(n_fft=n_fft, freq_bins=None,
                                               hop_length=512, window='hann', 
                                               freq_scale='no', center=True,
                                               pad_mode='reflect', fmin=50,
                                               fmax=6000, sr=22050, trainable=False,
                                               output_format='Magnitude')
            self.n_bins = n_fft // 2
    
            # Creating CNN Layers
            self.CNN_freq_kernel_size = (128, 1)
            self.CNN_freq_kernel_stride = (2, 1)
            k_out = 128
            k2_out = 256
            self.CNN_freq = nn.Conv2d(1, k_out, 
                                        kernel_size=self.CNN_freq_kernel_size, 
                                        stride=self.CNN_freq_kernel_stride)
            self.CNN_time = nn.Conv2d(k_out, k2_out, 
                                        kernel_size=(1, 3), stride=(1, 1))
    
            self.region_v = 1 + (self.n_bins - self.CNN_freq_kernel_size[0]) // self.CNN_freq_kernel_stride[0]
            self.linear = torch.nn.Linear(k2_out * self.region_v, output_dim, bias=False)
    
        def forward(self, x):
            z = self.spec_layer(x)
            z = torch.log(z + self.epsilon)
            z2 = torch.relu(self.CNN_freq(z.unsqueeze(1)))
            z3 = torch.relu(self.CNN_time(z2)).mean(-1)
            y = self.linear(torch.relu(torch.flatten(z3, 1)))
            return torch.sigmoid(y)
    
    # Usage: model takes waveforms directly
    model = Model(n_fft=1024, output_dim=10)
    waveforms = torch.randn(4, 44100)
    output = model(waveforms) # automatically converts waveforms into spectrograms
  6. Quick Start with nnAudio

    master

    nnAudio is an audio processing toolbox built on PyTorch convolutional neural networks. It allows for on-the-fly spectrogram generation during neural network training, enabling the Fourier kernels (e.g., CQT kernels) to be trained as part of the model.

    To use nnAudio, load your audio as a PyTorch tensor, initialize a feature layer from nnAudio.features, and pass the waveform through the layer to obtain the spectrogram.

    from nnAudio import features
    from scipy.io import wavfile
    import torch
    
    # 1. Loading your audio
    sr, song = wavfile.read('./Bach.wav') 
    
    # 2. Converting Stereo to Mono
    x = song.mean(1) 
    
    # 3. Casting the array into a PyTorch Tensor
    x = torch.tensor(x, device='cuda:0').float() 
    
    # 4. Initializing the model (e.g., STFT)
    spec_layer = features.STFT(n_fft=2048, freq_bins=None, hop_length=512, 
                              window='hann', freq_scale='linear', center=True, 
                              pad_mode='reflect', fmin=50, fmax=11025, sr=sr)
    
    # 5. Feed-forward your waveform to get the spectrogram
    spec = spec_layer(x)
  7. nnAudio dependencies and requirements

    master

    To use nnAudio, ensure your environment meets the following requirements:

    • Python: >= 3.6
    • PyTorch: >= 1.6.0 (Note: Griffin-Lim is only available in versions 1.6.0 and later)
    • NumPy: >= 1.14.5
    • SciPy: >= 1.2.0

    Note: While nnAudio uses logic from librosa.filters.mel, it does not require librosa to be installed as the necessary functions are bundled within the package.

  8. Install nnAudio via PyPI or GitHub

    master

    You can install nnAudio using pip.

    Via PyPI:

    pip install nnAudio==x.x.x

    (Replace x.x.x with your desired version number).

    Via GitHub (Latest version):

    pip install git+https://github.com/KinWaiCheuk/nnAudio.git#subdirectory=Installation

    Manual Installation from GitHub:

    1. Clone the repository: git clone https://github.com/KinWaiCheuk/nnAudio.git <path>
    2. Navigate to the installation directory: cd Installation
    3. Run the setup script: python setup.py install

    Requirements:

    • Python >= 3.6
    • Numpy >= 1.14.5
    • Scipy >= 1.2.0
    • PyTorch >= 1.6.0 (Note: Griffin-Lim requires PyTorch 1.6.0+)
    • librosa (Optional: nnAudio includes its own implementation of the mel function to avoid a hard dependency).
    pip install git+https://github.com/KinWaiCheuk/nnAudio.git#subdirectory=Installation
  9. Move nnAudio layers to GPU

    master

    Since nnAudio layers are nn.Modules, you can move them to a GPU using the standard PyTorch .to(device) method.

    If using a standalone layer:

    spec_layer = features.STFT().to(device)

    If the layer is part of a larger model, simply move the entire model to the device:

    net = Model()
    net.to(device)
  10. Install nnAudio

    master

    You can install nnAudio via pip using either the official release or directly from the GitHub repository.

    Note: A new version of nnAudio is being actively maintained at AMAAI-Lab/nnAudio2. Users may want to consider the newer version for active maintenance.

    # Install from GitHub
    pip install git+https://github.com/KinWaiCheuk/nnAudio.git#subdirectory=Installation
    
    # Or install a specific version via PyPI
    pip install nnaudio==0.3.4
  11. Use nnAudio for standalone spectrogram extraction

    master

    To use nnAudio as a standalone tool, define a spectrogram layer (e.g., features.STFT) just like a PyTorch neural network layer. The input to the layer must be a PyTorch Tensor with the shape (batch, len_audio).

    Example of extracting an STFT spectrogram from a waveform:

    from nnAudio import features
    from scipy.io import wavfile
    import torch
    
    # Loading your audio
    sr, song = wavfile.read('./Bach.wav') 
    # Converting Stereo to Mono
    x = song.mean(1) 
    # Casting the array into a PyTorch Tensor
    x = torch.tensor(x, device='cuda:0').float() 
    
    # Initializing the model
    spec_layer = features.STFT(n_fft=2048, freq_bins=None, hop_length=512, 
                                  window='hann', freq_scale='linear', center=True, pad_mode='reflect', 
                                  fmin=50, fmax=11025, sr=sr)
    
    # Feed-forward your waveform to get the spectrogram
    spec = spec_layer(x)