├── requirements.txt ├── _config.yml ├── MANIFEST.in ├── .gitignore ├── cached_conv ├── test_script.py ├── test_conv_t.py ├── test_conv.py ├── test_sequential.py ├── __init__.py ├── test_align_branches.py └── convs.py ├── setup.py ├── .github └── workflows │ └── python-publish.yaml ├── README.md └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | torch 2 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include requirements.txt 2 | include README.md -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *pycache* 2 | *pytest* 3 | *build* 4 | *externals* 5 | *egg-info* 6 | dist/* 7 | .vscode 8 | *DS_Store -------------------------------------------------------------------------------- /cached_conv/test_script.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | 4 | import cached_conv as cc 5 | 6 | torch.set_grad_enabled(False) 7 | 8 | model_list = [ 9 | (cc.CachedConv1d, { 10 | "in_channels": 16, 11 | "out_channels": 16, 12 | "kernel_size": 3, 13 | "padding": cc.get_padding(3) 14 | }), 15 | (cc.CachedConvTranspose1d, { 16 | "in_channels": 16, 17 | "out_channels": 16, 18 | "kernel_size": 4, 19 | "stride": 2, 20 | "padding": 1 21 | }), 22 | ] 23 | 24 | 25 | @pytest.mark.parametrize("model", model_list) 26 | def test_script(model): 27 | 28 | model, hp = model[0](**model[1]), model[1] 29 | x = torch.randn(1, hp["in_channels"], 2**14) 30 | model(x) 31 | script = torch.jit.script(model) -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | import os 3 | 4 | with open("README.md", "r") as readme: 5 | readme = readme.read() 6 | 7 | with open("requirements.txt", "r") as requirements: 8 | requirements = requirements.read() 9 | 10 | setuptools.setup( 11 | name="cached_conv", 12 | version=os.environ["CACHED_CONV_VERSION"], 13 | author="Antoine CAILLON", 14 | author_email="caillon@ircam.fr", 15 | description="Tools allowing to use neural network inside realtime apps.", 16 | long_description=readme, 17 | long_description_content_type="text/markdown", 18 | packages=setuptools.find_packages(), 19 | classifiers=[ 20 | "Programming Language :: Python :: 3", 21 | "License :: OSI Approved :: MIT License", 22 | "Operating System :: OS Independent", 23 | ], 24 | install_requires=requirements.split("\n"), 25 | python_requires='>=3.7', 26 | ) 27 | -------------------------------------------------------------------------------- /cached_conv/test_conv_t.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | import torch.nn as nn 4 | 5 | import cached_conv as cc 6 | 7 | hparams_list = [ 8 | { 9 | "in_channels": 16, 10 | "out_channels": 16, 11 | "kernel_size": 4, 12 | "stride": 2, 13 | "padding": 1 14 | }, 15 | { 16 | "in_channels": 16, 17 | "out_channels": 16, 18 | "kernel_size": 8, 19 | "stride": 4, 20 | "padding": 2 21 | }, 22 | { 23 | "in_channels": 16, 24 | "out_channels": 16, 25 | "kernel_size": 12, 26 | "stride": 4, 27 | "padding": 4 28 | }, 29 | ] 30 | 31 | 32 | @pytest.mark.parametrize("hparams", hparams_list) 33 | def test_conv_t(hparams): 34 | model_constructor = lambda: cc.ConvTranspose1d(**hparams) 35 | input_tensor = torch.randn(1, hparams["out_channels"], 2**14) 36 | assert cc.test_equal(model_constructor, input_tensor) 37 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yaml: -------------------------------------------------------------------------------- 1 | name: Upload Python Package 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | 8 | permissions: 9 | contents: read 10 | 11 | jobs: 12 | deploy: 13 | 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | - name: Set up Python 19 | uses: actions/setup-python@v3 20 | with: 21 | python-version: '3.10' 22 | - name: Install dependencies 23 | run: | 24 | python -m pip install torch --index-url https://download.pytorch.org/whl/cpu 25 | python -m pip install --upgrade pip setuptools wheel build pytest 26 | python -m pip install -r requirements.txt 27 | - name: Run tests 28 | run: | 29 | pytest 30 | - name: Build package 31 | run: CACHED_CONV_VERSION=${{ github.ref_name }} python -m build 32 | - name: Publish package 33 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 34 | with: 35 | user: __token__ 36 | password: ${{ secrets.PYPI_TOKEN }} -------------------------------------------------------------------------------- /cached_conv/test_conv.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | 4 | import cached_conv as cc 5 | 6 | hparams_list = [{ 7 | "in_channels": 16, 8 | "out_channels": 16, 9 | "kernel_size": 3, 10 | "padding": cc.get_padding(3) 11 | }, { 12 | "in_channels": 16, 13 | "out_channels": 16, 14 | "kernel_size": 5, 15 | "padding": cc.get_padding(5) 16 | }, { 17 | "in_channels": 16, 18 | "out_channels": 16, 19 | "kernel_size": 3, 20 | "stride": 2, 21 | "padding": cc.get_padding(3, 2) 22 | }, { 23 | "in_channels": 16, 24 | "out_channels": 16, 25 | "kernel_size": 7, 26 | "stride": 2, 27 | "padding": cc.get_padding(7, 2) 28 | }, { 29 | "in_channels": 16, 30 | "out_channels": 16, 31 | "kernel_size": 7, 32 | "stride": 4, 33 | "padding": cc.get_padding(7, 4) 34 | }] 35 | 36 | 37 | @pytest.mark.parametrize("hparams", hparams_list) 38 | def test_conv(hparams): 39 | model_constructor = lambda: cc.Conv1d(**hparams) 40 | input_tensor = torch.randn(1, hparams["in_channels"], 2**14) 41 | assert cc.test_equal(model_constructor, input_tensor) 42 | -------------------------------------------------------------------------------- /cached_conv/test_sequential.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | 4 | import cached_conv as cc 5 | 6 | hparams_list = [{ 7 | "dim": 1, 8 | "kernels": [3, 5, 7, 9], 9 | "strides": [1, 1, 1, 1] 10 | }, { 11 | "dim": 1, 12 | "kernels": [3, 5, 7, 9], 13 | "strides": [2, 1, 1, 1] 14 | }, { 15 | "dim": 1, 16 | "kernels": [3, 5, 7, 9], 17 | "strides": [1, 2, 1, 1] 18 | }, { 19 | "dim": 1, 20 | "kernels": [3, 5, 7, 9], 21 | "strides": [1, 1, 2, 1] 22 | }, { 23 | "dim": 1, 24 | "kernels": [3, 3, 3, 3], 25 | "strides": [2, 1, 2, 1] 26 | }] 27 | 28 | 29 | def build_model(dim, kernels, strides): 30 | layers = [] 31 | cum_delay = 0 32 | for k, s in zip(kernels, strides): 33 | layers.append( 34 | cc.Conv1d( 35 | dim, 36 | dim, 37 | k, 38 | stride=s, 39 | padding=cc.get_padding(k, s), 40 | cumulative_delay=cum_delay, 41 | )) 42 | cum_delay = layers[-1].cumulative_delay 43 | 44 | model = cc.CachedSequential(*layers) 45 | return model 46 | 47 | 48 | @pytest.mark.parametrize("hparams", hparams_list) 49 | def test_sequential(hparams): 50 | model_constructor = lambda: build_model(**hparams) 51 | input_tensor = torch.randn(1, hparams["dim"], 2**14) 52 | assert cc.test_equal(model_constructor, input_tensor) 53 | -------------------------------------------------------------------------------- /cached_conv/__init__.py: -------------------------------------------------------------------------------- 1 | from warnings import warn 2 | 3 | import torch 4 | 5 | from .convs import MAX_BATCH_SIZE 6 | from .convs import AlignBranches as _AlignBranches 7 | from .convs import (Branches, CachedConv1d, CachedConvTranspose1d, 8 | CachedPadding1d, CachedSequential) 9 | from .convs import Conv1d as _Conv1d 10 | from .convs import ConvTranspose1d as _ConvTranspose1d 11 | from .convs import get_padding 12 | 13 | USE_BUFFER_CONV = False 14 | 15 | 16 | def chunk_process(f, x, N): 17 | x = torch.split(x, x.shape[-1] // N, -1) 18 | y = torch.cat([f(_x) for _x in x], -1) 19 | return y 20 | 21 | 22 | def use_buffer_conv(state: bool): 23 | warn( 24 | "use_buffer_conv is deprecated, use use_cached_conv instead", 25 | DeprecationWarning, 26 | stacklevel=2, 27 | ) 28 | use_cached_conv(state) 29 | 30 | 31 | def use_cached_conv(state: bool): 32 | global USE_BUFFER_CONV 33 | USE_BUFFER_CONV = state 34 | 35 | 36 | def Conv1d(*args, **kwargs): 37 | if USE_BUFFER_CONV: 38 | return CachedConv1d(*args, **kwargs) 39 | else: 40 | return _Conv1d(*args, **kwargs) 41 | 42 | 43 | def ConvTranspose1d(*args, **kwargs): 44 | if USE_BUFFER_CONV: 45 | return CachedConvTranspose1d(*args, **kwargs) 46 | else: 47 | return _ConvTranspose1d(*args, **kwargs) 48 | 49 | 50 | def AlignBranches(*args, **kwargs): 51 | if USE_BUFFER_CONV: 52 | return _AlignBranches(*args, **kwargs) 53 | else: 54 | return Branches(*args, **kwargs) 55 | 56 | 57 | def test_equal(model_constructor, input_tensor, crop=True): 58 | initial_state = USE_BUFFER_CONV 59 | 60 | use_cached_conv(False) 61 | model = model_constructor() 62 | use_cached_conv(True) 63 | cmodel = model_constructor() 64 | 65 | for p1, p2 in zip(model.parameters(), cmodel.parameters()): 66 | p2.data.copy_(p1.data) 67 | 68 | y = model(input_tensor)[..., :-cmodel.cumulative_delay] 69 | cy = chunk_process(lambda x: cmodel(x), input_tensor, 70 | 4)[..., cmodel.cumulative_delay:] 71 | 72 | if crop: 73 | cd = cmodel.cumulative_delay 74 | y = y[..., cd:-cd] 75 | cy = cy[..., cd:-cd] 76 | 77 | use_cached_conv(initial_state) 78 | return torch.allclose(y, cy, 1e-4, 1e-4) 79 | -------------------------------------------------------------------------------- /cached_conv/test_align_branches.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | import pytest 4 | import torch 5 | import torch.nn as nn 6 | 7 | import cached_conv as cc 8 | 9 | 10 | def test_residual(): 11 | cc.use_cached_conv(False) 12 | conv = cc.Conv1d(1, 1, 5, padding=cc.get_padding(5)) 13 | model = cc.AlignBranches( 14 | conv, 15 | nn.Identity(), 16 | delays=[conv.cumulative_delay, 0], 17 | ) 18 | 19 | cc.use_cached_conv(True) 20 | cconv = cc.Conv1d(1, 1, 5, padding=cc.get_padding(5)) 21 | cmodel = cc.AlignBranches( 22 | cconv, 23 | nn.Identity(), 24 | delays=[cconv.cumulative_delay, 0], 25 | ) 26 | 27 | for p1, p2 in zip(model.parameters(), cmodel.parameters()): 28 | p2.data.copy_(p1.data) 29 | 30 | x = torch.randn(1, 1, 2**14) 31 | 32 | y = sum(model(x))[..., :-cmodel.cumulative_delay] 33 | cy = cc.chunk_process( 34 | lambda x: sum(cmodel(x)), 35 | x, 36 | 4, 37 | )[..., cmodel.cumulative_delay:] 38 | 39 | assert torch.allclose(y, cy, 1e-3, 1e-3) 40 | 41 | 42 | def test_parallel(): 43 | cc.use_cached_conv(False) 44 | 45 | b1 = cc.Conv1d(1, 1, 5, padding=cc.get_padding(5)) 46 | b2 = cc.Conv1d(1, 1, 3, padding=cc.get_padding(3)) 47 | model = cc.AlignBranches(b1, b2) 48 | 49 | cc.use_cached_conv(True) 50 | 51 | cb1 = cc.Conv1d(1, 1, 5, padding=cc.get_padding(5)) 52 | cb2 = cc.Conv1d(1, 1, 3, padding=cc.get_padding(3)) 53 | cmodel = cc.AlignBranches(cb1, cb2) 54 | 55 | for p1, p2 in zip(model.parameters(), cmodel.parameters()): 56 | p2.data.copy_(p1.data) 57 | 58 | x = torch.randn(1, 1, 2**14) 59 | 60 | y = sum(model(x))[..., :-cmodel.cumulative_delay] 61 | cy = cc.chunk_process( 62 | lambda x: sum(cmodel(x)), 63 | x, 64 | 4, 65 | )[..., cmodel.cumulative_delay:] 66 | 67 | assert torch.allclose(y, cy, 1e-3, 1e-3) 68 | 69 | 70 | def test_parallel_stride(): 71 | cc.use_cached_conv(False) 72 | 73 | b1 = cc.Conv1d(1, 1, 5, stride=2, padding=cc.get_padding(5, 2)) 74 | b2 = cc.Conv1d(1, 1, 3, stride=2, padding=cc.get_padding(3, 2)) 75 | model = cc.AlignBranches(b1, b2, stride=.5) 76 | 77 | cc.use_cached_conv(True) 78 | 79 | cb1 = cc.Conv1d(1, 1, 5, stride=2, padding=cc.get_padding(5, 2)) 80 | cb2 = cc.Conv1d(1, 1, 3, stride=2, padding=cc.get_padding(3, 2)) 81 | cmodel = cc.AlignBranches(cb1, cb2, stride=.5) 82 | 83 | for p1, p2 in zip(model.parameters(), cmodel.parameters()): 84 | p2.data.copy_(p1.data) 85 | 86 | x = torch.randn(1, 1, 2**14) 87 | 88 | y = sum(model(x))[..., :-cmodel.cumulative_delay] 89 | cy = cc.chunk_process( 90 | lambda x: sum(cmodel(x)), 91 | x, 92 | 4, 93 | )[..., cmodel.cumulative_delay:] 94 | 95 | assert torch.allclose(y, cy, 1e-3, 1e-3) 96 | 97 | 98 | def test_parallel_transpose(): 99 | cc.use_cached_conv(False) 100 | 101 | b1 = cc.ConvTranspose1d(1, 1, 4, 2, 1) 102 | b2 = cc.ConvTranspose1d(1, 1, 4, 2, 1) 103 | model = cc.AlignBranches(b1, b2, stride=2) 104 | 105 | cc.use_cached_conv(True) 106 | 107 | cb1 = cc.ConvTranspose1d(1, 1, 4, 2, 1) 108 | cb2 = cc.ConvTranspose1d(1, 1, 4, 2, 1) 109 | cmodel = cc.AlignBranches(cb1, cb2, stride=2) 110 | 111 | for p1, p2 in zip(model.parameters(), cmodel.parameters()): 112 | p2.data.copy_(p1.data) 113 | 114 | x = torch.randn(1, 1, 2**14) 115 | 116 | y = sum(model(x))[..., :-cmodel.cumulative_delay] 117 | cy = cc.chunk_process( 118 | lambda x: sum(cmodel(x)), 119 | x, 120 | 4, 121 | )[..., cmodel.cumulative_delay:] 122 | 123 | assert torch.allclose(y, cy, 1e-3, 1e-3) 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Streamable Neural Audio Synthesis With Non-Causal Convolutions 2 | 3 | Deep learning models are mostly used in an offline inference fashion. However, this strongly limits the use of these models inside audio generation setups, as most creative workflows are based on real-time digital signal processing. Although approaches based on recurrent networks can be naturally adapted to this buffer-based computation, the use of convolutions still poses some serious challenges. To tackle this issue, the use of _causal streaming convolutions_ have been proposed. However, this requires specific complexified training and can impact the resulting audio quality. 4 | 5 | In this paper, we introduce a new method allowing to produce _non-causal streaming_ models. This allows to make any convolutional model compatible with real-time buffer-based processing. As our method is based on a post-training reconfiguration of the model, we show that it is able to transform models trained without causal constraints into a streaming model. We show how our method can be adapted to fit complex architectures with parallel branches. To evaluate our method, we apply it on the recent RAVE model, which provides high-quality real-time audio synthesis. We test our approach on multiple music and speech datasets and show that it is faster than overlap-add methods, while having no impact on the generation quality. Finally, we introduce two open-source implementation of our work as Max/MSP and PureData externals, and as a VST audio plugin. This allows to endow traditional digital audio workstations with real-time neural audio synthesis on any laptop CPU. 6 | 7 | ## Streamable RAVE for live audio processing 8 | 9 | Applying our method on the RAVE model allows its use on realtime audio signals, on a wide range of platforms. 10 | 11 | | RAVE x nn~ | embedded RAVE | 12 | | :---------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------: | 13 | | [![RAVE x nn~](http://img.youtube.com/vi/dMZs04TzxUI/mqdefault.jpg)](https://www.youtube.com/watch?v=dMZs04TzxUI) | [![RAVE x nn~](http://img.youtube.com/vi/jAIRf4nGgYI/mqdefault.jpg)](https://www.youtube.com/watch?v=jAIRf4nGgYI) | 14 | 15 | 16 | ## Building a Streamable Convolutional Neural Network 17 | 18 | Let's define a simple autoencoder model 19 | 20 | ```python 21 | import torch 22 | import torch.nn as nn 23 | import cached_conv as cc 24 | 25 | class AutoEncoder(nn.Module): 26 | def __init__(self): 27 | super().__init__() 28 | self.encoder = cc.Sequential( 29 | cc.Conv1d(1, 16, 3, stride=2, padding=1), 30 | nn.ReLU(), 31 | cc.Conv1d(16, 16, 3, stride=2, padding=1), 32 | nn.ReLU(), 33 | cc.Conv1d(16, 16, 3, stride=2, padding=1), 34 | ) 35 | 36 | self.decoder = cc.Sequential( 37 | cc.ConvTranspose1d(16, 16, 4, stride=2, padding=1), 38 | nn.ReLU(), 39 | cc.ConvTranspose1d(16, 16, 4, stride=2, padding=1), 40 | nn.ReLU(), 41 | cc.ConvTranspose1d(16, 1, 4, stride=2, padding=1), 42 | ) 43 | 44 | def forward(self, x): 45 | return self.decoder(self.encoder(x)) 46 | ``` 47 | 48 | Notice that we use convolutions defined by the `cached_conv` package instead of `torch.nn`. If we stop here, we get a model that behaves exactly as its `torch.nn` counterpart. However, if we enable cached convs and then instanciate the model 49 | 50 | ```python 51 | import cached_conv as cc 52 | 53 | cc.use_cached_conv(True) 54 | 55 | model = AutoEncoder() 56 | ``` 57 | 58 | we now have a streamable model, i.e that can work on live streams ! We can now export it as a torchscript model 59 | 60 | ```python 61 | model.register_buffer("forward_params", torch.tensor([1, 1, 1, 1])) 62 | scripted_model = torch.jit.script(model) 63 | torch.jit.save(scripted_model, "exported_model.ts") 64 | ``` 65 | 66 | And load it inside [nn~ for max/msp and PureData](https://github.com/acids-ircam/nn_tilde) for real-time neural audio processing ! Note that nn~ requires a `METHOD_params` buffer in the model for each exported method. It must be a tensor with 4 values: 67 | 68 | - in channel number 69 | - in sampling rate divider (1 = audio rate, 100 = audio rate / 100) 70 | - out channel number 71 | - out sampling rate divider 72 | 73 | We can also export the encode method like this 74 | 75 | ```python 76 | class AutoEncoder(nn.Module): 77 | @torch.jit.export 78 | def encode(self, x): 79 | return self.encoder(x) 80 | 81 | ... 82 | 83 | model = AutoEncoder() 84 | model.register_buffer("encode_params", torch.tensor([1, 1, 16, 8])) 85 | ``` 86 | 87 | ## Realtime applications 88 | 89 | ### [nn~](https://github.com/acids-ircam/nn_tilde) 90 | 91 | The **nn~** external for max/msp and PureData allows to interface pre-trained deep learning models in a graphical way, giving full control to the user on the different dimensions of input and output tensors. 92 | 93 | ![max_msp_screenshot](https://github.com/acids-ircam/RAVE/raw/master/docs/maxmsp_screenshot.png) 94 | 95 | 96 | ### [RAVE vst](https://github.com/acids-ircam/rave_vst) 97 | 98 | The RAVE vst is a VST2/VST3/AU plugin designed to allow the use of the [RAVE model](https://github.com/acids-ircam/RAVE) inside regular digital audio workstations such as Ableton Live or Bitwig Studio. 99 | 100 | ![plugin_screenshot](https://github.com/acids-ircam/rave_vst/blob/main/assets/rave_screenshot_audio_panel.png?raw=true) 101 | 102 | -------------------------------------------------------------------------------- /cached_conv/convs.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | 4 | MAX_BATCH_SIZE = 64 5 | 6 | 7 | def get_padding(kernel_size, stride=1, dilation=1, mode="centered"): 8 | """ 9 | Computes 'same' padding given a kernel size, stride an dilation. 10 | 11 | Parameters 12 | ---------- 13 | 14 | kernel_size: int 15 | kernel_size of the convolution 16 | 17 | stride: int 18 | stride of the convolution 19 | 20 | dilation: int 21 | dilation of the convolution 22 | 23 | mode: str 24 | either "centered", "causal" or "anticausal" 25 | """ 26 | if kernel_size == 1: return (0, 0) 27 | p = (kernel_size - 1) * dilation + 1 28 | half_p = p // 2 29 | if mode == "centered": 30 | p_right = p // 2 31 | p_left = (p - 1) // 2 32 | elif mode == "causal": 33 | p_right = 0 34 | p_left = p // 2 + (p - 1) // 2 35 | elif mode == "anticausal": 36 | p_right = p // 2 + (p - 1) // 2 37 | p_left = 0 38 | else: 39 | raise Exception(f"Padding mode {mode} is not valid") 40 | return (p_left, p_right) 41 | 42 | 43 | class CachedSequential(nn.Sequential): 44 | """ 45 | Sequential operations with future compensation tracking 46 | """ 47 | 48 | def __init__(self, *args, **kwargs): 49 | cumulative_delay = kwargs.pop("cumulative_delay", 0) 50 | stride = kwargs.pop("stride", 1) 51 | super().__init__(*args, **kwargs) 52 | 53 | self.cumulative_delay = int(cumulative_delay) * stride 54 | 55 | last_delay = 0 56 | for i in range(1, len(self) + 1): 57 | try: 58 | last_delay = self[-i].cumulative_delay 59 | break 60 | except AttributeError: 61 | pass 62 | self.cumulative_delay += last_delay 63 | 64 | 65 | class Sequential(CachedSequential): 66 | pass 67 | 68 | 69 | class CachedPadding1d(nn.Module): 70 | """ 71 | Cached Padding implementation, replace zero padding with the end of 72 | the previous tensor. 73 | """ 74 | 75 | def __init__(self, padding, crop=False): 76 | super().__init__() 77 | self.initialized = 0 78 | self.padding = padding 79 | self.crop = crop 80 | 81 | @torch.jit.unused 82 | @torch.no_grad() 83 | def init_cache(self, x): 84 | b, c, _ = x.shape 85 | self.register_buffer( 86 | "pad", 87 | torch.zeros(MAX_BATCH_SIZE, c, self.padding).to(x)) 88 | self.initialized += 1 89 | 90 | def forward(self, x): 91 | if not self.initialized: 92 | self.init_cache(x) 93 | 94 | if self.padding: 95 | x = torch.cat([self.pad[:x.shape[0]], x], -1) 96 | self.pad[:x.shape[0]].copy_(x[..., -self.padding:]) 97 | 98 | if self.crop: 99 | x = x[..., :-self.padding] 100 | 101 | return x 102 | 103 | 104 | class CachedConv1d(nn.Conv1d): 105 | """ 106 | Implementation of a Conv1d operation with cached padding 107 | """ 108 | 109 | def __init__(self, *args, **kwargs): 110 | padding = kwargs.get("padding", 0) 111 | cumulative_delay = kwargs.pop("cumulative_delay", 0) 112 | 113 | kwargs["padding"] = 0 114 | 115 | super().__init__(*args, **kwargs) 116 | 117 | if isinstance(padding, int): 118 | r_pad = padding 119 | padding = 2 * padding 120 | elif isinstance(padding, list) or isinstance(padding, tuple): 121 | r_pad = padding[1] 122 | padding = padding[0] + padding[1] 123 | 124 | s = self.stride[0] 125 | cd = cumulative_delay 126 | 127 | stride_delay = (s - ((r_pad + cd) % s)) % s 128 | 129 | self.cumulative_delay = (r_pad + stride_delay + cd) // s 130 | 131 | self.cache = CachedPadding1d(padding) 132 | self.downsampling_delay = CachedPadding1d(stride_delay, crop=True) 133 | 134 | def forward(self, x): 135 | x = self.downsampling_delay(x) 136 | x = self.cache(x) 137 | return nn.functional.conv1d( 138 | x, 139 | self.weight, 140 | self.bias, 141 | self.stride, 142 | self.padding, 143 | self.dilation, 144 | self.groups, 145 | ) 146 | 147 | 148 | class CachedConvTranspose1d(nn.ConvTranspose1d): 149 | """ 150 | Implementation of a ConvTranspose1d operation with cached padding 151 | """ 152 | 153 | def __init__(self, *args, **kwargs): 154 | cd = kwargs.pop("cumulative_delay", 0) 155 | super().__init__(*args, **kwargs) 156 | stride = self.stride[0] 157 | self.initialized = 0 158 | self.cumulative_delay = self.padding[0] + cd * stride 159 | 160 | @torch.jit.unused 161 | @torch.no_grad() 162 | def init_cache(self, x): 163 | b, c, _ = x.shape 164 | self.register_buffer( 165 | "cache", 166 | torch.zeros( 167 | MAX_BATCH_SIZE, 168 | c, 169 | 2 * self.padding[0], 170 | ).to(x)) 171 | self.initialized += 1 172 | 173 | def forward(self, x): 174 | x = nn.functional.conv_transpose1d( 175 | x, 176 | self.weight, 177 | None, 178 | self.stride, 179 | 0, 180 | self.output_padding, 181 | self.groups, 182 | self.dilation, 183 | ) 184 | 185 | if not self.initialized: 186 | self.init_cache(x) 187 | 188 | padding = 2 * self.padding[0] 189 | 190 | x[..., :padding] += self.cache[:x.shape[0]] 191 | self.cache[:x.shape[0]].copy_(x[..., -padding:]) 192 | 193 | x = x[..., :-padding] 194 | 195 | bias = self.bias 196 | if bias is not None: 197 | x = x + bias.unsqueeze(-1) 198 | return x 199 | 200 | 201 | class ConvTranspose1d(nn.ConvTranspose1d): 202 | 203 | def __init__(self, *args, **kwargs) -> None: 204 | kwargs.pop("cumulative_delay", 0) 205 | super().__init__(*args, **kwargs) 206 | self.cumulative_delay = 0 207 | 208 | 209 | class Conv1d(nn.Conv1d): 210 | 211 | def __init__(self, *args, **kwargs): 212 | self._pad = kwargs.get("padding", (0, 0)) 213 | kwargs.pop("cumulative_delay", 0) 214 | kwargs["padding"] = 0 215 | 216 | super().__init__(*args, **kwargs) 217 | self.cumulative_delay = 0 218 | 219 | def forward(self, x): 220 | x = nn.functional.pad(x, self._pad) 221 | return nn.functional.conv1d( 222 | x, 223 | self.weight, 224 | self.bias, 225 | self.stride, 226 | self.padding, 227 | self.dilation, 228 | self.groups, 229 | ) 230 | 231 | 232 | class AlignBranches(nn.Module): 233 | 234 | def __init__(self, *branches, delays=None, cumulative_delay=0, stride=1): 235 | super().__init__() 236 | self.branches = nn.ModuleList(branches) 237 | 238 | if delays is None: 239 | delays = list(map(lambda x: x.cumulative_delay, self.branches)) 240 | 241 | max_delay = max(delays) 242 | 243 | self.paddings = nn.ModuleList([ 244 | CachedPadding1d(p, crop=True) 245 | for p in map(lambda f: max_delay - f, delays) 246 | ]) 247 | 248 | self.cumulative_delay = int(cumulative_delay * stride) + max_delay 249 | 250 | def forward(self, x): 251 | outs = [] 252 | for branch, pad in zip(self.branches, self.paddings): 253 | delayed_x = pad(x) 254 | outs.append(branch(delayed_x)) 255 | return outs 256 | 257 | 258 | class Branches(nn.Module): 259 | 260 | def __init__(self, *branches, delays=None, cumulative_delay=0, stride=1): 261 | super().__init__() 262 | self.branches = nn.ModuleList(branches) 263 | 264 | if delays is None: 265 | delays = list(map(lambda x: x.cumulative_delay, self.branches)) 266 | 267 | max_delay = max(delays) 268 | 269 | self.cumulative_delay = int(cumulative_delay * stride) + max_delay 270 | 271 | def forward(self, x): 272 | outs = [] 273 | for branch in self.branches: 274 | outs.append(branch(x)) 275 | return outs 276 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution-NonCommercial 4.0 International 2 | 3 | Creative Commons Corporation ("Creative Commons") is not a law firm and 4 | does not provide legal services or legal advice. Distribution of 5 | Creative Commons public licenses does not create a lawyer-client or 6 | other relationship. Creative Commons makes its licenses and related 7 | information available on an "as-is" basis. Creative Commons gives no 8 | warranties regarding its licenses, any material licensed under their 9 | terms and conditions, or any related information. Creative Commons 10 | disclaims all liability for damages resulting from their use to the 11 | fullest extent possible. 12 | 13 | Using Creative Commons Public Licenses 14 | 15 | Creative Commons public licenses provide a standard set of terms and 16 | conditions that creators and other rights holders may use to share 17 | original works of authorship and other material subject to copyright and 18 | certain other rights specified in the public license below. The 19 | following considerations are for informational purposes only, are not 20 | exhaustive, and do not form part of our licenses. 21 | 22 | - Considerations for licensors: Our public licenses are intended for 23 | use by those authorized to give the public permission to use 24 | material in ways otherwise restricted by copyright and certain other 25 | rights. Our licenses are irrevocable. Licensors should read and 26 | understand the terms and conditions of the license they choose 27 | before applying it. Licensors should also secure all rights 28 | necessary before applying our licenses so that the public can reuse 29 | the material as expected. Licensors should clearly mark any material 30 | not subject to the license. This includes other CC-licensed 31 | material, or material used under an exception or limitation to 32 | copyright. More considerations for licensors : 33 | wiki.creativecommons.org/Considerations_for_licensors 34 | 35 | - Considerations for the public: By using one of our public licenses, 36 | a licensor grants the public permission to use the licensed material 37 | under specified terms and conditions. If the licensor's permission 38 | is not necessary for any reason–for example, because of any 39 | applicable exception or limitation to copyright–then that use is not 40 | regulated by the license. Our licenses grant only permissions under 41 | copyright and certain other rights that a licensor has authority to 42 | grant. Use of the licensed material may still be restricted for 43 | other reasons, including because others have copyright or other 44 | rights in the material. A licensor may make special requests, such 45 | as asking that all changes be marked or described. Although not 46 | required by our licenses, you are encouraged to respect those 47 | requests where reasonable. More considerations for the public : 48 | wiki.creativecommons.org/Considerations_for_licensees 49 | 50 | Creative Commons Attribution-NonCommercial 4.0 International Public 51 | License 52 | 53 | By exercising the Licensed Rights (defined below), You accept and agree 54 | to be bound by the terms and conditions of this Creative Commons 55 | Attribution-NonCommercial 4.0 International Public License ("Public 56 | License"). To the extent this Public License may be interpreted as a 57 | contract, You are granted the Licensed Rights in consideration of Your 58 | acceptance of these terms and conditions, and the Licensor grants You 59 | such rights in consideration of benefits the Licensor receives from 60 | making the Licensed Material available under these terms and conditions. 61 | 62 | - Section 1 – Definitions. 63 | 64 | - a. Adapted Material means material subject to Copyright and 65 | Similar Rights that is derived from or based upon the Licensed 66 | Material and in which the Licensed Material is translated, 67 | altered, arranged, transformed, or otherwise modified in a 68 | manner requiring permission under the Copyright and Similar 69 | Rights held by the Licensor. For purposes of this Public 70 | License, where the Licensed Material is a musical work, 71 | performance, or sound recording, Adapted Material is always 72 | produced where the Licensed Material is synched in timed 73 | relation with a moving image. 74 | - b. Adapter's License means the license You apply to Your 75 | Copyright and Similar Rights in Your contributions to Adapted 76 | Material in accordance with the terms and conditions of this 77 | Public License. 78 | - c. Copyright and Similar Rights means copyright and/or similar 79 | rights closely related to copyright including, without 80 | limitation, performance, broadcast, sound recording, and Sui 81 | Generis Database Rights, without regard to how the rights are 82 | labeled or categorized. For purposes of this Public License, the 83 | rights specified in Section 2(b)(1)-(2) are not Copyright and 84 | Similar Rights. 85 | - d. Effective Technological Measures means those measures that, 86 | in the absence of proper authority, may not be circumvented 87 | under laws fulfilling obligations under Article 11 of the WIPO 88 | Copyright Treaty adopted on December 20, 1996, and/or similar 89 | international agreements. 90 | - e. Exceptions and Limitations means fair use, fair dealing, 91 | and/or any other exception or limitation to Copyright and 92 | Similar Rights that applies to Your use of the Licensed 93 | Material. 94 | - f. Licensed Material means the artistic or literary work, 95 | database, or other material to which the Licensor applied this 96 | Public License. 97 | - g. Licensed Rights means the rights granted to You subject to 98 | the terms and conditions of this Public License, which are 99 | limited to all Copyright and Similar Rights that apply to Your 100 | use of the Licensed Material and that the Licensor has authority 101 | to license. 102 | - h. Licensor means the individual(s) or entity(ies) granting 103 | rights under this Public License. 104 | - i. NonCommercial means not primarily intended for or directed 105 | towards commercial advantage or monetary compensation. For 106 | purposes of this Public License, the exchange of the Licensed 107 | Material for other material subject to Copyright and Similar 108 | Rights by digital file-sharing or similar means is NonCommercial 109 | provided there is no payment of monetary compensation in 110 | connection with the exchange. 111 | - j. Share means to provide material to the public by any means or 112 | process that requires permission under the Licensed Rights, such 113 | as reproduction, public display, public performance, 114 | distribution, dissemination, communication, or importation, and 115 | to make material available to the public including in ways that 116 | members of the public may access the material from a place and 117 | at a time individually chosen by them. 118 | - k. Sui Generis Database Rights means rights other than copyright 119 | resulting from Directive 96/9/EC of the European Parliament and 120 | of the Council of 11 March 1996 on the legal protection of 121 | databases, as amended and/or succeeded, as well as other 122 | essentially equivalent rights anywhere in the world. 123 | - l. You means the individual or entity exercising the Licensed 124 | Rights under this Public License. Your has a corresponding 125 | meaning. 126 | 127 | - Section 2 – Scope. 128 | 129 | - a. License grant. 130 | - 1. Subject to the terms and conditions of this Public 131 | License, the Licensor hereby grants You a worldwide, 132 | royalty-free, non-sublicensable, non-exclusive, irrevocable 133 | license to exercise the Licensed Rights in the Licensed 134 | Material to: 135 | - A. reproduce and Share the Licensed Material, in whole 136 | or in part, for NonCommercial purposes only; and 137 | - B. produce, reproduce, and Share Adapted Material for 138 | NonCommercial purposes only. 139 | - 2. Exceptions and Limitations. For the avoidance of doubt, 140 | where Exceptions and Limitations apply to Your use, this 141 | Public License does not apply, and You do not need to comply 142 | with its terms and conditions. 143 | - 3. Term. The term of this Public License is specified in 144 | Section 6(a). 145 | - 4. Media and formats; technical modifications allowed. The 146 | Licensor authorizes You to exercise the Licensed Rights in 147 | all media and formats whether now known or hereafter 148 | created, and to make technical modifications necessary to do 149 | so. The Licensor waives and/or agrees not to assert any 150 | right or authority to forbid You from making technical 151 | modifications necessary to exercise the Licensed Rights, 152 | including technical modifications necessary to circumvent 153 | Effective Technological Measures. For purposes of this 154 | Public License, simply making modifications authorized by 155 | this Section 2(a)(4) never produces Adapted Material. 156 | - 5. Downstream recipients. 157 | - A. Offer from the Licensor – Licensed Material. Every 158 | recipient of the Licensed Material automatically 159 | receives an offer from the Licensor to exercise the 160 | Licensed Rights under the terms and conditions of this 161 | Public License. 162 | - B. No downstream restrictions. You may not offer or 163 | impose any additional or different terms or conditions 164 | on, or apply any Effective Technological Measures to, 165 | the Licensed Material if doing so restricts exercise of 166 | the Licensed Rights by any recipient of the Licensed 167 | Material. 168 | - 6. No endorsement. Nothing in this Public License 169 | constitutes or may be construed as permission to assert or 170 | imply that You are, or that Your use of the Licensed 171 | Material is, connected with, or sponsored, endorsed, or 172 | granted official status by, the Licensor or others 173 | designated to receive attribution as provided in Section 174 | 3(a)(1)(A)(i). 175 | - b. Other rights. 176 | - 1. Moral rights, such as the right of integrity, are not 177 | licensed under this Public License, nor are publicity, 178 | privacy, and/or other similar personality rights; however, 179 | to the extent possible, the Licensor waives and/or agrees 180 | not to assert any such rights held by the Licensor to the 181 | limited extent necessary to allow You to exercise the 182 | Licensed Rights, but not otherwise. 183 | - 2. Patent and trademark rights are not licensed under this 184 | Public License. 185 | - 3. To the extent possible, the Licensor waives any right to 186 | collect royalties from You for the exercise of the Licensed 187 | Rights, whether directly or through a collecting society 188 | under any voluntary or waivable statutory or compulsory 189 | licensing scheme. In all other cases the Licensor expressly 190 | reserves any right to collect such royalties, including when 191 | the Licensed Material is used other than for NonCommercial 192 | purposes. 193 | 194 | - Section 3 – License Conditions. 195 | 196 | Your exercise of the Licensed Rights is expressly made subject to 197 | the following conditions. 198 | 199 | - a. Attribution. 200 | - 1. If You Share the Licensed Material (including in modified 201 | form), You must: 202 | - A. retain the following if it is supplied by the 203 | Licensor with the Licensed Material: 204 | - i. identification of the creator(s) of the Licensed 205 | Material and any others designated to receive 206 | attribution, in any reasonable manner requested by 207 | the Licensor (including by pseudonym if designated); 208 | - ii. a copyright notice; 209 | - iii. a notice that refers to this Public License; 210 | - iv. a notice that refers to the disclaimer of 211 | warranties; 212 | - v. a URI or hyperlink to the Licensed Material to 213 | the extent reasonably practicable; 214 | - B. indicate if You modified the Licensed Material and 215 | retain an indication of any previous modifications; and 216 | - C. indicate the Licensed Material is licensed under this 217 | Public License, and include the text of, or the URI or 218 | hyperlink to, this Public License. 219 | - 2. You may satisfy the conditions in Section 3(a)(1) in any 220 | reasonable manner based on the medium, means, and context in 221 | which You Share the Licensed Material. For example, it may 222 | be reasonable to satisfy the conditions by providing a URI 223 | or hyperlink to a resource that includes the required 224 | information. 225 | - 3. If requested by the Licensor, You must remove any of the 226 | information required by Section 3(a)(1)(A) to the extent 227 | reasonably practicable. 228 | - 4. If You Share Adapted Material You produce, the Adapter's 229 | License You apply must not prevent recipients of the Adapted 230 | Material from complying with this Public License. 231 | 232 | - Section 4 – Sui Generis Database Rights. 233 | 234 | Where the Licensed Rights include Sui Generis Database Rights that 235 | apply to Your use of the Licensed Material: 236 | 237 | - a. for the avoidance of doubt, Section 2(a)(1) grants You the 238 | right to extract, reuse, reproduce, and Share all or a 239 | substantial portion of the contents of the database for 240 | NonCommercial purposes only; 241 | - b. if You include all or a substantial portion of the database 242 | contents in a database in which You have Sui Generis Database 243 | Rights, then the database in which You have Sui Generis Database 244 | Rights (but not its individual contents) is Adapted Material; 245 | and 246 | - c. You must comply with the conditions in Section 3(a) if You 247 | Share all or a substantial portion of the contents of the 248 | database. 249 | 250 | For the avoidance of doubt, this Section 4 supplements and does not 251 | replace Your obligations under this Public License where the 252 | Licensed Rights include other Copyright and Similar Rights. 253 | 254 | - Section 5 – Disclaimer of Warranties and Limitation of Liability. 255 | 256 | - a. Unless otherwise separately undertaken by the Licensor, to 257 | the extent possible, the Licensor offers the Licensed Material 258 | as-is and as-available, and makes no representations or 259 | warranties of any kind concerning the Licensed Material, whether 260 | express, implied, statutory, or other. This includes, without 261 | limitation, warranties of title, merchantability, fitness for a 262 | particular purpose, non-infringement, absence of latent or other 263 | defects, accuracy, or the presence or absence of errors, whether 264 | or not known or discoverable. Where disclaimers of warranties 265 | are not allowed in full or in part, this disclaimer may not 266 | apply to You. 267 | - b. To the extent possible, in no event will the Licensor be 268 | liable to You on any legal theory (including, without 269 | limitation, negligence) or otherwise for any direct, special, 270 | indirect, incidental, consequential, punitive, exemplary, or 271 | other losses, costs, expenses, or damages arising out of this 272 | Public License or use of the Licensed Material, even if the 273 | Licensor has been advised of the possibility of such losses, 274 | costs, expenses, or damages. Where a limitation of liability is 275 | not allowed in full or in part, this limitation may not apply to 276 | You. 277 | - c. The disclaimer of warranties and limitation of liability 278 | provided above shall be interpreted in a manner that, to the 279 | extent possible, most closely approximates an absolute 280 | disclaimer and waiver of all liability. 281 | 282 | - Section 6 – Term and Termination. 283 | 284 | - a. This Public License applies for the term of the Copyright and 285 | Similar Rights licensed here. However, if You fail to comply 286 | with this Public License, then Your rights under this Public 287 | License terminate automatically. 288 | - b. Where Your right to use the Licensed Material has terminated 289 | under Section 6(a), it reinstates: 290 | 291 | - 1. automatically as of the date the violation is cured, 292 | provided it is cured within 30 days of Your discovery of the 293 | violation; or 294 | - 2. upon express reinstatement by the Licensor. 295 | 296 | For the avoidance of doubt, this Section 6(b) does not affect 297 | any right the Licensor may have to seek remedies for Your 298 | violations of this Public License. 299 | 300 | - c. For the avoidance of doubt, the Licensor may also offer the 301 | Licensed Material under separate terms or conditions or stop 302 | distributing the Licensed Material at any time; however, doing 303 | so will not terminate this Public License. 304 | - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 305 | License. 306 | 307 | - Section 7 – Other Terms and Conditions. 308 | 309 | - a. The Licensor shall not be bound by any additional or 310 | different terms or conditions communicated by You unless 311 | expressly agreed. 312 | - b. Any arrangements, understandings, or agreements regarding the 313 | Licensed Material not stated herein are separate from and 314 | independent of the terms and conditions of this Public License. 315 | 316 | - Section 8 – Interpretation. 317 | 318 | - a. For the avoidance of doubt, this Public License does not, and 319 | shall not be interpreted to, reduce, limit, restrict, or impose 320 | conditions on any use of the Licensed Material that could 321 | lawfully be made without permission under this Public License. 322 | - b. To the extent possible, if any provision of this Public 323 | License is deemed unenforceable, it shall be automatically 324 | reformed to the minimum extent necessary to make it enforceable. 325 | If the provision cannot be reformed, it shall be severed from 326 | this Public License without affecting the enforceability of the 327 | remaining terms and conditions. 328 | - c. No term or condition of this Public License will be waived 329 | and no failure to comply consented to unless expressly agreed to 330 | by the Licensor. 331 | - d. Nothing in this Public License constitutes or may be 332 | interpreted as a limitation upon, or waiver of, any privileges 333 | and immunities that apply to the Licensor or You, including from 334 | the legal processes of any jurisdiction or authority. 335 | 336 | Creative Commons is not a party to its public licenses. Notwithstanding, 337 | Creative Commons may elect to apply one of its public licenses to 338 | material it publishes and in those instances will be considered the 339 | "Licensor." The text of the Creative Commons public licenses is 340 | dedicated to the public domain under the CC0 Public Domain Dedication. 341 | Except for the limited purpose of indicating that material is shared 342 | under a Creative Commons public license or as otherwise permitted by the 343 | Creative Commons policies published at creativecommons.org/policies, 344 | Creative Commons does not authorize the use of the trademark "Creative 345 | Commons" or any other trademark or logo of Creative Commons without its 346 | prior written consent including, without limitation, in connection with 347 | any unauthorized modifications to any of its public licenses or any 348 | other arrangements, understandings, or agreements concerning use of 349 | licensed material. For the avoidance of doubt, this paragraph does not 350 | form part of the public licenses. 351 | 352 | Creative Commons may be contacted at creativecommons.org. 353 | --------------------------------------------------------------------------------