Skip to content

Make convolve mode symbolic to avoid unnecessary large convolution in gradient graph #1522

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 4 commits into from
Jul 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 5 additions & 13 deletions pytensor/link/jax/dispatch/blockwise.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
import jax.numpy as jnp

from pytensor.graph import FunctionGraph
from pytensor.link.jax.dispatch import jax_funcify
from pytensor.tensor.blockwise import Blockwise


@jax_funcify.register(Blockwise)
def funcify_Blockwise(op: Blockwise, node, *args, **kwargs):
def jax_funcify_Blockwise(op: Blockwise, node, **kwargs):
signature = op.signature
core_node = op._create_dummy_core_node(node.inputs)
core_fgraph = FunctionGraph(inputs=core_node.inputs, outputs=core_node.outputs)
tuple_core_fn = jax_funcify(core_fgraph)

if len(node.outputs) == 1:

def core_fn(*inputs):
return tuple_core_fn(*inputs)[0]

else:
core_fn = tuple_core_fn
core_node = op._create_dummy_core_node(
node.inputs, propagate_unbatched_core_inputs=True
)
core_fn = jax_funcify(core_node.op, node=core_node, **kwargs)

vect_fn = jnp.vectorize(core_fn, signature=signature)

Expand Down
16 changes: 13 additions & 3 deletions pytensor/link/jax/dispatch/signal/conv.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import jax

from pytensor.link.jax.dispatch import jax_funcify
from pytensor.tensor.basic import get_underlying_scalar_constant_value
from pytensor.tensor.exceptions import NotScalarConstantError
from pytensor.tensor.signal.conv import Convolve1d


@jax_funcify.register(Convolve1d)
def jax_funcify_Convolve1d(op, node, **kwargs):
mode = op.mode
_, _, full_mode = node.inputs
try:
full_mode = get_underlying_scalar_constant_value(full_mode)
except NotScalarConstantError:
raise NotImplementedError(

Check warning on line 15 in pytensor/link/jax/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/jax/dispatch/signal/conv.py#L14-L15

Added lines #L14 - L15 were not covered by tests
"Cannot compile Convolve1D to jax without static mode"
)
static_mode = "full" if full_mode else "valid"

def conv1d(data, kernel):
return jax.numpy.convolve(data, kernel, mode=mode)
def conv1d(data, kernel, _runtime_full_mode):
# _runtime_full_mode is not used, as we only support static mode
return jax.numpy.convolve(data, kernel, mode=static_mode)

return conv1d
5 changes: 3 additions & 2 deletions pytensor/link/numba/dispatch/blockwise.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from pytensor.tensor.blockwise import Blockwise, BlockwiseWithCoreShape


@numba_funcify.register
@numba_funcify.register(BlockwiseWithCoreShape)
def numba_funcify_Blockwise(op: BlockwiseWithCoreShape, node, **kwargs):
[blockwise_node] = op.fgraph.apply_nodes
blockwise_op: Blockwise = blockwise_node.op
Expand All @@ -26,7 +26,8 @@ def numba_funcify_Blockwise(op: BlockwiseWithCoreShape, node, **kwargs):
core_shapes_len = tuple(get_vector_length(sh) for sh in node.inputs[nin:])

core_node = blockwise_op._create_dummy_core_node(
cast(tuple[TensorVariable], blockwise_node.inputs)
cast(tuple[TensorVariable], node.inputs[:nin]),
propagate_unbatched_core_inputs=True,
)
core_op_fn = numba_funcify(
core_op,
Expand Down
109 changes: 54 additions & 55 deletions pytensor/link/numba/dispatch/signal/conv.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,62 +9,61 @@
@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)

if mode == "valid":

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}")
@numba_njit
def valid_convolve1d(x, y):
nx = len(x)
ny = len(y)

Check warning on line 19 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L18-L19

Added lines #L18 - L19 were not covered by tests
if nx < ny:
x, y = y, x
nx, ny = ny, nx
y_flipped = y[::-1]

Check warning on line 23 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L21-L23

Added lines #L21 - L23 were not covered by tests

length = nx - ny + 1
ret = np.empty(length, out_dtype)

Check warning on line 26 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L25-L26

Added lines #L25 - L26 were not covered by tests

for i in range(length):
ret[i] = innerprod(x[i : i + ny], y_flipped)

Check warning on line 29 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L29

Added line #L29 was not covered by tests

return ret

Check warning on line 31 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L31

Added line #L31 was not covered by tests

@numba_njit
def full_convolve1d(x, y):
nx = len(x)
ny = len(y)

Check warning on line 36 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L35-L36

Added lines #L35 - L36 were not covered by tests
if nx < ny:
x, y = y, x
nx, ny = ny, nx
y_flipped = y[::-1]

Check warning on line 40 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L38-L40

Added lines #L38 - L40 were not covered by tests

length = nx + ny - 1
ret = np.empty(length, out_dtype)
idx = 0

Check warning on line 44 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L42-L44

Added lines #L42 - L44 were not covered by tests

for i in range(ny - 1):
k = i + 1
ret[idx] = innerprod(x[:k], y_flipped[-k:])
idx = idx + 1

Check warning on line 49 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L47-L49

Added lines #L47 - L49 were not covered by tests

for i in range(nx - ny + 1):
ret[idx] = innerprod(x[i : i + ny], y_flipped)
idx = idx + 1

Check warning on line 53 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L52-L53

Added lines #L52 - L53 were not covered by tests

for i in range(ny - 1):
k = ny - i - 1
ret[idx] = innerprod(x[-k:], y_flipped[:k])
idx = idx + 1

Check warning on line 58 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L56-L58

Added lines #L56 - L58 were not covered by tests

return ret

Check warning on line 60 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L60

Added line #L60 was not covered by tests

@numba_njit
def convolve_1d(x, y, mode):
if mode:
return full_convolve1d(x, y)

Check warning on line 65 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L65

Added line #L65 was not covered by tests
else:
return valid_convolve1d(x, y)

Check warning on line 67 in pytensor/link/numba/dispatch/signal/conv.py

View check run for this annotation

Codecov / codecov/patch

pytensor/link/numba/dispatch/signal/conv.py#L67

Added line #L67 was not covered by tests

return convolve_1d
7 changes: 3 additions & 4 deletions pytensor/tensor/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,10 +678,9 @@ def make_node(self, t):
self, [t], [ps.get_scalar_type(dtype=t.type.dtype).make_variable()]
)

def perform(self, node, inp, out_):
(s,) = inp
(out,) = out_
out[0] = s.flatten()[0]
def perform(self, node, inputs, output_storage):
# not using .item() because that returns a Python scalar, not a numpy scalar
output_storage[0][0] = inputs[0][()]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That [()] syntax is really ugly

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's how you index/update a 0d array in numpy

Copy link
Member

@jessegrabowski jessegrabowski Jul 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can also use None I believe.

Edit: It only works for assignment. If this is really what they want you to do in this case, that sucks. But c'est la vie.

Copy link
Member Author

@ricardoV94 ricardoV94 Jul 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea is you're indexing an array without indices / dimensions, so you can't say pick first entry of first dimension (there are no dims). Anyway surprised it bothers you too much


def infer_shape(self, fgraph, node, in_shapes):
return [()]
Expand Down
Loading