Coding questions · NVIDIA
Implement 2D convolution using NumPy slicing
This question evaluates a candidate's proficiency with array manipulation and vectorized numerical computation using NumPy, focusing on 2D convolution concepts such as slicing, broadcasting, and filter application.
Implement 2D convolution on a 4×4 input and a 3×3 filter with stride 1 using NumPy. Avoid explicit Python loops by relying on array slicing, broadcasting, or vectorization. Return the resulting 2×2 output array.
Compute 2D Convolution of a 4x4 Matrix with a 3x3 Kernel in SQL
You are given a 4x4 input matrix and a 3x3 convolution kernel, each stored as separate tables in row/column form. Implement a valid 2D convolution with stride 1 in SQL.
Definitions:
- The input matrix is 4x4, with rows and columns indexed from 1 to 4.
- The kernel (filter) is 3x3, with rows and columns indexed from 1 to 3.
- Use valid convolution with stride 1 (no padding), so the top-left of the kernel can start at positions (1,1), (1,2), (2,1), and (2,2) on the input.
- For an output position (out_row, out_col), the convolution value is: SUM over kernel_row = 1..3 and kernel_col = 1..3 of input_value(out_row + kernel_row - 1, out_col + kernel_col - 1) * kernel_weight(kernel_row, kernel_col)
Write a SQL query that returns the 2x2 output of this convolution as 4 rows with columns:
- out_row (INT)
- out_col (INT)
- conv_value (INT)
Use the provided tables and sample data below.
Table input_matrix
| column | type | constraints |
|---|---|---|
| row_idx | INT | NOT NULL |
| col_idx | INT | NOT NULL |
| value | INT | NOT NULL |
Sample data:
| col_idx | row_idx | value |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 0 |
| 1 | 2 | 0 |
| 2 | 2 | 1 |
| 3 | 2 | 2 |
| 4 | 2 | 3 |
| 1 | 3 | 3 |
| 2 | 3 | 0 |
| 3 | 3 | 1 |
| 4 | 3 | 2 |
| 1 | 4 | 2 |
| 2 | 4 | 3 |
| 3 | 4 | 0 |
| 4 | 4 | 1 |
Table kernel
| column | type | constraints |
|---|---|---|
| kernel_row | INT | NOT NULL |
| kernel_col | INT | NOT NULL |
| weight | INT | NOT NULL |
Sample data:
| kernel_col | kernel_row | weight |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 0 |
| 3 | 1 | 2 |
| 1 | 2 | 0 |
| 2 | 2 | 1 |
| 3 | 2 | 0 |
| 1 | 3 | 3 |
| 2 | 3 | 0 |
| 3 | 3 | 1 |
Expected output
The query should return one row per valid output position of the 2x2 convolution result. Each row contains the output coordinates (out_row, out_col) and the corresponding convolution value (conv_value) computed as the sum of elementwise products of the overlapping 3x3 patch from input_matrix with the kernel weights.
| conv_value | out_col | out_row |
|---|---|---|
| 18 | 1 | 1 |
| 6 | 2 | 1 |
| 10 | 1 | 2 |
| 18 | 2 | 2 |
Hints
- Generate the 4 valid output positions (out_row, out_col) using a VALUES clause or a small derived table.
- Join the kernel to the input_matrix by shifting input indices with (out_row + kernel_row - 1, out_col + kernel_col - 1), then aggregate the product of value and weight.