-
Notifications
You must be signed in to change notification settings - Fork 131
Implement Convolve2D
Op
#1397
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
Draft
jessegrabowski
wants to merge
2
commits into
pymc-devs:main
Choose a base branch
from
jessegrabowski:conv-2d
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+148
−2
Draft
Implement Convolve2D
Op
#1397
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,14 @@ | ||
from typing import TYPE_CHECKING, Literal, cast | ||
|
||
from numpy import convolve as numpy_convolve | ||
from scipy.signal import convolve2d as scipy_convolve2d | ||
|
||
from pytensor.graph import Apply, Op | ||
from pytensor.scalar.basic import upcast | ||
from pytensor.tensor.basic import as_tensor_variable, join, zeros | ||
from pytensor.tensor.blockwise import Blockwise | ||
from pytensor.tensor.math import maximum, minimum | ||
from pytensor.tensor.type import vector | ||
from pytensor.tensor.type import matrix, vector | ||
from pytensor.tensor.variable import TensorVariable | ||
|
||
|
||
|
@@ -131,3 +132,116 @@ | |
mode = "valid" | ||
|
||
return cast(TensorVariable, Blockwise(Convolve1d(mode=mode))(in1, in2)) | ||
|
||
|
||
class Convolve2D(Op): | ||
__props__ = ("mode", "boundary", "fillvalue") | ||
gufunc_signature = "(n,m),(k,l)->(o,p)" | ||
|
||
def __init__( | ||
self, | ||
mode: Literal["full", "valid", "same"] = "full", | ||
boundary: Literal["fill", "wrap", "symm"] = "fill", | ||
fillvalue: float | int = 0, | ||
): | ||
if mode not in ("full", "valid", "same"): | ||
raise ValueError(f"Invalid mode: {mode}") | ||
if boundary not in ("fill", "wrap", "symm"): | ||
raise ValueError(f"Invalid boundary: {boundary}") | ||
|
||
self.mode = mode | ||
self.boundary = boundary | ||
self.fillvalue = fillvalue | ||
|
||
def make_node(self, in1, in2): | ||
in1, in2 = map(as_tensor_variable, (in1, in2)) | ||
|
||
assert in1.ndim == 2 | ||
assert in2.ndim == 2 | ||
|
||
dtype = upcast(in1.dtype, in2.dtype) | ||
|
||
n, m = in1.type.shape | ||
k, l = in2.type.shape | ||
|
||
if any(x is None for x in (n, m, k, l)): | ||
out_shape = (None, None) | ||
elif self.mode == "full": | ||
out_shape = (n + k - 1, m + l - 1) | ||
elif self.mode == "valid": | ||
out_shape = (n - k + 1, m - l + 1) | ||
else: # mode == "same" | ||
out_shape = (n, m) | ||
|
||
out = matrix(dtype=dtype, shape=out_shape) | ||
return Apply(self, [in1, in2], [out]) | ||
|
||
def perform(self, node, inputs, outputs): | ||
in1, in2 = inputs | ||
outputs[0][0] = scipy_convolve2d( | ||
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. Now this is where I would like to compare with the old C stuff we had 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. See below |
||
in1, in2, mode=self.mode, boundary=self.boundary, fillvalue=self.fillvalue | ||
) | ||
|
||
def infer_shape(self, fgraph, node, shapes): | ||
in1_shape, in2_shape = shapes | ||
n, m = in1_shape | ||
k, l = in2_shape | ||
|
||
if self.mode == "full": | ||
shape = (n + k - 1, m + l - 1) | ||
elif self.mode == "valid": | ||
shape = ( | ||
maximum(n, k) - minimum(n, k) + 1, | ||
maximum(m, l) - minimum(m, l) + 1, | ||
) | ||
else: # self.mode == 'same': | ||
shape = (n, m) | ||
|
||
return [shape] | ||
|
||
def L_op(self, inputs, outputs, output_grads): | ||
raise NotImplementedError | ||
|
||
|
||
def convolve2d( | ||
in1: "TensorLike", | ||
in2: "TensorLike", | ||
mode: Literal["full", "valid", "same"] = "full", | ||
boundary: Literal["fill", "wrap", "symm"] = "fill", | ||
fillvalue: float | int = 0, | ||
) -> TensorVariable: | ||
"""Convolve two two-dimensional arrays. | ||
|
||
Convolve in1 and in2, with the output size determined by the mode argument. | ||
|
||
Parameters | ||
---------- | ||
in1 : (..., N, M) tensor_like | ||
First input. | ||
in2 : (..., K, L) tensor_like | ||
Second input. | ||
mode : {'full', 'valid', 'same'}, optional | ||
A string indicating the size of the output: | ||
- 'full': The output is the full discrete linear convolution of the inputs, with shape (..., N+K-1, M+L-1). | ||
- 'valid': The output consists only of elements that do not rely on zero-padding, with shape (..., max(N, K) - min(N, K) + 1, max(M, L) - min(M, L) + 1). | ||
- 'same': The output is the same size as in1, centered with respect to the 'full' output. | ||
boundary : {'fill', 'wrap', 'symm'}, optional | ||
A string indicating how to handle boundaries: | ||
- 'fill': Pads the input arrays with fillvalue. | ||
- 'wrap': Circularly wraps the input arrays. | ||
- 'symm': Symmetrically reflects the input arrays. | ||
fillvalue : float or int, optional | ||
The value to use for padding when boundary is 'fill'. Default is 0. | ||
Returns | ||
------- | ||
out: tensor_variable | ||
The discrete linear convolution of in1 with in2. | ||
|
||
""" | ||
in1 = as_tensor_variable(in1) | ||
in2 = as_tensor_variable(in2) | ||
|
||
blockwise_convolve = Blockwise( | ||
Convolve2D(mode=mode, boundary=boundary, fillvalue=fillvalue) | ||
) | ||
return cast(TensorVariable, blockwise_convolve(in1, in2)) |
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.