.. meta::
    :description: Sample input at the grid's normalized coordinates, as torch.nn.functional.grid_sample for 4-D input.
    :date-modified: 11/30/2026

.. currentmodule:: nkilib.experimental.vision

Grid Sample Kernel API Reference
================================

Sample input at the grid's normalized coordinates, as torch.nn.functional.grid_sample for 4-D input.

Any coordinates are exact (no displacement bound): the input is first rewritten into an HBM scratch in channels-last order with a zero border, and every chunk of output pixels fetches its samples with batched indirect DMA gathers (software DGE, 128 x cols rows per instruction). For bilinear samples the scratch normally holds each pixel's 2 x 2 neighbourhood, so a sample is one contiguous row of 4 C elements; the bilinear weights then blend the four taps on the vector engine. An input much larger than the output, or whose neighbourhood scratch would pass 2 GiB or not fit SBUF's tiles, gathers the four taps from the padded image instead, and a one-channel input there is read directly, without a scratch (see _plan_grid_sample). Padding modes act on the source coordinates (border clamps, reflection reflects then clamps); zeros relies on the zero border, onto which coordinates outside [-1, size] are clamped. Coordinates follow ATen's fp32 operation order; reflection is exact for source coordinates within 2^23 pixels of the input (beyond, where fp32 holds no fraction, they saturate at that distance). Scratch rows (the gathered entries) are indexed in fp32 below 2^24 per batch; past it (6K images and up) each index is a row base exact in fp32 plus a column, added in integer arithmetic: an input is rejected only when its padded height reaches 2^24 or its scratch 2^32 entries per batch, an output from 2^31 pixels per batch. A chunk stores each channel's consecutive output pixels as runs; when it has more channels than gathered rows per partition, the Tensor Engine first transposes it channel-major (bit-exact), so that each channel leaves in one run. Small batches share chunks, which then store into a channel-major staging buffer that one copy moves to the output. Sampling is software-pipelined over up to 8 tile sets (as many as fit SBUF): a chunk's coordinates, scratch rows and gather run up to 7 chunks ahead of its blend and store. A program of at most 512 chunks runs them unrolled; beyond, each segment's steady state runs in a device loop. With LNC=2 each program builds its own scratch of the batches it samples and takes half of a single batch's chunks, or half of the batches that share chunks.

Background
-----------

``grid_sample`` samples ``input`` at the normalized coordinates in ``grid``, matching ``torch.nn.functional.grid_sample`` for 4-D input, with bilinear or nearest sampling and the zeros, border, and reflection padding modes. The companion ``grid_sample_supported`` reports on the host whether a given call is handled by the kernel.

API Reference
--------------

**Source code for this kernel API can be found at**: `grid_sample.py <https://github.com/aws-neuron/nki-library/blob/2.34/src/nkilib_src/nkilib/experimental/vision/grid_sample.py>`_

grid_sample
^^^^^^^^^^^

.. py:function:: grid_sample(input: nl.NkiTensor, grid: nl.NkiTensor, mode: str = 'bilinear', padding_mode: str = 'zeros', align_corners: bool = False) -> nl.NkiTensor

   Sample input at the grid's normalized coordinates, as torch.nn.functional.grid_sample for 4-D input.

   :param input: [N, C, H, W], float32, bfloat16 or float16.
   :type input: ``nl.NkiTensor``
   :param grid: [N, Ho, Wo, 2], normalized (x, y) sample coordinates (-1 and 1 are the input's edges), the dtype of input.
   :type grid: ``nl.NkiTensor``
   :param mode: "bilinear" or "nearest" (round half to even, as torch).
   :type mode: ``str``
   :param padding_mode: "zeros", "border" or "reflection".
   :type padding_mode: ``str``
   :param align_corners: As torch: True maps -1 and 1 to the centers of the corner pixels, False to their outer edges.
   :type align_corners: ``bool``
   :return: [N, C, Ho, Wo] in input's dtype.
   :rtype: ``nl.NkiTensor``

   **Dimensions**:

   * N: Batch size

grid_sample_supported
^^^^^^^^^^^^^^^^^^^^^

.. py:function:: grid_sample_supported(input_shape: tuple[int, ...], grid_shape: tuple[int, ...], dtype: str, mode: str, padding_mode: str, platform_target: str, grid_dtype: Optional[str] = None) -> bool

   Whether grid_sample accepts a call, decided on the host without tracing the kernel: the checks grid_sample makes while tracing, so that a caller (torch-neuronx's grid_sampler_2d decomposition) can route the call to the kernel or keep its own decomposition. True does not say that the kernel is the faster choice.

   :param input_shape: The input's shape, [N, C, H, W].
   :type input_shape: ``tuple[int, ...]``
   :param grid_shape: The grid's shape, [N, Ho, Wo, 2].
   :type grid_shape: ``tuple[int, ...]``
   :param dtype: The input's dtype name: "float32", "bfloat16" or "float16".
   :type dtype: ``str``
   :param mode: grid_sample's mode, "bilinear" or "nearest".
   :type mode: ``str``
   :param padding_mode: grid_sample's padding_mode, "zeros", "border" or "reflection".
   :type padding_mode: ``str``
   :param platform_target: The Neuron platform the call compiles for, as torch-neuronx's get_platform_target() names it ("trn1", "trn2", "trn3"). grid_sample runs on trn2 only.
   :type platform_target: ``str``
   :param grid_dtype: The grid's dtype name. None means the input's.
   :type grid_dtype: ``Optional[str]``
   :return: Whether grid_sample accepts the call.
   :rtype: ``nl.NkiTensor``

