cswork / libraryOpen practice workspace

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

columntypeconstraints
row_idxINTNOT NULL
col_idxINTNOT NULL
valueINTNOT NULL

Sample data:

col_idxrow_idxvalue
111
212
313
410
120
221
322
423
133
230
331
432
142
243
340
441

Table kernel

columntypeconstraints
kernel_rowINTNOT NULL
kernel_colINTNOT NULL
weightINTNOT NULL

Sample data:

kernel_colkernel_rowweight
111
210
312
120
221
320
133
230
331

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_valueout_colout_row
1811
621
1012
1822

Hints

  1. Generate the 4 valid output positions (out_row, out_col) using a VALUES clause or a small derived table.
  2. 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.