Skip to content
fn

unfold

→Tensor
unfold(input: Tensor, kernel_size: int | tuple[int, int], dilation: int | tuple[int, int] = 1, padding: int | tuple[int, int] = 0, stride: int | tuple[int, int] = 1)

Implementing kernel

C++ engine symbols that back this Python API.

Extract sliding local blocks (im2col) from a 4-D or unbatched 3-D tensor.

Slides a (kH, kW) window across the spatial extent of input (with given stride, padding, and dilation) and flattens each window into a column of the output. This is the classical im2col operation — convolution can be written as unfold + matmul + fold.

The number of output locations is

L=∏d⌊Sin,d+2pd−dd(kd−1)−1sd⌋+1L = \prod_d \left\lfloor \frac{S_{\mathrm{in},d} + 2 p_d - d_d (k_d - 1) - 1}{s_d} \right\rfloor + 1

where dd indexes spatial dims and s,p,k,ds, p, k, d are stride / padding / kernel / dilation respectively.

Parameters

inputTensor
Input of shape (N, C, H, W), or (C, H, W) unbatched.
kernel_sizeint or (int, int)
Spatial size of the sliding window.
dilationint or (int, int)= 1
Spacing between elements within a window. Default 1.
paddingint or (int, int)= 0
Implicit zero padding applied symmetrically on both sides.
strideint or (int, int)= 1
Step between successive windows. Default 1.

Returns

Tensor

Tensor of shape (N, C·kH·kW, L), or (C·kH·kW, L) for an unbatched input.

Notes

The inverse, fold, sums overlapping blocks back into an image. fold(unfold(x)) == x only when stride equals kernel size and padding is zero — otherwise overlapping windows produce higher counts at interior pixels.

Examples

>>> import lucid
>>> from lucid.nn.functional import unfold
>>> x = lucid.randn(1, 3, 8, 8)
>>> u = unfold(x, kernel_size=3, stride=1, padding=1)
>>> u.shape                        # (N, C·kH·kW, L) = (1, 27, 64)
(1, 27, 64)

Used by 2