10. 2D Convolution medium
Write a program that performs a 2D convolution operation on the GPU. Given an input matrix and a kernel (filter), compute the convolved output. The convolution should be performed with a "valid" boundary condition, meaning the kernel is only applied where it fully overlaps with the input.
Input (4x4) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Kernel (2x2) 0 1 1 0 Output[0][0] 7 1×0 + 2×1 + 5×1 + 6×0 = 0 + 2 + 5 + 0 = 7 kernel position output cellThe input consists of:
input: A 2D matrix of 32-bit floating-point numbers, represented as a 1D array in row-major order.kernel: A 2D kernel (filter) of 32-bit floating-point numbers, also represented as a 1D array in row-major order.
The output should be written to the output matrix (also a 1D array in row-major order). The output matrix will have dimensions:
output_rows = input_rows - kernel_rows + 1output_cols = input_cols - kernel_cols + 1
The convolution operation is defined as:
Implementation Requirements
- Use only native features (external libraries are not permitted)
- The
solvefunction signature must remain unchanged - The final result must be stored in the array
output
Example 1:
Input:
input (3×3):
kernel (2×2):
input_rows = 3
input_cols = 3
kernel_rows = 2
kernel_cols = 2
Output:
output (2×2):
Example 2:
Input:
input (4×4):
kernel (1×3):
input_rows = 4
input_cols = 4
kernel_rows = 1
kernel_cols = 3
Output:
output (4×2):
Constraints
- 1 ≤
input_rows,input_cols≤ 3072 - 1 ≤
kernel_rows,kernel_cols≤ 31 kernel_rows≤input_rowskernel_cols≤input_cols- Performance is measured with
input_cols= 3,072,input_rows= 3,072,kernel_cols= 15,kernel_rows= 15
Starter code (CUDA)
#include <cuda_runtime.h>
// input, kernel, output are device pointers
extern "C" void solve(const float* input, const float* kernel, float* output, int input_rows,
int input_cols, int kernel_rows, int kernel_cols) {}
From LeetGPU, CC BY-NC-ND 4.0.