Skip to content
fn

pad

→Tensor
pad(input: Tensor, pad: Sequence[int], mode: str = 'constant', value: float | None = None)

Implementing kernel

C++ engine symbols that back this Python API.

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. This is Lucid's one pad: there is no lucid.pad or Tensor.pad.

Parameters

inputTensor
Input tensor of any rank N.
padSequence 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. A negative entry removes that many entries from its side instead.
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= None
Fill value used only when mode == "constant".

Returns

Tensor

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

Raises

lucid._C.engine.NotImplementedError
An unknown mode.
lucid._C.engine.InvalidArgument
A pad of odd length or longer than 2·N, a reflection as wide as its dim, a circular pad wider than it, a replicated empty dim, or negative pads that remove more than a dim holds. Both a RuntimeError, as the reference raises, and a ValueError.

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, dtype=lucid.float32).reshape(1, 1, 2, 3)
>>> y = pad(x, (1, 1, 0, 0), mode="reflect")
>>> y.shape                    # last dim grows by 2
(1, 1, 2, 5)
>>> pad(lucid.arange(4.0), (-1, 2)).tolist()
[1.0, 2.0, 3.0, 0.0, 0.0]

Used by 4