v9.1.1
Menu

Implement Max Pooling with Indices

Implement max pooling that returns both pooled values and indices for unpooling, a crucial component in CNNs, particularly in encoder-decoder architectures. This operation is essential for preserving spatial information.

Max pooling is a downsampling technique that reduces spatial dimensions by taking the maximum value across each kernel window, a k×kk \times k square where kk is the kernel size (the stride defaults to kk, so the windows tile the input without overlapping). The forward pass involves iterating over the input, applying the max pooling operation to each window.

Here are the key steps:

  1. Divide the input into overlapping or non-overlapping kernel windows.
  2. For each window, find the maximum value and its corresponding index.
  3. Store the index for later use in unpooling operations. The index is the maximum's position in its channel's flattened H×WH \times W input plane, i.e. row⋅W+col\text{row} \cdot W + \text{col} (an integer tensor).
max⁡i,j∈windowxi,j\max_{i, j \in \text{window}} x_{i, j}

This technique is widely used in image segmentation tasks.

Example

Input
input: [[[[1, 2], [3, 4]]]]  # 1×1×2×2
kernel_size = 2
Output
(tensor([[[[4.]]]]), tensor([[[[3]]]]))
Reasoning
  • Input: x is a 1×1×2×21 \times 1 \times 2 \times 2 tensor holding (1234)\begin{pmatrix}1 & 2\\ 3 & 4\end{pmatrix} with kernel_size k=2k = 2.
  • Windows: with stride kk, each side yields ⌊2/2⌋=1\lfloor 2/2 \rfloor = 1 window, so the whole image is one window.
  • Value: max⁡{1,2,3,4}=4\max\{1, 2, 3, 4\} = 4, kept as a float (4.) because the input is floating point.
  • Index: the 4 sits at row 1, column 1 of the input plane. Read row by row, its position is 1⋅W+1=1⋅2+1=31 \cdot W + 1 = 1 \cdot 2 + 1 = 3. Indices are integers, hence 3 with no decimal point.
  • Shape: both tensors are 1×1×1×11 \times 1 \times 1 \times 1; batch and channel pass through untouched.
  • Notice the index counts positions in the whole input plane, not inside the window: for a 4×44 \times 4 input holding 0,…,150, \dots, 15, the bottom-right window's maximum 15 is at row 3, column 3, giving index 3⋅4+3=153 \cdot 4 + 3 = 15 — exactly where unpooling must put it back.

Constraints

  • input: Tensor (batch, channels, H, W)
  • kernel_size: Pooling window size
  • Return: (pooled_output, indices) both same shape as output

Learn this in

More from CV: Deep Learning

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.