class

ReflectionPad2d

extendsModule
ReflectionPad2d(padding: int | tuple[int, int, int, int])
source

Pad a 4-D tensor (N, C, H, W) by reflecting at all four spatial edges.

Reflection padding mirrors the pixel values at each boundary, producing a smooth, artefact-free extension of the image. This is particularly effective for convolutional image processing tasks where constant-value borders would introduce ringing or aliasing.

The reflected value at an out-of-bounds index ii (with respect to input size SS and left-pad pp) is:

output[,i]=x[,  ip](i<p)\text{output}[\dots, i] = x[\dots,\; |i - p|] \quad (i < p)

Parameters

paddingint or tuple[int, int, int, int]
(left, right, top, bottom) reflection padding sizes. Each value must be strictly less than the corresponding spatial input size. A single int pads equally on all four sides.

Attributes

paddingtuple[int, int, int, int]
Normalised (left, right, top, bottom) padding.

Notes

  • Input: (N,C,H,W)(N, C, H, W).
  • Output: (N,C,H+ptop+pbottom,W+pleft+pright)(N, C, H + p_{\text{top}} + p_{\text{bottom}}, W + p_{\text{left}} + p_{\text{right}}).
  • Widely used in Neural Style Transfer and image-to-image translation architectures (e.g. Johnson et al., 2016) to avoid border colour bleeding caused by zero padding.

Examples

**Style-transfer encoder with reflection padding:**
>>> import lucid
>>> import lucid.nn as nn
>>>
>>> pad = nn.ReflectionPad2d(padding=3)
>>> conv = nn.Conv2d(3, 64, kernel_size=7)
>>> x = lucid.zeros(1, 3, 256, 256)
>>> conv(pad(x)).shape
(1, 64, 256, 256)    # 256 + 2*3 - 6 = 256 (same-size output)
**Asymmetric reflection:**
>>> pad = nn.ReflectionPad2d(padding=(1, 2, 0, 3))
>>> x = lucid.zeros(2, 8, 32, 32)
>>> pad(x).shape
(2, 8, 35, 35)

Methods (3)

dunder

__init__

None
__init__(padding: int | tuple[int, int, int, int])
source

Initialise the ReflectionPad2d module. See the class docstring for parameter semantics.

fn

forward

Tensor
forward(x: Tensor)
source

Pad the input tensor according to the configured padding.

Parameters

inputTensor
Input tensor of shape (N,C,)(N, C, *).

Returns

Tensor

Padded tensor with spatial dimensions expanded by the configured padding amounts.

fn

extra_repr

str
extra_repr()
source

Return a string representation of the layer's configuration.