torch.nn.ReflectionPad2d
class ReflectionPad2d extends Modulenew ReflectionPad2d(padding: Padding2D)
- readonly
padding([number, number, number, number])
2D reflection padding: pads by reflecting images at boundaries.
Extends 2D spatial data (images) by reflecting at edges. Mirrors both height and width dimensions independently. Produces smooth borders without black corners (vs zero padding). Essential for:
- Image preprocessing (avoids black border artifacts)
- Style transfer/image-to-image translation (smooth boundaries)
- Object detection with conv networks (reduces edge artifacts)
- Computer vision tasks sensitive to image boundaries
- Maintaining spatial coherence at image edges
2D reflection mirrors both spatial dimensions: for a 3x3 image with padding=1, corners reflect diagonally creating seamless border extension.
When to use ReflectionPad2d:
- Image processing (avoids artificial black borders)
- Style transfer models (reflection maintains visual continuity)
- CNNs expecting smooth image boundaries
- Tasks where boundary artifacts matter
- Semantic segmentation near edges
Trade-offs:
- vs ZeroPad2d: Reflection smoother; zero padding causes black borders
- vs ReplicationPad2d: Reflection avoids edge repetition patterns
- vs CircularPad2d: Reflection asymmetric; circular for periodic content
- Computation: Slightly more complex than zero padding
Reflection mechanics (2D): For image [a b c; d e f; g h i] with padding=1:
- Each corner reflects diagonally
- Each edge reflects across boundary
- Creates smooth grid pattern without repetition
- Diagonal reflection: Corners reflect diagonally (not independently per dimension)
- Smooth transitions: All pixels have natural continuity at boundaries
- Height/width independent: Each dimension reflects independently
- No learnable params: Pure deterministic transformation
- Common in CNNs: Used in many state-of-the-art image models
- Padding limit: Cannot pad more than (height/width - 1) on any side
- Corner behavior: Diagonal reflection can create interesting patterns
- Small images: Very small images may show obvious mirroring
Examples
// Simple image padding
const pad = new torch.nn.ReflectionPad2d(1);
const img = torch.randn([32, 3, 224, 224]); // [batch, channels, height, width]
const padded = pad.forward(img); // [32, 3, 226, 226]// Asymmetric padding (more on bottom/right)
const pad = new torch.nn.ReflectionPad2d([2, 3, 1, 2]); // [left, right, top, bottom]
const img = torch.randn([16, 3, 128, 128]);
const padded = pad.forward(img); // [16, 3, 131, 133]// Style transfer: avoiding black corners
const pad = new torch.nn.ReflectionPad2d(3);
const content_img = torch.randn([1, 3, 256, 256]);
const padded = pad.forward(content_img); // [1, 3, 262, 262]
// Process with style transfer network
// No black corners from zero padding affecting perceptual loss