TorchedUp
ProblemsPremium
TorchedUp
PyTorch: Conv2D Forward PassHard
ProblemsPremium

PyTorch: Conv2D Forward Pass

Implement a Conv2D forward pass using PyTorch's built-in torch.nn.functional.conv2d.

Signature: def conv2d_forward_backward(x, weight, bias, stride=1, padding=0)

  • x: input tensor of shape (N, C_in, H, W)
  • weight: filter tensor (C_out, C_in, kH, kW)
  • bias: bias tensor (C_out,)
  • stride: convolution stride (default 1)
  • padding: zero-padding size (default 0)
  • Returns: output of the convolution as a nested list

Use torch.nn.functional.conv2d for the forward pass. The output shape is (N, C_out, H_out, W_out) where H_out = (H + 2*padding - kH) // stride + 1.

Example:

x = [[[[1,1,1],[1,1,1],[1,1,1]]]]  # (1,1,3,3)
w = [[[[1,1],[1,1]]]]              # (1,1,2,2)
b = [0.0]
# Output shape: (1,1,2,2), each position sums 4 ones = 4.0

Math

Asked at

Python (numpy)0/3 runs today

Test Results

○1×1×3×3 all-ones, 2×2 all-ones filter
○difference filter on linear input
○stride=2, padding=1, 3×3 all-ones filter on 4×4 all-ones
○identity filter extracts single pixel🔒 Premium
Advertisement