Pad and crop a feature map

A convolution pads both sides of a dimension by the same amount. zeroPadding2d and cropping2d change each side of a [N, C, H, W] feature map on its own.

DSL entry What it does

zeroPadding2d(left, right, top, bottom)

Adds that many columns or rows of zeros to each side. zeroPadding2d(1) adds one on every side.

cropping2d(left, right, top, bottom)

Removes that many columns or rows from each side. cropping2d(1) removes one on every side.

The order of the sides is that of pad2d: left, right, top, bottom.

val model = sequential<FP32, Float>(ctx) {
    input(intArrayOf(3, 32, 32))
    zeroPadding2d(left = 0, right = 1, top = 0, bottom = 1)   // (3, 33, 33)
    conv2d(outChannels = 16, kernelSize = 2 to 2)             // (16, 32, 32): the size is kept
    cropping2d(2)                                             // (16, 28, 28)
}

Typical uses: keeping the size with an even kernel, as above; padding for a stride of 2 the way TensorFlow’s same does (more on the right and the bottom); cutting a border off before two branches of different size are merged.

Outside the DSL the layers are ZeroPadding2d and Cropping2d in sk.ainet.lang.nn, and the functions are tensor.pad2d(left, right, top, bottom) and tensor.crop2d(left, right, top, bottom).

Padding is the pad2d operation and cropping is two narrow operations, so neither needs a kernel of its own. Values and gradients are held to PyTorch by suite TS-017 of skainet-ground-truth.