Skip to content
class

GridSampleBackward

GridSampleBackward

Python wrappers

Public Python APIs implemented by this engine symbol.

Autograd node for differentiable image resampling (grid sample).

Reads a 4-D input image at the (typically non-integer) positions specified by a sampling grid:

y[n,c,i,j]=I(xn,c,  grid[n,i,j]) y[n, c, i, j] = \mathcal{I}\bigl(x_{n, c}, \; \text{grid}[n, i, j]\bigr)

where I\mathcal{I} is the chosen interpolation kernel and the grid stores normalised (x,y)(x, y) coordinates in [−1,1][-1, 1]. For bilinear interpolation the four neighbouring pixels around the unnormalised coordinate u=(x+1)⋅(Win−1)/2u = (x + 1) \cdot (W_{\text{in}} - 1) / 2, v=(y+1)⋅(Hin−1)/2v = (y + 1) \cdot (H_{\text{in}} - 1) / 2 (under align_corners_=true) are combined with the standard bilinear weights; analogous neighbourhoods of four (nearest) or sixteen (bicubic) pixels are used in the other modes.

Out-of-bounds samples are handled by padding_mode_: zeros returns 00, border clamps the source coordinate, reflection reflects it off the image boundary. The backward distributes grad_out back to both the input pixels (through the interpolation weights) and the grid (through the analytical derivative of the interpolation kernel).

Math

Coordinate unnormalisation:

u={(x+1)(Win−1)/2align_corners(x+1)Win/2−0.5otherwise u = \begin{cases} (x + 1) (W_{\text{in}} - 1) / 2 & \text{align\_corners} \\ (x + 1) W_{\text{in}} / 2 - 0.5 & \text{otherwise} \end{cases}

(analogous formula for vv).

References

Jaderberg et al., "Spatial Transformer Networks" (NeurIPS 2015).

Attributes

schema_v1OpSchema
"grid_sample", AmpPolicy::Promote.
mode_int
Interpolation kernel: 0 = bilinear, 1 = nearest.
padding_mode_int
Out-of-bounds policy: 0 = zeros, 1 = border.
align_corners_bool
Coordinate mapping mode (see file header).
input_shape_Shape
Saved (N, C, H_in, W_in) for backward reconstruction.
grid_shape_Shape
Saved (N, H_out, W_out, 2) for backward reconstruction.

Static methods

1
static

forward

→TensorImplPtr
int forward(const int & input, const int & grid, int mode, int padding_mode, bool align_corners)

Resample input at the positions specified by grid.

Parameters

inputTensorImplPtr
4-D input image of shape (N, C, H_in, W_in).
gridTensorImplPtr
Sampling grid of shape (N, H_out, W_out, 2) with normalised coordinates in [−1,1][-1, 1].
modeint
Interpolation kernel code (0/1 for bilinear/nearest).
padding_modeint
Out-of-bounds policy code (0/1 for zeros/border).
align_cornersbool
Coordinate mapping mode.

Returns

TensorImplPtr

Resampled tensor of shape (N, C, H_out, W_out).

Methods

2
fn

apply

int apply(int grad_out)

Backward pass: gradients w.r.t. input and grid.

fn

apply_for_graph

int apply_for_graph(const int & grad_out)

Graph-mode backward: the kernel's adjoint written in ops — gathers, scatter-adds and the bilinear weights — so it can be differentiated again, in the input and the grid alike.