fn

pad

Tensor
pad(x: Tensor, padding: tuple[int, ...], mode: str = 'constant', value: float = 0.0)
source

Pad an N-D tensor along an arbitrary set of trailing dimensions.

Generalises np.pad with several boundary modes useful in deep learning: zero/constant fill, mirror reflection, edge replication, and circular wrap-around.

Parameters

xTensor
Input tensor of any rank N.
paddingtuple of int
Flat padding spec starting from the last dimension, in (left, right) pairs. For example:
  • (l, r) pads only the last dim,
  • (l, r, t, b) pads the last two dims (last with (l, r), second-to-last with (t, b)),
  • (l, r, t, b, f, k) extends the pattern to three dims.
Length must be even and at most 2·N.
modestr= 'constant'
One of:
  • "constant" (default): fill with value.
  • "reflect": mirror around the boundary, excluding the boundary itself (so size-1 along a padded dim is illegal).
  • "replicate": repeat the edge element.
  • "circular": wrap around (toroidal boundary conditions).
valuefloat= 0.0
Fill value used only when mode == "constant".

Returns

Tensor

Padded tensor with each padded dim d enlarged by padding[2·k] + padding[2·k+1] where k is its offset from the last dim.

Notes

Non-constant modes are decomposed into gather + concat in Python, relying on existing autograd machinery (gather's scatter-add backward correctly accumulates gradients for reflected / replicated entries). "reflect" requires pad_amount <= size - 1 on each side; "circular" requires pad_amount <= size.

Examples

>>> import lucid
>>> from lucid.nn.functional import pad
>>> x = lucid.arange(6).reshape(1, 1, 2, 3).astype(lucid.float32)
>>> y = pad(x, (1, 1, 0, 0), mode="reflect")
>>> y.shape                    # last dim grows by 2
(1, 1, 2, 5)