Convolution operator in HWCN layout. Parameters ---------- a_np : numpy.ndarray 4-D with shape [in_height, in_width, in_channel, batch] w_np : numpy.ndarray 4-D with shape [filter_height, filter_width, in_channel, num_filter] stride : int or a list/tuple of two
(a_np, w_np, stride, padding)
| 24 | |
| 25 | |
| 26 | def conv2d_hwcn_python(a_np, w_np, stride, padding): |
| 27 | """Convolution operator in HWCN layout. |
| 28 | |
| 29 | Parameters |
| 30 | ---------- |
| 31 | a_np : numpy.ndarray |
| 32 | 4-D with shape [in_height, in_width, in_channel, batch] |
| 33 | |
| 34 | w_np : numpy.ndarray |
| 35 | 4-D with shape [filter_height, filter_width, in_channel, num_filter] |
| 36 | |
| 37 | stride : int or a list/tuple of two ints |
| 38 | Stride size, or [stride_height, stride_width] |
| 39 | |
| 40 | padding : int or str or a list/tuple of 2 or 4 ints |
| 41 | Padding size, or ['VALID', 'SAME'], or |
| 42 | [pad_height, pad_width] for 2 ints, or |
| 43 | [pad_top, pad_left, pad_bottom, pad_right] for 2 ints |
| 44 | |
| 45 | Returns |
| 46 | ------- |
| 47 | b_np : np.ndarray |
| 48 | 4-D with shape [out_height, out_width, out_channel, batch] |
| 49 | """ |
| 50 | in_height, in_width, in_channel, batch = a_np.shape |
| 51 | kernel_h, kernel_w, _, num_filter = w_np.shape |
| 52 | if isinstance(stride, int): |
| 53 | stride_h = stride_w = stride |
| 54 | else: |
| 55 | stride_h, stride_w = stride |
| 56 | |
| 57 | pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (kernel_h, kernel_w)) |
| 58 | pad_h = pad_top + pad_bottom |
| 59 | pad_w = pad_left + pad_right |
| 60 | # compute the output shape |
| 61 | out_channel = num_filter |
| 62 | out_height = (in_height - kernel_h + pad_h) // stride_h + 1 |
| 63 | out_width = (in_width - kernel_w + pad_w) // stride_w + 1 |
| 64 | # change the layout from HWCN to NCHW |
| 65 | at = a_np.transpose((3, 2, 0, 1)) |
| 66 | wt = w_np.transpose((3, 2, 0, 1)) |
| 67 | bt = np.zeros((batch, out_channel, out_height, out_width)) |
| 68 | # computation |
| 69 | for n in range(batch): |
| 70 | for f in range(out_channel): |
| 71 | for c in range(in_channel): |
| 72 | if pad_h > 0 or pad_w > 0: |
| 73 | apad = np.zeros((in_height + pad_h, in_width + pad_w)) |
| 74 | apad[pad_top : pad_top + in_height, pad_left : pad_left + in_width] = at[n, c] |
| 75 | else: |
| 76 | apad = at[n, c] |
| 77 | out = scipy.signal.convolve2d(apad, np.rot90(np.rot90(wt[f, c])), mode="valid") |
| 78 | bt[n, f] += out[::stride_h, ::stride_w] |
| 79 | return bt.transpose((2, 3, 1, 0)) |
nothing calls this directly
no test coverage detected
searching dependent graphs…