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 square where is the kernel size (the stride defaults to , 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:
- Divide the input into overlapping or non-overlapping kernel windows.
- For each window, find the maximum value and its corresponding index.
- Store the index for later use in unpooling operations. The index is the maximum's position in its channel's flattened input plane, i.e. (an integer tensor).
This technique is widely used in image segmentation tasks.
Example
input: [[[[1, 2], [3, 4]]]] # 1×1×2×2 kernel_size = 2
(tensor([[[[4.]]]]), tensor([[[[3]]]]))
- Input:
xis a tensor holding withkernel_size. - Windows: with stride , each side yields window, so the whole image is one window.
- Value: , 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 . Indices are integers, hence
3with no decimal point. - Shape: both tensors are ; batch and channel pass through untouched.
- Notice the index counts positions in the whole input plane, not inside the window: for a input holding , the bottom-right window's maximum 15 is at row 3, column 3, giving index — 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