Giter Club home page Giter Club logo

julius's Introduction

Julius, fast PyTorch based DSP for audio and 1D signals

linter badge tests badge cov badge

Julius contains different Digital Signal Processing algorithms implemented with PyTorch, so that they are differentiable and available on CUDA. Note that all the modules implemented here can be used with TorchScript.

For now, I have implemented:

Along that, you might found useful utilities in:

Representation of the convolutions filters used for the efficient resampling.

News

  • 19/09/2022: julius 0.2.7 released:: fixed ONNX compat (thanks @iver56). I know I missed the 0.2.6 one...
  • 28/07/2021: julius 0.2.5 released:: support for setting a custom output length when resampling.
  • 22/06/2021: julius 0.2.4 released:: adding highpass and band passfilters. Extra linting and type checking of the code. New unfold implemention, up to x6 faster FFT convolutions and more efficient memory usage.
  • 26/01/2021: julius 0.2.2 released: fixing normalization of filters in lowpass and resample to avoid very low frequencies to be leaked. Switch from zero padding to replicate padding (uses first/last value instead of 0) to avoid discontinuities with strong artifacts.
  • 20/01/2021: julius implementation of resampling is now officially part of Torchaudio.

Installation

julius requires python 3.6. To install:

pip3 install -U julius

Usage

See the Julius documentation for the usage of Julius. Hereafter you will find a few examples to get you quickly started:

import julius
import torch

signal = torch.randn(6, 4, 1024)
# Resample from a sample rate of 100 to 70. The old and new sample rate must be integers,
# and resampling will be fast if they form an irreductible fraction with small numerator
# and denominator (here 10 and 7). Any shape is supported, last dim is time.
resampled_signal = julius.resample_frac(signal, 100, 70)

# Low pass filter with a `0.1 * sample_rate` cutoff frequency.
low_freqs = julius.lowpass_filter(signal, 0.1)

# Fast convolutions with FFT, useful for large kernels
conv = julius.FFTConv1d(4, 10, 512)
convolved = conv(signal)

# Decomposition over frequency bands in the Waveform domain
bands = julius.split_bands(signal, n_bands=10, sample_rate=100)
# Decomposition with n_bands frequency bands evenly spaced in mel space.
# Input shape can be `[*, T]`, output will be `[n_bands, *, T]`.
random_eq = (torch.rand(10, 1, 1, 1) * bands).sum(0)

Algorithms

Resample

This is an implementation of the sinc resample algorithm by Julius O. Smith. It is the same algorithm than the one used in resampy but to run efficiently on GPU it is limited to fractional changes of the sample rate. It will be fast if the old and new sample rate are small after dividing them by their GCD. For instance going from a sample rate of 2000 to 3000 (2, 3 after removing the GCD) will be extremely fast, while going from 20001 to 30001 will not. Julius resampling is faster than resampy even on CPU, and when running on GPU it makes resampling a completely negligible part of your pipeline (except of course for weird cases like going from a sample rate of 20001 to 30001).

FFTConv1d

Computing convolutions with very large kernels (>= 128) and a stride of 1 can be much faster using FFT. This implements the same API as torch.nn.Conv1d and torch.nn.functional.conv1d but with a FFT backend. Dilation and groups are not supported. FFTConv will be faster on CPU even for relatively small tensors (a few dozen channels, kernel size of 128). On CUDA, due to the higher parallelism, regular convolution can be faster in many cases, but for kernel sizes above 128, for a large number of channels or batch size, FFTConv1d will eventually be faster (basically when you no longer have idle cores that can hide the true complexity of the operation).

LowPass

Classical Finite Impulse Reponse windowed sinc lowpass filter. It will use FFT convolutions automatically if the filter size is large enough. This is the basic block from which you can build high pass and band pass filters (see julius.filters).

Bands

Decomposition of a signal over frequency bands in the waveform domain. This can be useful for instance to perform parametric EQ (see Usage above).

Benchmarks

You can find speed tests (and comparisons to reference implementations) on the benchmark. The CPU benchmarks are run on a Mac Book Pro 2020, with a 2.4 GHz 8-core intel CPU i9. The GPUs benchmark are run on Nvidia V100 with 16GB of memory. We also compare the validity of our implementations, as compared to reference ones like resampy or torch.nn.Conv1d.

Running tests

Clone this repository, then

pip3 install .[dev]'
python3 tests.py

To run the benchmarks:

pip3 install .[dev]'
python3 -m bench.gen

License

julius is released under the MIT license.

Thanks

This package is named in the honor of Julius O. Smith, whose books and website were a gold mine of information for me to learn about DSP. Go checkout his website if you want to learn more about DSP.

julius's People

Contributors

adefossez avatar iver56 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

julius's Issues

Time spent on repeated kernel construction

First, let me say THANK YOU for reducing the time spent resampling ~ 30x in my particular application, compared to using resampy with the kaiser_fast mode. And thereby also reducing total application runtime ~ 50%! <3

After swapping resampy for julius my application spent most of its time in _init_kernels because I was using the resample_frac interface. I've worked around this by caching ResampleFrac instances:

def resample(wav_arr, from_sr, to_sr, _resamplers={}):
    try:
        resampler = _resamplers[(from_sr, to_sr)]
    except KeyError:
        resampler = _resamplers[(from_sr, to_sr)] = julius.resample.ResampleFrac(from_sr, to_sr)
    with torch.no_grad():
        return resampler(torch.from_numpy(wav_arr)).numpy()

I wonder what you think about caching those instances (or maybe only the kernels) by default, OR adding a hint to the documentation that you might want to use the ResampleFrac interface if you're repeatedly resampling between the same sample rates.

torchaudio

Nice work.
But it seems there're already resample implemented by conv1d in pytorch's official torchaudio
Is there any necessary to implement it again?

Question about the window function

Hi @adefossez ,
First of all, thanks for your wonderful implementation! I have started to use it a lot recently, it really saves my time.
Also, your ResampleFrac module support torch.jit which is another great thing to admire.

Although the speed of resampling is excellent, I have noticed that the quality of julius isn't as good as other famous packages (like resampy). From @jonashaag's notebook, we can see that julius frequency response main lobe is wider than others, which I think is a result from the window function.

Current julius window function is fixed to use hann window:

julius/julius/resample.py

Lines 105 to 106 in 29c6aad

window = torch.cos(t/self.zeros/2)**2
kernel = sinc(t) * window

If we add an option of window functions, user can have more choice to control the quality besides raising number of zeros.

BTW: As a side note, can I ask why not using fft_conv in ResampleFrac? Sinc interpolation use very large kernel, and I think it suites perfectly to use FFT to accelerate sinc interpolation.

cuFFT error: CUFFT_EXEC_FAILED

Hi
Iโ€™m getting a RuntimeError: cuFFT error: CUFFT_EXEC_FAILED, when I try to use the bandpass_filter with fft=True (a single GPU)
The last function called is new_fft.irfft
Any idea what could be the root cause?
Thanks

split_bands doesn't print in IPython notebook with a numpy array in cutoffs

Small issue in SplitBands.

Steps to reproduce:

Run the following in a Jupyter notebook:

import julius

split_bands = julius.SplitBands(1, 16)
print(split_bands)

split_bands = julius.SplitBands(1, cutoffs=[0.1, 0.25])
print(split_bands)

split_bands = julius.SplitBands(1, cutoffs=np.array([0.1, 0.25]))
print(split_bands)

This has the following output:

SplitBands(sample_rate=1,n_bands=16)
SplitBands(sample_rate=1,cutoffs=[0.1, 0.25])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-93-5b31698bfbfc> in <module>
      8 
      9 split_bands = julius.SplitBands(1, cutoffs=np.array([0.1, 0.25]))
---> 10 print(split_bands)

/home/admin/miniconda3/envs/venv/lib/python3.8/site-packages/julius/bands.py in __repr__(self)
    100 
    101     def __repr__(self):
--> 102         return simple_repr(self, overrides={"cutoffs": self._cutoffs})
    103 
    104 

/home/admin/miniconda3/envs/venv/lib/python3.8/site-packages/julius/utils.py in simple_repr(obj, attrs, overrides)
     30         if attr in params:
     31             param = params[attr]
---> 32             if param.default is inspect._empty or value != param.default:
     33                 display = True
     34         else:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Probably just need a tolist if it's a numpy array in simple_repr.

Anyway, great project! I've enjoyed using it.

Add convenience function for high pass filter

As you say in the code, a high pass filter can be implemented by using a low pass filter and doing some subtraction. A convenience function that does this would be nice :) This makes it easier for developers with less DSP knowledge to apply high pass filtering

Pytorch version

If I want to install julius, what is the minimum version of torch I should use? Julius seems to be incompatible with torch 1.5.1.

Bandpass filter

Do we have bandpass filter also available ?

def apply_bandpass(x, lf=20, hf=512, order=8, sr=2048):
    sos = signal.butter(order, [lf, hf], btype="bandpass", output="sos", fs=sr)
    normalization = np.sqrt((hf - lf) / (sr / 2))
    return signal.sosfiltfilt(sos, x) / normalization

Allow specifying expected output length when resampling

Hi Alexandre :)

Consider this scenario:

We have a machine learning model that takes in and outputs audio at a high sample rate. For some reasons (amongst other things execution time) the model uses an internal sample rate that is lower than the input-output. The output shape is expected to be the same as the input shape.

class ResampleWrapper(nn.Module):
    """
    This class downsamples audio before it's passed to the audio denoiser model,
    and upsamples the audio back to the original sample rate before returning.
    """

    def __init__(
        self,
        model: nn.Module,
        input_sample_rate: int = 48_000,
        internal_sample_rate: int = 32_000,
    ):
        super().__init__()
        self.model = model
        self.input_sample_rate = input_sample_rate
        self.internal_sample_rate = internal_sample_rate

        self.downsampler = ResampleFrac(
            self.input_sample_rate, self.internal_sample_rate
        )
        self.upsampler = ResampleFrac(self.internal_sample_rate, self.input_sample_rate)

    def forward(self, x):
        """
        :param x: tensor with shape (batch_size, num_channels, num_samples)
        :return: tensor with shape (batch_size, num_channels, num_samples)
        """
        x = self.downsampler(x)
        x = self.model(x)
        x = self.upsampler(x)
        return x

Depending on the exact length of the input, downsampling and then upsampling will often give an output that is off by one sample in length.

In librosa this kind of issue can be solved by setting the fix parameter or by using fix_length manually.

I imagine that julius.ResampleFrac could provide a parameter called something like expected_length in its forward function that customizes the slice end offset in the end so that the result has the given length ๐Ÿ˜„

Would you like a pull request that adds this feature?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.