|
| 1 | +from typing import TYPE_CHECKING, Literal, cast |
| 2 | + |
| 3 | +from numpy import convolve as numpy_convolve |
| 4 | + |
| 5 | +from pytensor.graph import Apply, Op |
| 6 | +from pytensor.scalar.basic import upcast |
| 7 | +from pytensor.tensor.basic import as_tensor_variable, join, zeros |
| 8 | +from pytensor.tensor.blockwise import Blockwise |
| 9 | +from pytensor.tensor.math import maximum, minimum |
| 10 | +from pytensor.tensor.type import vector |
| 11 | +from pytensor.tensor.variable import TensorVariable |
| 12 | + |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from pytensor.tensor import TensorLike |
| 16 | + |
| 17 | + |
| 18 | +class Conv1d(Op): |
| 19 | + __props__ = ("mode",) |
| 20 | + gufunc_signature = "(n),(k)->(o)" |
| 21 | + |
| 22 | + def __init__(self, mode: Literal["full", "valid"] = "full"): |
| 23 | + if mode not in ("full", "valid"): |
| 24 | + raise ValueError(f"Invalid mode: {mode}") |
| 25 | + self.mode = mode |
| 26 | + |
| 27 | + def make_node(self, data, kernel): |
| 28 | + data = as_tensor_variable(data) |
| 29 | + kernel = as_tensor_variable(kernel) |
| 30 | + |
| 31 | + assert data.ndim == 1 |
| 32 | + assert kernel.ndim == 1 |
| 33 | + |
| 34 | + dtype = upcast(data.dtype, kernel.dtype) |
| 35 | + |
| 36 | + n = data.type.shape[0] |
| 37 | + k = kernel.type.shape[0] |
| 38 | + |
| 39 | + if n is None or k is None: |
| 40 | + out_shape = (None,) |
| 41 | + elif self.mode == "full": |
| 42 | + out_shape = (n + k - 1,) |
| 43 | + else: # mode == "valid": |
| 44 | + out_shape = (max(n, k) - min(n, k) + 1,) |
| 45 | + |
| 46 | + out = vector(dtype=dtype, shape=out_shape) |
| 47 | + return Apply(self, [data, kernel], [out]) |
| 48 | + |
| 49 | + def perform(self, node, inputs, outputs): |
| 50 | + data, kernel = inputs |
| 51 | + # We use numpy_convolve as that's what scipy would use if method="direct" was passed. |
| 52 | + # And mode != "same", which this Op doesn't cover anyway. |
| 53 | + outputs[0][0] = numpy_convolve(data, kernel, mode=self.mode) |
| 54 | + |
| 55 | + def infer_shape(self, fgraph, node, shapes): |
| 56 | + data_shape, kernel_shape = shapes |
| 57 | + n = data_shape[0] |
| 58 | + k = kernel_shape[0] |
| 59 | + if self.mode == "full": |
| 60 | + shape = n + k - 1 |
| 61 | + else: # mode == "valid": |
| 62 | + shape = maximum(n, k) - minimum(n, k) + 1 |
| 63 | + return [[shape]] |
| 64 | + |
| 65 | + def L_op(self, inputs, outputs, output_grads): |
| 66 | + data, kernel = inputs |
| 67 | + [grad] = output_grads |
| 68 | + |
| 69 | + if self.mode == "full": |
| 70 | + valid_conv = type(self)(mode="valid") |
| 71 | + data_bar = valid_conv(grad, kernel[::-1]) |
| 72 | + kernel_bar = valid_conv(grad, data[::-1]) |
| 73 | + |
| 74 | + else: # mode == "valid": |
| 75 | + full_conv = type(self)(mode="full") |
| 76 | + n = data.shape[0] |
| 77 | + k = kernel.shape[0] |
| 78 | + kmn = maximum(0, k - n) |
| 79 | + nkm = maximum(0, n - k) |
| 80 | + # We need mode="full" if k >= n else "valid" for data_bar (opposite for kernel_bar), but mode is not symbolic. |
| 81 | + # Instead, we always use mode="full" and slice the result so it behaves like "valid" for the input that's shorter. |
| 82 | + data_bar = full_conv(grad, kernel[::-1]) |
| 83 | + data_bar = data_bar[kmn : data_bar.shape[0] - kmn] |
| 84 | + kernel_bar = full_conv(grad, data[::-1]) |
| 85 | + kernel_bar = kernel_bar[nkm : kernel_bar.shape[0] - nkm] |
| 86 | + |
| 87 | + return [data_bar, kernel_bar] |
| 88 | + |
| 89 | + |
| 90 | +def convolve1d( |
| 91 | + in1: "TensorLike", |
| 92 | + in2: "TensorLike", |
| 93 | + mode: Literal["full", "valid", "same"] = "full", |
| 94 | +) -> TensorVariable: |
| 95 | + """Convolve two one-dimensional arrays. |
| 96 | +
|
| 97 | + Convolve in1 and in2, with the output size determined by the mode argument. |
| 98 | +
|
| 99 | + Parameters |
| 100 | + ---------- |
| 101 | + in1 : (..., N,) tensor_like |
| 102 | + First input. |
| 103 | + in2 : (..., M,) tensor_like |
| 104 | + Second input. |
| 105 | + mode : {'full', 'valid', 'same'}, optional |
| 106 | + A string indicating the size of the output: |
| 107 | + - 'full': The output is the full discrete linear convolution of the inputs, with shape (..., N+M-1,). |
| 108 | + - 'valid': The output consists only of elements that do not rely on zero-padding, with shape (..., max(N, M) - min(N, M) + 1,). |
| 109 | + - 'same': The output is the same size as in1, centered with respect to the 'full' output. |
| 110 | +
|
| 111 | + Returns |
| 112 | + ------- |
| 113 | + out: tensor_variable |
| 114 | + The discrete linear convolution of in1 with in2. |
| 115 | +
|
| 116 | + """ |
| 117 | + in1 = as_tensor_variable(in1) |
| 118 | + in2 = as_tensor_variable(in2) |
| 119 | + |
| 120 | + if mode == "same": |
| 121 | + # We implement "same" as "valid" with padded data. |
| 122 | + in1_batch_shape = tuple(in1.shape)[:-1] |
| 123 | + zeros_left = in2.shape[0] // 2 |
| 124 | + zeros_right = (in2.shape[0] - 1) // 2 |
| 125 | + in1 = join( |
| 126 | + -1, |
| 127 | + zeros((*in1_batch_shape, zeros_left), dtype=in2.dtype), |
| 128 | + in1, |
| 129 | + zeros((*in1_batch_shape, zeros_right), dtype=in2.dtype), |
| 130 | + ) |
| 131 | + mode = "valid" |
| 132 | + |
| 133 | + return cast(TensorVariable, Blockwise(Conv1d(mode=mode))(in1, in2)) |
| 134 | + |
| 135 | + |
| 136 | +def convolve( |
| 137 | + in1: "TensorLike", |
| 138 | + in2: "TensorLike", |
| 139 | + mode: Literal["full", "valid", "same"] = "full", |
| 140 | + method: Literal["auto", "direct", "fft"] = "direct", |
| 141 | +) -> TensorVariable: |
| 142 | + """Convolve two N-dimensional arrays. |
| 143 | +
|
| 144 | + Convolve in1 and in2, with the output size determined by the mode argument. |
| 145 | +
|
| 146 | + Parameters |
| 147 | + ---------- |
| 148 | + in1 : tensor_like |
| 149 | + First input. |
| 150 | + in2 : tensor_like |
| 151 | + Second input. |
| 152 | + mode : {'full', 'valid', 'same'}, optional |
| 153 | + A string indicating the size of the output: |
| 154 | + - 'full': The output is the full discrete linear convolution of the inputs. (Default) |
| 155 | + - 'valid': The output consists only of elements that do not rely on zero-padding. |
| 156 | + - 'same': The output is the same size as in1, centered with respect to the 'full' output. |
| 157 | + method : {'auto', 'direct', 'fft'}, optional |
| 158 | + Unused by PyTensor, only direct method is used. |
| 159 | +
|
| 160 | + Returns |
| 161 | + ------- |
| 162 | + out: tensor_variable |
| 163 | + The discrete linear convolution of in1 with in2. |
| 164 | + """ |
| 165 | + in1 = as_tensor_variable(in1) |
| 166 | + in2 = as_tensor_variable(in2) |
| 167 | + if in1.ndim != 1 or in2.ndim != 1: |
| 168 | + raise NotImplementedError( |
| 169 | + "convolve only implemented for 1D inputs. If you want a batch 1d convolution, use convolve1d." |
| 170 | + ) |
| 171 | + return convolve1d(in1, in2, mode=mode) |
0 commit comments