-
Notifications
You must be signed in to change notification settings - Fork 135
Faster convolve1d in numba backend #1378
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,70 @@ | ||
import numpy as np | ||
from numba.np.arraymath import _get_inner_prod | ||
|
||
from pytensor.link.numba.dispatch import numba_funcify | ||
from pytensor.link.numba.dispatch.basic import numba_njit | ||
from pytensor.tensor.signal.conv import Conv1d | ||
from pytensor.tensor.signal.conv import Convolve1d | ||
|
||
|
||
@numba_funcify.register(Conv1d) | ||
def numba_funcify_Conv1d(op, node, **kwargs): | ||
@numba_funcify.register(Convolve1d) | ||
def numba_funcify_Convolve1d(op, node, **kwargs): | ||
# This specialized version is faster than the overloaded numba np.convolve | ||
mode = op.mode | ||
a_dtype, b_dtype = node.inputs[0].type.dtype, node.inputs[1].type.dtype | ||
out_dtype = node.outputs[0].type.dtype | ||
innerprod = _get_inner_prod(a_dtype, b_dtype) | ||
|
||
@numba_njit | ||
def conv1d(data, kernel): | ||
return np.convolve(data, kernel, mode=mode) | ||
if mode == "valid": | ||
|
||
return conv1d | ||
def valid_convolve1d(x, y): | ||
nx = len(x) | ||
ny = len(y) | ||
if nx < ny: | ||
x, y = y, x | ||
nx, ny = ny, nx | ||
y_flipped = y[::-1] | ||
|
||
length = nx - ny + 1 | ||
ret = np.empty(length, out_dtype) | ||
|
||
for i in range(length): | ||
ret[i] = innerprod(x[i : i + ny], y_flipped) | ||
|
||
return ret | ||
|
||
return numba_njit(valid_convolve1d) | ||
|
||
elif mode == "full": | ||
|
||
def full_convolve1d(x, y): | ||
nx = len(x) | ||
ny = len(y) | ||
if nx < ny: | ||
x, y = y, x | ||
nx, ny = ny, nx | ||
y_flipped = y[::-1] | ||
|
||
length = nx + ny - 1 | ||
ret = np.empty(length, out_dtype) | ||
idx = 0 | ||
|
||
for i in range(ny - 1): | ||
k = i + 1 | ||
ret[idx] = innerprod(x[:k], y_flipped[-k:]) | ||
idx = idx + 1 | ||
|
||
for i in range(nx - ny + 1): | ||
ret[idx] = innerprod(x[i : i + ny], y_flipped) | ||
idx = idx + 1 | ||
|
||
for i in range(ny - 1): | ||
k = ny - i - 1 | ||
ret[idx] = innerprod(x[-k:], y_flipped[:k]) | ||
idx = idx + 1 | ||
|
||
return ret | ||
|
||
return numba_njit(full_convolve1d) | ||
|
||
else: | ||
raise ValueError(f"Unsupported mode: {mode}") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
from pytensor.graph.basic import Constant | ||
from pytensor.graph.rewriting.basic import copy_stack_trace, node_rewriter | ||
from pytensor.tensor.blockwise import Blockwise | ||
from pytensor.tensor.rewriting.basic import register_specialize, register_stabilize | ||
from pytensor.tensor.signal import convolve1d | ||
from pytensor.tensor.signal.conv import Convolve1d | ||
from pytensor.tensor.subtensor import Subtensor, indices_from_subtensor | ||
|
||
|
||
@register_stabilize | ||
@register_specialize | ||
@node_rewriter([Subtensor]) | ||
def local_sliced_full_conv_to_valid_conv(fgraph, node): | ||
"""Rewrite sliced full conv that are equivalent to valid. | ||
|
||
The gradient of a valid Conv1d always implements the worst case scenario - full convolution - | ||
because it would need to know which input is larger to do something smarter. | ||
If we find out (through rewrites or static shape) we provide the direct implementation | ||
which can be orders of magnitude faster. | ||
|
||
# if x.shape[-1] > y.shape[-1] | ||
# z = convolve1d(x, y, mode="full") | ||
# z[..., y.shape[-1] - 1: z.shape[-1] - y.shape[-1] - 1] -> convolve1d(x, y, mode="valid") | ||
""" | ||
conv, *other_idx_vars = node.inputs | ||
|
||
if not ( | ||
conv.owner is not None | ||
and isinstance(conv.owner.op, Blockwise) | ||
and isinstance(conv.owner.op.core_op, Convolve1d) | ||
and conv.owner.op.core_op.mode == "full" | ||
): | ||
return None | ||
|
||
# Check we have an (a:b) constant slice at the last axis of the input | ||
idx_list = node.op.idx_list | ||
if not (len(idx_list) == conv.type.ndim and isinstance(idx_list[-1], slice)): | ||
return None | ||
|
||
last_slice = idx_list[-1] | ||
if not ( | ||
last_slice.start is not None | ||
and last_slice.stop is not None | ||
and last_slice.step is None | ||
): | ||
return None | ||
|
||
*other_idx_vars, start, stop = other_idx_vars | ||
if not (isinstance(start, Constant) and isinstance(stop, Constant)): | ||
return None | ||
|
||
x, y = conv.owner.inputs | ||
len_x = x.type.shape[-1] | ||
len_y = y.type.shape[-1] | ||
if len_x is None or len_y is None: | ||
return None | ||
|
||
start, stop = start.data, stop.data | ||
if len_x < len_y: | ||
# Convolution is symmetric with input order | ||
x, y = y, x | ||
len_x, len_y = len_y, len_x | ||
|
||
if ( | ||
start == len_y - 1 | ||
# equivalent to stop = conv.shape[-1] - len_y - 1 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why not use that form then? I don't understand this comment There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because I already extracted len_x, and I can use that directly |
||
and stop == start + (len_x - len_y) + 1 | ||
): | ||
new_conv = convolve1d(x, y, mode="valid") | ||
copy_stack_trace(conv, new_conv) | ||
|
||
if other_idx_vars: | ||
# If there were more than just empty slices besides the last one | ||
new_indices = indices_from_subtensor(idx_list[:-1], other_idx_vars) | ||
new_conv = new_conv[new_indices] | ||
copy_stack_trace(node.out, new_conv) | ||
|
||
return [new_conv] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.