Skip to content

NEON implementation of interpolate for {bilinear, bicubic} x {antialias=(True, False)} on ChannelsLast RGB images - #176217

Closed
NicolasHug wants to merge 7 commits into
pytorch:mainfrom
NicolasHug:neon_interpolate_bilinear_antialias
Closed

NicolasHug wants to merge 7 commits into
pytorch:mainfrom
NicolasHug:neon_interpolate_bilinear_antialias

Conversation

@NicolasHug

@NicolasHug NicolasHug commented Mar 2, 2026 •

Copy link
Copy Markdown
Member

This is a NEON implementation of torch.nn.functional.interpolate. It is ~3X - 6X faster than the existing generic implementation (see benchmarks below), while remaining bitwise equivalent.

It supports:

  • bilinear and bicubic modes, both with antialias=True and antialias=False.
  • CPU only (NEON)
  • Channels Last tensors only (tensors that aren't channels-last will fallback to the existing "generic" implementation). This is fine and consistent: the torchvision image decoders almost always output CL images.
  • RGB images only, i.e. NCHW images where C == 3. This is by far the most relevant case.

It is based on the existing AVX2 implementation and follows the same ideas/patterns, with some key differences that are due to the different instruction sets. The NEON one is generally a lot simpler.


Testing

This PR is just adding a new transparent dispatch to a new implementation for a functionality that already exists, and that is already tested. So in theory, if the CI is green, it means the new implem is fine. That's however assuming that the existing testing coverage of torch.nn.functional.interpolate is adequate. To be on the safe side, here are some separate tests I ran locally on an aarch64 CPU.

I'm testing the new implementation against the existing generic implementation, which is triggered on channels-first inputs. All results are bitwise equivalent.

Details
"""Tests for NEON-optimized uint8 resize in F.interpolate.

The reference is F.interpolate on a contiguous (channels-first) tensor.
We compare against the channels-last path which should hit the NEON kernels
on aarch64.
"""

import torch
import pytest


RESOLUTIONS = [
    (64, 64),
    (320, 480),
    (720, 1280),
    (2160, 3840),
]

SCALE_FACTORS = [0.25, 0.5, 0.75, 1.5, 2.0, 4.0]

MODES = ["bilinear", "bicubic"]

ANTIALIAS_VALUES = [True, False]


def reference(x, output_size, mode, antialias):
    # The ref is the non-NEON path, which is always triggered on channels-first
    # tensors.
    x_cf = x.contiguous()
    return torch.nn.functional.interpolate(
        x_cf,
        size=output_size,
        mode=mode,
        antialias=antialias,
    )


def run_cl(x, output_size, mode, antialias):
    x_cl = x.contiguous(memory_format=torch.channels_last)
    return torch.nn.functional.interpolate(
        x_cl,
        size=output_size,
        mode=mode,
        antialias=antialias,
    )


def check(x, output_size, mode, antialias):
    ref = reference(x, output_size, mode, antialias)
    out = run_cl(x, output_size, mode, antialias)
    torch.testing.assert_close(out, ref, atol=0, rtol=0)


@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("scale", SCALE_FACTORS, ids=[f"x{s}" for s in SCALE_FACTORS])
@pytest.mark.parametrize(
    "resolution", RESOLUTIONS, ids=[f"{h}x{w}" for h, w in RESOLUTIONS]
)
def test_resolutions_and_scales(resolution, scale, mode, antialias):
    h, w = resolution
    oh, ow = max(1, int(h * scale)), max(1, int(w * scale))
    torch.manual_seed(42)
    x = torch.randint(0, 256, (1, 3, h, w), dtype=torch.uint8)
    check(x, (oh, ow), mode, antialias)


@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize(
    "shape,out_size",
    [
        ((1, 3, 64, 32), (32, 64)),
        ((1, 3, 100, 75), (50, 40)),
        ((1, 3, 37, 53), (71, 29)),
        ((1, 3, 123, 77), (91, 103)),
        ((1, 3, 45, 67), (89, 23)),
    ],
    ids=[
        "64x32->32x64",
        "100x75->50x40",
        "37x53->71x29",
        "123x77->91x103",
        "45x67->89x23",
    ],
)
def test_asymmetric(shape, out_size, mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, shape, dtype=torch.uint8)
    check(x, out_size, mode, antialias)


@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize(
    "shape,out_size",
    [
        ((1, 3, 2, 2), (4, 4)),
        ((1, 3, 4, 4), (8, 8)),
        ((1, 3, 4, 4), (2, 2)),
        ((1, 3, 3, 5), (7, 3)),
        ((1, 3, 5, 5), (5, 5)),
    ],
    ids=["2x2->4x4", "4x4->8x8", "4x4->2x2", "3x5->7x3", "5x5->5x5"],
)
def test_small(shape, out_size, mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, shape, dtype=torch.uint8)
    check(x, out_size, mode, antialias)


@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize(
    "shape,out_size",
    [
        ((1, 3, 13, 17), (19, 23)),
        ((1, 3, 31, 47), (11, 59)),
        ((1, 3, 97, 61), (53, 41)),
    ],
    ids=["13x17->19x23", "31x47->11x59", "97x61->53x41"],
)
def test_odd_sizes(shape, out_size, mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, shape, dtype=torch.uint8)
    check(x, out_size, mode, antialias)


@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("out_size", [(16, 16), (32, 32)], ids=["->16x16", "->32x32"])
def test_large_downscale(out_size, mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, (1, 3, 256, 256), dtype=torch.uint8)
    check(x, out_size, mode, antialias)


@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
def test_batch(mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, (4, 3, 64, 64), dtype=torch.uint8)
    check(x, (32, 48), mode, antialias)


@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
def test_horizontal_only(mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, (1, 3, 64, 64), dtype=torch.uint8)
    check(x, (64, 128), mode, antialias)


@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
def test_vertical_only(mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, (1, 3, 64, 64), dtype=torch.uint8)
    check(x, (128, 64), mode, antialias)
~/dev/pytorch (neon_interpolate_bilinear_antialias*) ยป pytest neon_interpolate/test_neon_upsample.py -v
============================================================================ test session starts =============================================================================
platform linux -- Python 3.10.19, pytest-9.0.2, pluggy-1.6.0 -- /home/nicolashug/.conda/envs/torch/bin/python3.10
cachedir: .pytest_cache
rootdir: /home/nicolashug/dev/pytorch
configfile: pytest.ini
collected 168 items                                                                                                                                                          

neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.25-bilinear-aa=True] PASSED                                                               [  0%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.25-bilinear-aa=False] PASSED                                                              [  1%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.25-bicubic-aa=True] PASSED                                                                [  1%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.25-bicubic-aa=False] PASSED                                                               [  2%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.5-bilinear-aa=True] PASSED                                                                [  2%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.5-bilinear-aa=False] PASSED                                                               [  3%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.5-bicubic-aa=True] PASSED                                                                 [  4%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.5-bicubic-aa=False] PASSED                                                                [  4%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.75-bilinear-aa=True] PASSED                                                               [  5%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.75-bilinear-aa=False] PASSED                                                              [  5%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.75-bicubic-aa=True] PASSED                                                                [  6%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.75-bicubic-aa=False] PASSED                                                               [  7%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x1.5-bilinear-aa=True] PASSED                                                                [  7%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x1.5-bilinear-aa=False] PASSED                                                               [  8%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x1.5-bicubic-aa=True] PASSED                                                                 [  8%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x1.5-bicubic-aa=False] PASSED                                                                [  9%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x2.0-bilinear-aa=True] PASSED                                                                [ 10%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x2.0-bilinear-aa=False] PASSED                                                               [ 10%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x2.0-bicubic-aa=True] PASSED                                                                 [ 11%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x2.0-bicubic-aa=False] PASSED                                                                [ 11%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x4.0-bilinear-aa=True] PASSED                                                                [ 12%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x4.0-bilinear-aa=False] PASSED                                                               [ 13%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x4.0-bicubic-aa=True] PASSED                                                                 [ 13%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x4.0-bicubic-aa=False] PASSED                                                                [ 14%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.25-bilinear-aa=True] PASSED                                                             [ 14%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.25-bilinear-aa=False] PASSED                                                            [ 15%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.25-bicubic-aa=True] PASSED                                                              [ 16%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.25-bicubic-aa=False] PASSED                                                             [ 16%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.5-bilinear-aa=True] PASSED                                                              [ 17%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.5-bilinear-aa=False] PASSED                                                             [ 17%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.5-bicubic-aa=True] PASSED                                                               [ 18%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.5-bicubic-aa=False] PASSED                                                              [ 19%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.75-bilinear-aa=True] PASSED                                                             [ 19%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.75-bilinear-aa=False] PASSED                                                            [ 20%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.75-bicubic-aa=True] PASSED                                                              [ 20%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.75-bicubic-aa=False] PASSED                                                             [ 21%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x1.5-bilinear-aa=True] PASSED                                                              [ 22%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x1.5-bilinear-aa=False] PASSED                                                             [ 22%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x1.5-bicubic-aa=True] PASSED                                                               [ 23%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x1.5-bicubic-aa=False] PASSED                                                              [ 23%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x2.0-bilinear-aa=True] PASSED                                                              [ 24%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x2.0-bilinear-aa=False] PASSED                                                             [ 25%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x2.0-bicubic-aa=True] PASSED                                                               [ 25%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x2.0-bicubic-aa=False] PASSED                                                              [ 26%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x4.0-bilinear-aa=True] PASSED                                                              [ 26%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x4.0-bilinear-aa=False] PASSED                                                             [ 27%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x4.0-bicubic-aa=True] PASSED                                                               [ 27%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x4.0-bicubic-aa=False] PASSED                                                              [ 28%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.25-bilinear-aa=True] PASSED                                                            [ 29%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.25-bilinear-aa=False] PASSED                                                           [ 29%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.25-bicubic-aa=True] PASSED                                                             [ 30%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.25-bicubic-aa=False] PASSED                                                            [ 30%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.5-bilinear-aa=True] PASSED                                                             [ 31%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.5-bilinear-aa=False] PASSED                                                            [ 32%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.5-bicubic-aa=True] PASSED                                                              [ 32%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.5-bicubic-aa=False] PASSED                                                             [ 33%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.75-bilinear-aa=True] PASSED                                                            [ 33%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.75-bilinear-aa=False] PASSED                                                           [ 34%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.75-bicubic-aa=True] PASSED                                                             [ 35%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.75-bicubic-aa=False] PASSED                                                            [ 35%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x1.5-bilinear-aa=True] PASSED                                                             [ 36%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x1.5-bilinear-aa=False] PASSED                                                            [ 36%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x1.5-bicubic-aa=True] PASSED                                                              [ 37%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x1.5-bicubic-aa=False] PASSED                                                             [ 38%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x2.0-bilinear-aa=True] PASSED                                                             [ 38%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x2.0-bilinear-aa=False] PASSED                                                            [ 39%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x2.0-bicubic-aa=True] PASSED                                                              [ 39%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x2.0-bicubic-aa=False] PASSED                                                             [ 40%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x4.0-bilinear-aa=True] PASSED                                                             [ 41%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x4.0-bilinear-aa=False] PASSED                                                            [ 41%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x4.0-bicubic-aa=True] PASSED                                                              [ 42%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x4.0-bicubic-aa=False] PASSED                                                             [ 42%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.25-bilinear-aa=True] PASSED                                                           [ 43%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.25-bilinear-aa=False] PASSED                                                          [ 44%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.25-bicubic-aa=True] PASSED                                                            [ 44%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.25-bicubic-aa=False] PASSED                                                           [ 45%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.5-bilinear-aa=True] PASSED                                                            [ 45%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.5-bilinear-aa=False] PASSED                                                           [ 46%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.5-bicubic-aa=True] PASSED                                                             [ 47%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.5-bicubic-aa=False] PASSED                                                            [ 47%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.75-bilinear-aa=True] PASSED                                                           [ 48%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.75-bilinear-aa=False] PASSED                                                          [ 48%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.75-bicubic-aa=True] PASSED                                                            [ 49%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.75-bicubic-aa=False] PASSED                                                           [ 50%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x1.5-bilinear-aa=True] PASSED                                                            [ 50%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x1.5-bilinear-aa=False] PASSED                                                           [ 51%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x1.5-bicubic-aa=True] PASSED                                                             [ 51%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x1.5-bicubic-aa=False] PASSED                                                            [ 52%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x2.0-bilinear-aa=True] PASSED                                                            [ 52%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x2.0-bilinear-aa=False] PASSED                                                           [ 53%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x2.0-bicubic-aa=True] PASSED                                                             [ 54%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x2.0-bicubic-aa=False] PASSED                                                            [ 54%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x4.0-bilinear-aa=True] PASSED                                                            [ 55%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x4.0-bilinear-aa=False] PASSED                                                           [ 55%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x4.0-bicubic-aa=True] PASSED                                                             [ 56%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x4.0-bicubic-aa=False] PASSED                                                            [ 57%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[64x32->32x64-bilinear-aa=True] PASSED                                                                          [ 57%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[64x32->32x64-bilinear-aa=False] PASSED                                                                         [ 58%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[64x32->32x64-bicubic-aa=True] PASSED                                                                           [ 58%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[64x32->32x64-bicubic-aa=False] PASSED                                                                          [ 59%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[100x75->50x40-bilinear-aa=True] PASSED                                                                         [ 60%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[100x75->50x40-bilinear-aa=False] PASSED                                                                        [ 60%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[100x75->50x40-bicubic-aa=True] PASSED                                                                          [ 61%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[100x75->50x40-bicubic-aa=False] PASSED                                                                         [ 61%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[37x53->71x29-bilinear-aa=True] PASSED                                                                          [ 62%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[37x53->71x29-bilinear-aa=False] PASSED                                                                         [ 63%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[37x53->71x29-bicubic-aa=True] PASSED                                                                           [ 63%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[37x53->71x29-bicubic-aa=False] PASSED                                                                          [ 64%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[123x77->91x103-bilinear-aa=True] PASSED                                                                        [ 64%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[123x77->91x103-bilinear-aa=False] PASSED                                                                       [ 65%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[123x77->91x103-bicubic-aa=True] PASSED                                                                         [ 66%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[123x77->91x103-bicubic-aa=False] PASSED                                                                        [ 66%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[45x67->89x23-bilinear-aa=True] PASSED                                                                          [ 67%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[45x67->89x23-bilinear-aa=False] PASSED                                                                         [ 67%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[45x67->89x23-bicubic-aa=True] PASSED                                                                           [ 68%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[45x67->89x23-bicubic-aa=False] PASSED                                                                          [ 69%]
neon_interpolate/test_neon_upsample.py::test_small[2x2->4x4-bilinear-aa=True] PASSED                                                                                   [ 69%]
neon_interpolate/test_neon_upsample.py::test_small[2x2->4x4-bilinear-aa=False] PASSED                                                                                  [ 70%]
neon_interpolate/test_neon_upsample.py::test_small[2x2->4x4-bicubic-aa=True] PASSED                                                                                    [ 70%]
neon_interpolate/test_neon_upsample.py::test_small[2x2->4x4-bicubic-aa=False] PASSED                                                                                   [ 71%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->8x8-bilinear-aa=True] PASSED                                                                                   [ 72%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->8x8-bilinear-aa=False] PASSED                                                                                  [ 72%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->8x8-bicubic-aa=True] PASSED                                                                                    [ 73%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->8x8-bicubic-aa=False] PASSED                                                                                   [ 73%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->2x2-bilinear-aa=True] PASSED                                                                                   [ 74%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->2x2-bilinear-aa=False] PASSED                                                                                  [ 75%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->2x2-bicubic-aa=True] PASSED                                                                                    [ 75%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->2x2-bicubic-aa=False] PASSED                                                                                   [ 76%]
neon_interpolate/test_neon_upsample.py::test_small[3x5->7x3-bilinear-aa=True] PASSED                                                                                   [ 76%]
neon_interpolate/test_neon_upsample.py::test_small[3x5->7x3-bilinear-aa=False] PASSED                                                                                  [ 77%]
neon_interpolate/test_neon_upsample.py::test_small[3x5->7x3-bicubic-aa=True] PASSED                                                                                    [ 77%]
neon_interpolate/test_neon_upsample.py::test_small[3x5->7x3-bicubic-aa=False] PASSED                                                                                   [ 78%]
neon_interpolate/test_neon_upsample.py::test_small[5x5->5x5-bilinear-aa=True] PASSED                                                                                   [ 79%]
neon_interpolate/test_neon_upsample.py::test_small[5x5->5x5-bilinear-aa=False] PASSED                                                                                  [ 79%]
neon_interpolate/test_neon_upsample.py::test_small[5x5->5x5-bicubic-aa=True] PASSED                                                                                    [ 80%]
neon_interpolate/test_neon_upsample.py::test_small[5x5->5x5-bicubic-aa=False] PASSED                                                                                   [ 80%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[13x17->19x23-bilinear-aa=True] PASSED                                                                           [ 81%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[13x17->19x23-bilinear-aa=False] PASSED                                                                          [ 82%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[13x17->19x23-bicubic-aa=True] PASSED                                                                            [ 82%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[13x17->19x23-bicubic-aa=False] PASSED                                                                           [ 83%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[31x47->11x59-bilinear-aa=True] PASSED                                                                           [ 83%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[31x47->11x59-bilinear-aa=False] PASSED                                                                          [ 84%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[31x47->11x59-bicubic-aa=True] PASSED                                                                            [ 85%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[31x47->11x59-bicubic-aa=False] PASSED                                                                           [ 85%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[97x61->53x41-bilinear-aa=True] PASSED                                                                           [ 86%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[97x61->53x41-bilinear-aa=False] PASSED                                                                          [ 86%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[97x61->53x41-bicubic-aa=True] PASSED                                                                            [ 87%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[97x61->53x41-bicubic-aa=False] PASSED                                                                           [ 88%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->16x16-bilinear-aa=True] PASSED                                                                          [ 88%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->16x16-bilinear-aa=False] PASSED                                                                         [ 89%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->16x16-bicubic-aa=True] PASSED                                                                           [ 89%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->16x16-bicubic-aa=False] PASSED                                                                          [ 90%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->32x32-bilinear-aa=True] PASSED                                                                          [ 91%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->32x32-bilinear-aa=False] PASSED                                                                         [ 91%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->32x32-bicubic-aa=True] PASSED                                                                           [ 92%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->32x32-bicubic-aa=False] PASSED                                                                          [ 92%]
neon_interpolate/test_neon_upsample.py::test_batch[bilinear-aa=True] PASSED                                                                                            [ 93%]
neon_interpolate/test_neon_upsample.py::test_batch[bilinear-aa=False] PASSED                                                                                           [ 94%]
neon_interpolate/test_neon_upsample.py::test_batch[bicubic-aa=True] PASSED                                                                                             [ 94%]
neon_interpolate/test_neon_upsample.py::test_batch[bicubic-aa=False] PASSED                                                                                            [ 95%]
neon_interpolate/test_neon_upsample.py::test_horizontal_only[bilinear-aa=True] PASSED                                                                                  [ 95%]
neon_interpolate/test_neon_upsample.py::test_horizontal_only[bilinear-aa=False] PASSED                                                                                 [ 96%]
neon_interpolate/test_neon_upsample.py::test_horizontal_only[bicubic-aa=True] PASSED                                                                                   [ 97%]
neon_interpolate/test_neon_upsample.py::test_horizontal_only[bicubic-aa=False] PASSED                                                                                  [ 97%]
neon_interpolate/test_neon_upsample.py::test_vertical_only[bilinear-aa=True] PASSED                                                                                    [ 98%]
neon_interpolate/test_neon_upsample.py::test_vertical_only[bilinear-aa=False] PASSED                                                                                   [ 98%]
neon_interpolate/test_neon_upsample.py::test_vertical_only[bicubic-aa=True] PASSED                                                                                     [ 99%]
neon_interpolate/test_neon_upsample.py::test_vertical_only[bicubic-aa=False] PASSED                                                                                    [100%]

============================================================================ 168 passed in 6.59s =============================================================================


Benchmarking

TL;DR: BRRRRRRRRRRRRRRRRRRRRRRRRRR

NEON implementation is ~4X - 6X faster than the existing one on relevant cases, and generally at least 2X faster.
(EDIT: with #177637 merged, the 3X speedup reported below are now closer to 4X)

Speedup (generic / NEON) for different img resolutions and scaling factors

BILINEAR, ANTIALIAS=TRUE
           x0.25      x0.5     x0.75      x1.5      x2.0      x4.0
------------------------------------------------------------------
 64x64      1.97x      2.09x      2.60x      3.59x      4.23x      5.85x
  320p      3.51x      2.77x      3.35x      4.40x      4.94x      6.42x
  720p      3.71x      2.83x      3.45x      4.48x      4.95x      6.33x
    4K      3.76x      2.80x      3.46x      4.46x      5.04x      6.28x


BILINEAR, ANTIALIAS=FALSE
           x0.25      x0.5     x0.75      x1.5      x2.0      x4.0
------------------------------------------------------------------
 64x64      1.50x      2.05x      2.48x      3.72x      4.44x      6.11x
  320p      2.44x      2.92x      3.36x      4.41x      4.97x      6.46x
  720p      2.40x      2.99x      3.43x      4.53x      4.93x      6.47x
    4K      2.52x      2.95x      3.42x      4.55x      4.96x      6.32x

BICUBIC, ANTIALIAS=TRUE
           x0.25      x0.5     x0.75      x1.5      x2.0      x4.0
------------------------------------------------------------------
 64x64      2.29x      2.49x      2.42x      3.43x      3.91x      5.06x
  320p      4.09x      4.05x      2.84x      3.85x      4.31x      5.32x
  720p      4.27x      4.28x      2.90x      3.90x      4.30x      5.16x
    4K      4.28x      4.12x      2.94x      4.05x      4.29x      5.30x

BICUBIC, ANTIALIAS=FALSE
           x0.25      x0.5     x0.75      x1.5      x2.0      x4.0
------------------------------------------------------------------
 64x64      1.60x      2.10x      2.48x      3.46x      3.91x      4.95x
  320p      2.37x      2.77x      3.09x      3.90x      4.33x      5.33x
  720p      2.55x      2.84x      3.17x      3.94x      4.29x      5.19x
    4K      2.39x      2.86x      3.25x      4.06x      4.36x      5.54x

Code and details:

Details

Note that this is using an env variable to force the generic path, see f9a5c87

"""Benchmark uint8 bilinear/bicubic resize: NEON (channels-last) vs generic (channels-first)."""

import torch
from time import perf_counter_ns


def bench(f, *args, num_exp=9, warmup=1, **kwargs):
    for _ in range(warmup):
        f(*args, **kwargs)
    times = []
    for _ in range(num_exp):
        start = perf_counter_ns()
        f(*args, **kwargs)
        end = perf_counter_ns()
        times.append(end - start)
    return torch.tensor(times).float()


resolutions = [
    ("64x64", (1, 3, 64, 64)),
    ("320p", (1, 3, 320, 480)),
    ("720p", (1, 3, 720, 1280)),
    ("4K", (1, 3, 2160, 3840)),
]
scale_factors = [0.25, 0.5, 0.75, 1.5, 2.0, 4.0]
modes = ["bilinear", "bicubic"]
antialias_values = [True, False]


if __name__ == "__main__":
    torch.set_num_threads(1)
    interpolate = torch.nn.functional.interpolate

    col = 10
    header = f"{'':>6}" + "".join(f"{'x' + str(sf):>{col}}" for sf in scale_factors)

    for mode in modes:
        for antialias in antialias_values:
            aa_label = "aa" if antialias else "no-aa"
            cf_results = {}
            cl_results = {}

            for name, shape in resolutions:
                for sf in scale_factors:
                    oh = max(1, int(shape[2] * sf))
                    ow = max(1, int(shape[3] * sf))
                    torch.manual_seed(42)
                    x = torch.randint(0, 256, shape, dtype=torch.uint8)

                    x_cf = x.contiguous()
                    t = bench(interpolate, x_cf, size=(oh, ow), mode=mode, antialias=antialias)
                    cf_results[(name, sf)] = t.median().item() * 1e-6

                    x_cl = x.contiguous(memory_format=torch.channels_last)
                    t = bench(interpolate, x_cl, size=(oh, ow), mode=mode, antialias=antialias)
                    cl_results[(name, sf)] = t.median().item() * 1e-6

            for label, results in [("Channels-first", cf_results), ("Channels-last", cl_results)]:
                print(f"\n{mode} {aa_label} ({label}, ms)")
                print(header)
                print("-" * len(header))
                for name, _ in resolutions:
                    row = f"{name:>6}"
                    for sf in scale_factors:
                        row += f"{results[(name, sf)]:>{col}.2f}"
                    print(row)

            print(f"\nSpeedup (channels-first / channels-last)")
            print(header)
            print("-" * len(header))
            for name, _ in resolutions:
                row = f"{name:>6}"
                for sf in scale_factors:
                    speedup = cf_results[(name, sf)] / cl_results[(name, sf)]
                    row += f"{speedup:>{col}.2f}x"
                print(row)
            print()
~/dev/pytorch (neon_interpolate_bilinear_antialias*) ยป lscpu                                                                                                                                                                                                                     nicolashug@devgpu026
Architecture:             aarch64
  CPU op-mode(s):         64-bit
  Byte Order:             Little Endian
CPU(s):                   144
  On-line CPU(s) list:    0-143
Vendor ID:                ARM
  Model name:             Neoverse-V2
    Model:                0
    Thread(s) per core:   1
    Core(s) per socket:   72
    Socket(s):            2
    Stepping:             r0p0
    Frequency boost:      disabled
    CPU(s) scaling MHz:   100%
    CPU max MHz:          3393.0000
    CPU min MHz:          81.0000
    BogoMIPS:             2000.00
    Flags:                fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh
Caches (sum of all):      
  L1d:                    9 MiB (144 instances)
  L1i:                    9 MiB (144 instances)
  L2:                     144 MiB (144 instances)
  L3:                     228 MiB (2 instances)
NUMA:                     
  NUMA node(s):           18
  NUMA node0 CPU(s):      0-71
  NUMA node1 CPU(s):      72-143
  NUMA node2 CPU(s):      
  NUMA node3 CPU(s):      
  NUMA node4 CPU(s):      
  NUMA node5 CPU(s):      
  NUMA node6 CPU(s):      
  NUMA node7 CPU(s):      
  NUMA node8 CPU(s):      
  NUMA node9 CPU(s):      
  NUMA node10 CPU(s):     
  NUMA node11 CPU(s):     
  NUMA node12 CPU(s):     
  NUMA node13 CPU(s):     
  NUMA node14 CPU(s):     
  NUMA node15 CPU(s):     
  NUMA node16 CPU(s):     
  NUMA node17 CPU(s):     
Vulnerabilities:          
  Gather data sampling:   Not affected
  Itlb multihit:          Not affected
  L1tf:                   Not affected
  Mds:                    Not affected
  Meltdown:               Not affected
  Mmio stale data:        Not affected
  Reg file data sampling: Not affected
  Retbleed:               Not affected
  Spec rstack overflow:   Not affected
  Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
  Spectre v1:             Mitigation; __user pointer sanitization
  Spectre v2:             Not affected
  Srbds:                  Not affected
  Tsx async abort:        Not affected

cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @jerryzh168 @aditew01

@pytorch-bot

pytorch-bot Bot commented Mar 2, 2026 •

Copy link
Copy Markdown

๐Ÿ”— Helpful Links

๐Ÿงช See artifacts and rendered test results at hud.pytorch.org/pr/176217

Note: Links to docs will display an error until the docs builds have been completed.

โŒ 1 New Failure

As of commit f9a5c87 with merge base 3621675 (image):

NEW FAILURE - The following job has failed:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added the module: cpu CPU specific problem (e.g., perf, algorithm) label Mar 2, 2026
@pytorch-bot

pytorch-bot Bot commented Mar 2, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@NicolasHug NicolasHug changed the title [WIP] NEON implem of interpolate(mode="bilinear", antialias=True) [WIP] NEON implementation of interpolate for {bilinear, bicubic} x {antialias=(True, False)} for ChannelsLast RGB images. Mar 3, 2026
output, input, align_corners, {scales_h, scales_w},
/*antialias=*/false);
}
#elif defined(__aarch64__)

@NicolasHug NicolasHug Mar 3, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that we just check for __aarch64__ and not for NEON support because all __aarch64__ CPUs must support NEON.

Those #ifdef-based dispatches are ugly, but they follow the current pattern that exists for CPU_CAPABILITY_AVX2 (see just above).

@NicolasHug NicolasHug added the release notes: nn release notes category label Mar 3, 2026
@NicolasHug NicolasHug changed the title [WIP] NEON implementation of interpolate for {bilinear, bicubic} x {antialias=(True, False)} for ChannelsLast RGB images. NEON implementation of interpolate for {bilinear, bicubic} x {antialias=(True, False)} on ChannelsLast RGB images Mar 3, 2026
@NicolasHug
NicolasHug marked this pull request as ready for review March 3, 2026 11:29
@meta-codesync

meta-codesync Bot commented Mar 3, 2026

Copy link
Copy Markdown

@NicolasHug has imported this pull request. If you are a Meta employee, you can view this in D95049079.

@malfet malfet added the ciflow/trunk Trigger trunk jobs on your pull request label Mar 3, 2026
@malfet

malfet commented Mar 3, 2026

Copy link
Copy Markdown
Collaborator

@claude review this and see if veclib primitives could have been used here

@claude

claude Bot commented Mar 3, 2026 •

Copy link
Copy Markdown

Claude finished @malfet's task in 3m 16s โ€”โ€” View job


  • Read the new NEON kernel implementation
  • Read the dispatch changes in UpSampleKernel.cpp
  • Read the existing AVX2 implementation for comparison
  • Analyze whether vecLib/Accelerate primitives could be used
  • Post comprehensive review

Code Review

The implementation is clean and well-structured. The NEON intrinsics are used correctly, and the code is genuinely simpler than the AVX2 counterpart (no RGBA packing/unpacking, cleaner deinterleaving via vld3_u8). A few observations:

Minor issues in UpSampleKernelNEONAntialias.h:

  1. Horizontal pass processes only 1 row at a time (line 64-134). The AVX2 path has a 4x variant (ImagingResampleHorizontalConvolution8u4x) that processes 4 rows simultaneously for better ILP. This could be a future optimization opportunity for the NEON path โ€” not a blocker, but worth noting as the horizontal pass may become the bottleneck for tall narrow images.

  2. Vertical pass: vshlq_s32 for right-shift (line 240-244). This works correctly (negative shift value = right shift), but a reader might expect vshrq_n_s32 instead. The dynamic shift via vshlq_s32 is necessary here since vert_weights_precision is a runtime value, so this is correct โ€” just noting it's not immediately obvious.

  3. neon_madd_s16 uses vpaddq_s32 (line 27). This produces [a0*b0+a1*b1, a2*b2+a3*b3, a4*b4+a5*b5, a6*b6+a7*b7] โ€” 4 partially-reduced int32 results. The naming and comment are accurate, and the semantics match SSE _mm_madd_epi16. Correct.

Dispatch in UpSampleKernel.cpp:

  1. Inconsistent #ifdef pattern across the 4 dispatch sites. Three of the four use #elif defined(__aarch64__) (bilinear, bilinear_aa, bicubic), but upsample_bicubic2d_aa_kernel_impl uses a different nesting pattern: #else / #if defined(__aarch64__) / #endif / { fallback }. This is functionally equivalent but stylistically inconsistent. I'd suggest unifying them all to use #elif for readability, though this is cosmetic.

Overall: The implementation looks correct and well-commented. The NEON intrinsic choices are appropriate for the target operations.


vecLib Analysis

TL;DR: vecLib primitives would not be useful here, and are not available on the target platform.

The request was whether Apple's vecLib (Accelerate framework) primitives could replace the hand-written NEON intrinsics. There are several reasons this wouldn't work:

1. Platform availability: Apple's Accelerate framework (vecLib, vDSP, vImage, BNNS) is macOS/iOS-only. This code targets __aarch64__ broadly, which includes Linux aarch64 (e.g., AWS Graviton, the Neoverse-V2 in the benchmarks). vecLib is simply not available there.

2. vDSP is float-only: vDSP convolution functions (vDSP_conv, vDSP_imgfir) operate on float/double arrays. This kernel uses integer-only arithmetic: uint8 โ†’ int16 ร— int16 โ†’ int32 โ†’ shift โ†’ uint8. Converting to float and back would:

  • Add conversion overhead that defeats the purpose of the optimization
  • Break bitwise equivalence with the generic path (different rounding)

3. vImage doesn't fit: vImage does have vImageScale_* functions for uint8 images, but:

  • No native 3-channel (RGB) format support โ€” only Planar8 or ARGB8888
  • Black-box implementation โ€” cannot control filter coefficients, fixed-point precision, or rounding to match PyTorch's existing behavior
  • Bitwise equivalence would be impossible to guarantee
  • API mismatch: vImage operates on whole images, not separable H/V passes

4. The NEON approach is correct: For integer fixed-point convolution with per-pixel variable-length kernels, direct NEON intrinsics are the right tool. The key advantage of NEON here is vld3_u8 which directly deinterleaves RGB โ€” this is cleaner than what AVX2 can do (which requires the RGBA packing/unpacking dance).


Comment on lines +293 to +296
if (xin == xout && yin == yout) {
output.copy_(input_);
return;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not need to be here

@malfet

malfet commented Mar 3, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@malfet

malfet commented Mar 3, 2026

Copy link
Copy Markdown
Collaborator

@claude review this code and see if any of the neon intrinsics can be replaced with abstractions from aten/src/ATen/cpu/vec

@claude

claude Bot commented Mar 3, 2026 •

Copy link
Copy Markdown

Claude finished @malfet's task in 3m 19s โ€”โ€” View job


  • Read the NEON kernel implementation
  • Read the dispatch changes in UpSampleKernel.cpp
  • Explore aten/src/ATen/cpu/vec abstractions for aarch64
  • Analyze which intrinsics could be replaced with vec abstractions
  • Post review findings

Analysis: NEON Intrinsics vs aten/src/ATen/cpu/vec Abstractions

I went through every NEON intrinsic used in UpSampleKernelNEONAntialias.h and checked whether it has a corresponding abstraction in aten/src/ATen/cpu/vec. Here's the summary:

Short answer: very few of the intrinsics can be replaced, and the ones that can would not meaningfully improve the code.


Intrinsics that could be replaced with vec abstractions

Intrinsic Used in Vec equivalent Worth it?
vdupq_n_s32(0) Accumulator init (lines 87-89, 190-193) Vectorized<int32_t>(0) constructor Marginal โ€” saves nothing, same code generated
vaddq_s32(a, b) Accumulator update (lines 218-221) Vectorized<int32_t> a + b Marginal โ€” the types surrounding it are raw NEON anyway
vld1q_u8(ptr) Vertical pass load (lines 208-209, 228) Vectorized<uint8_t>::loadu(ptr) Marginal โ€” and you'd immediately need to extract the raw uint8x16_t back out
vld1q_s16(ptr) Horizontal pass weights load (line 100) Vectorized<int16_t>::loadu(ptr) Same issue โ€” need the raw int16x8_t for subsequent operations
vaddvq_s32(acc) Horizontal reduction (lines 115-117) Vectorized<int32_t>(acc).reduce_add() Possible but requires wrapping/unwrapping
vdupq_n_s16(val) Broadcast weight (line 226) Vectorized<int16_t>(val) Marginal

Intrinsics with no vec abstraction

These are the intrinsics that form the core of the kernel and have no equivalent in the vec library:

Intrinsic Purpose Why no abstraction
vld3_u8 Interleaved RGB load + deinterleave The vec library has no structure-load support. This is the single most important optimization in the horizontal pass โ€” it loads 8 RGB pixels and deinterleaves into separate R/G/B vectors in one instruction. No portable abstraction can express this.
vmovl_u8 Widen uint8x8 โ†’ uint16x8 No widening conversion in vec for sub-register-width inputs. The VecConvert infrastructure exists but goes uint8โ†’float, not uint8โ†’int16.
vmull_s16 Widening multiply int16ร—int16 โ†’ int32 Vec has operator* for same-width multiply (vmulq_s16), but no widening multiply. The distinction is critical: vmull produces int32x4_t from int16x4_t inputs, preventing overflow.
vmlal_s16 Widening multiply-accumulate Same as above โ€” no vec equivalent for widening MAC.
vzipq_u8 Interleave bytes from two rows No interleave/deinterleave primitives in vec.
vpaddq_s32 Pairwise add (used in neon_madd_s16) No pairwise/horizontal add in vec. reduce_add() does full reduction, not pairwise.
vqmovn_s32 Saturating narrow int32 โ†’ int16 No narrowing operations in vec.
vqmovun_s16 Saturating narrow signed int16 โ†’ unsigned uint8 No narrowing operations in vec.
vshlq_s32 with negative shift Variable right-shift of accumulators Vec has operator>> but it takes Vectorized<int32_t> as the shift count, not a negative-valued left-shift. Different semantics.
vget_low_s16 / vget_high_s16 Extract half-register for widening ops No sub-register extraction in vec.
vcombine_s16 Combine two half-registers No combine primitive in vec.
vst1_u8 (64-bit store) Store 8 bytes (half a register) Vec store() always stores full register width (128 bits).

Why the vec abstraction is a poor fit here

The Vectorized<T> abstraction in aten/src/ATen/cpu/vec is designed for same-width, element-parallel operations: load N elements, do arithmetic, store N elements, all at the same type width. It works well for float-to-float or int32-to-int32 compute.

This interpolation kernel fundamentally relies on cross-width operations: uint8 input โ†’ widen to int16 โ†’ widening multiply to int32 โ†’ accumulate in int32 โ†’ narrow back to int16 โ†’ narrow to uint8 output. Every step in this pipeline changes the element width, and the vec abstraction has no support for:

  1. Widening loads/multiplies (vmovl, vmull, vmlal) โ€” the core of fixed-point accumulation
  2. Saturating narrows (vqmovn, vqmovun) โ€” the core of output conversion
  3. Structure loads (vld3) โ€” the core of channel deinterleaving
  4. Half-register operations (vget_low, vget_high, vcombine) โ€” needed because widening doubles the element count

Wrapping the few replaceable intrinsics (vdupq_n_s32, vaddq_s32) in Vectorized<T> would mean constantly converting between Vectorized<T> and raw NEON types at every boundary. The code would be harder to read, not easier.

Conclusion

The raw NEON intrinsics are the right choice here. The vec abstractions don't cover the operations that matter for this kernel (widening arithmetic, structure loads, saturating narrows), and replacing the few that overlap would add type-conversion noise without improving portability or readability.


@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-rocm-py3.10 / test (distributed, 3, 3, linux.rocm.gpu.gfx950.4)

Details for Dev Infra team Raised by workflow job

@malfet

malfet commented Mar 3, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -f "Mac + AARCH64 tests are green"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

EmanueleCoradin pushed a commit to EmanueleCoradin/pytorch that referenced this pull request Mar 30, 2026
โ€ฆalias=(True, False)}` on ChannelsLast RGB images (pytorch#176217)

This is a NEON implementation of `torch.nn.functional.interpolate`. **It is ~3X - 6X faster than the existing generic implementation** (see benchmarks below), while **remaining bitwise equivalent**.

It supports:

- `bilinear` and `bicubic` modes, both with `antialias=True` and `antialias=False`.
- CPU only (NEON)
- Channels Last tensors only (tensors that aren't channels-last will fallback to the existing "generic" implementation). This is fine and consistent: the `torchvision` image decoders almost always output CL images.
- RGB images only, i.e. `NCHW` images where C == 3. This is *by far* the most relevant case.

It is based on the [existing AVX2](https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/cpu/UpSampleKernelAVXAntialias.h) implementation and follows the same ideas/patterns, with some key differences that are due to the different instruction sets. The NEON one is generally a lot simpler.

----

### Testing

This PR is just adding a new transparent dispatch to a new implementation for a functionality that already exists, and that is already tested. So in theory, if the CI is green, it means the new implem is fine. That's however assuming that the existing testing coverage of `torch.nn.functional.interpolate` is adequate. To be on the safe side, here are some separate tests I ran locally on an aarch64 CPU.

I'm testing the new implementation against the existing generic implementation, which is triggered on channels-first inputs. **All results are bitwise equivalent.**

<details>

```py
"""Tests for NEON-optimized uint8 resize in F.interpolate.

The reference is F.interpolate on a contiguous (channels-first) tensor.
We compare against the channels-last path which should hit the NEON kernels
on aarch64.
"""

import torch
import pytest

RESOLUTIONS = [
    (64, 64),
    (320, 480),
    (720, 1280),
    (2160, 3840),
]

SCALE_FACTORS = [0.25, 0.5, 0.75, 1.5, 2.0, 4.0]

MODES = ["bilinear", "bicubic"]

ANTIALIAS_VALUES = [True, False]

def reference(x, output_size, mode, antialias):
    # The ref is the non-NEON path, which is always triggered on channels-first
    # tensors.
    x_cf = x.contiguous()
    return torch.nn.functional.interpolate(
        x_cf,
        size=output_size,
        mode=mode,
        antialias=antialias,
    )

def run_cl(x, output_size, mode, antialias):
    x_cl = x.contiguous(memory_format=torch.channels_last)
    return torch.nn.functional.interpolate(
        x_cl,
        size=output_size,
        mode=mode,
        antialias=antialias,
    )

def check(x, output_size, mode, antialias):
    ref = reference(x, output_size, mode, antialias)
    out = run_cl(x, output_size, mode, antialias)
    torch.testing.assert_close(out, ref, atol=0, rtol=0)

@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("scale", SCALE_FACTORS, ids=[f"x{s}" for s in SCALE_FACTORS])
@pytest.mark.parametrize(
    "resolution", RESOLUTIONS, ids=[f"{h}x{w}" for h, w in RESOLUTIONS]
)
def test_resolutions_and_scales(resolution, scale, mode, antialias):
    h, w = resolution
    oh, ow = max(1, int(h * scale)), max(1, int(w * scale))
    torch.manual_seed(42)
    x = torch.randint(0, 256, (1, 3, h, w), dtype=torch.uint8)
    check(x, (oh, ow), mode, antialias)

@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize(
    "shape,out_size",
    [
        ((1, 3, 64, 32), (32, 64)),
        ((1, 3, 100, 75), (50, 40)),
        ((1, 3, 37, 53), (71, 29)),
        ((1, 3, 123, 77), (91, 103)),
        ((1, 3, 45, 67), (89, 23)),
    ],
    ids=[
        "64x32->32x64",
        "100x75->50x40",
        "37x53->71x29",
        "123x77->91x103",
        "45x67->89x23",
    ],
)
def test_asymmetric(shape, out_size, mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, shape, dtype=torch.uint8)
    check(x, out_size, mode, antialias)

@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize(
    "shape,out_size",
    [
        ((1, 3, 2, 2), (4, 4)),
        ((1, 3, 4, 4), (8, 8)),
        ((1, 3, 4, 4), (2, 2)),
        ((1, 3, 3, 5), (7, 3)),
        ((1, 3, 5, 5), (5, 5)),
    ],
    ids=["2x2->4x4", "4x4->8x8", "4x4->2x2", "3x5->7x3", "5x5->5x5"],
)
def test_small(shape, out_size, mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, shape, dtype=torch.uint8)
    check(x, out_size, mode, antialias)

@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize(
    "shape,out_size",
    [
        ((1, 3, 13, 17), (19, 23)),
        ((1, 3, 31, 47), (11, 59)),
        ((1, 3, 97, 61), (53, 41)),
    ],
    ids=["13x17->19x23", "31x47->11x59", "97x61->53x41"],
)
def test_odd_sizes(shape, out_size, mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, shape, dtype=torch.uint8)
    check(x, out_size, mode, antialias)

@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("out_size", [(16, 16), (32, 32)], ids=["->16x16", "->32x32"])
def test_large_downscale(out_size, mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, (1, 3, 256, 256), dtype=torch.uint8)
    check(x, out_size, mode, antialias)

@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
def test_batch(mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, (4, 3, 64, 64), dtype=torch.uint8)
    check(x, (32, 48), mode, antialias)

@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
def test_horizontal_only(mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, (1, 3, 64, 64), dtype=torch.uint8)
    check(x, (64, 128), mode, antialias)

@pytest.mark.parametrize("antialias", ANTIALIAS_VALUES, ids=lambda a: f"aa={a}")
@pytest.mark.parametrize("mode", MODES)
def test_vertical_only(mode, antialias):
    torch.manual_seed(42)
    x = torch.randint(0, 256, (1, 3, 64, 64), dtype=torch.uint8)
    check(x, (128, 64), mode, antialias)
```

```
~/dev/pytorch (neon_interpolate_bilinear_antialias*) ยป pytest neon_interpolate/test_neon_upsample.py -v
============================================================================ test session starts =============================================================================
platform linux -- Python 3.10.19, pytest-9.0.2, pluggy-1.6.0 -- /home/nicolashug/.conda/envs/torch/bin/python3.10
cachedir: .pytest_cache
rootdir: /home/nicolashug/dev/pytorch
configfile: pytest.ini
collected 168 items

neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.25-bilinear-aa=True] PASSED                                                               [  0%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.25-bilinear-aa=False] PASSED                                                              [  1%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.25-bicubic-aa=True] PASSED                                                                [  1%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.25-bicubic-aa=False] PASSED                                                               [  2%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.5-bilinear-aa=True] PASSED                                                                [  2%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.5-bilinear-aa=False] PASSED                                                               [  3%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.5-bicubic-aa=True] PASSED                                                                 [  4%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.5-bicubic-aa=False] PASSED                                                                [  4%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.75-bilinear-aa=True] PASSED                                                               [  5%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.75-bilinear-aa=False] PASSED                                                              [  5%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.75-bicubic-aa=True] PASSED                                                                [  6%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x0.75-bicubic-aa=False] PASSED                                                               [  7%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x1.5-bilinear-aa=True] PASSED                                                                [  7%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x1.5-bilinear-aa=False] PASSED                                                               [  8%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x1.5-bicubic-aa=True] PASSED                                                                 [  8%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x1.5-bicubic-aa=False] PASSED                                                                [  9%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x2.0-bilinear-aa=True] PASSED                                                                [ 10%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x2.0-bilinear-aa=False] PASSED                                                               [ 10%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x2.0-bicubic-aa=True] PASSED                                                                 [ 11%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x2.0-bicubic-aa=False] PASSED                                                                [ 11%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x4.0-bilinear-aa=True] PASSED                                                                [ 12%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x4.0-bilinear-aa=False] PASSED                                                               [ 13%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x4.0-bicubic-aa=True] PASSED                                                                 [ 13%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[64x64-x4.0-bicubic-aa=False] PASSED                                                                [ 14%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.25-bilinear-aa=True] PASSED                                                             [ 14%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.25-bilinear-aa=False] PASSED                                                            [ 15%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.25-bicubic-aa=True] PASSED                                                              [ 16%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.25-bicubic-aa=False] PASSED                                                             [ 16%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.5-bilinear-aa=True] PASSED                                                              [ 17%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.5-bilinear-aa=False] PASSED                                                             [ 17%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.5-bicubic-aa=True] PASSED                                                               [ 18%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.5-bicubic-aa=False] PASSED                                                              [ 19%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.75-bilinear-aa=True] PASSED                                                             [ 19%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.75-bilinear-aa=False] PASSED                                                            [ 20%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.75-bicubic-aa=True] PASSED                                                              [ 20%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x0.75-bicubic-aa=False] PASSED                                                             [ 21%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x1.5-bilinear-aa=True] PASSED                                                              [ 22%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x1.5-bilinear-aa=False] PASSED                                                             [ 22%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x1.5-bicubic-aa=True] PASSED                                                               [ 23%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x1.5-bicubic-aa=False] PASSED                                                              [ 23%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x2.0-bilinear-aa=True] PASSED                                                              [ 24%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x2.0-bilinear-aa=False] PASSED                                                             [ 25%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x2.0-bicubic-aa=True] PASSED                                                               [ 25%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x2.0-bicubic-aa=False] PASSED                                                              [ 26%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x4.0-bilinear-aa=True] PASSED                                                              [ 26%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x4.0-bilinear-aa=False] PASSED                                                             [ 27%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x4.0-bicubic-aa=True] PASSED                                                               [ 27%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[320x480-x4.0-bicubic-aa=False] PASSED                                                              [ 28%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.25-bilinear-aa=True] PASSED                                                            [ 29%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.25-bilinear-aa=False] PASSED                                                           [ 29%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.25-bicubic-aa=True] PASSED                                                             [ 30%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.25-bicubic-aa=False] PASSED                                                            [ 30%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.5-bilinear-aa=True] PASSED                                                             [ 31%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.5-bilinear-aa=False] PASSED                                                            [ 32%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.5-bicubic-aa=True] PASSED                                                              [ 32%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.5-bicubic-aa=False] PASSED                                                             [ 33%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.75-bilinear-aa=True] PASSED                                                            [ 33%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.75-bilinear-aa=False] PASSED                                                           [ 34%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.75-bicubic-aa=True] PASSED                                                             [ 35%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x0.75-bicubic-aa=False] PASSED                                                            [ 35%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x1.5-bilinear-aa=True] PASSED                                                             [ 36%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x1.5-bilinear-aa=False] PASSED                                                            [ 36%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x1.5-bicubic-aa=True] PASSED                                                              [ 37%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x1.5-bicubic-aa=False] PASSED                                                             [ 38%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x2.0-bilinear-aa=True] PASSED                                                             [ 38%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x2.0-bilinear-aa=False] PASSED                                                            [ 39%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x2.0-bicubic-aa=True] PASSED                                                              [ 39%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x2.0-bicubic-aa=False] PASSED                                                             [ 40%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x4.0-bilinear-aa=True] PASSED                                                             [ 41%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x4.0-bilinear-aa=False] PASSED                                                            [ 41%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x4.0-bicubic-aa=True] PASSED                                                              [ 42%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[720x1280-x4.0-bicubic-aa=False] PASSED                                                             [ 42%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.25-bilinear-aa=True] PASSED                                                           [ 43%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.25-bilinear-aa=False] PASSED                                                          [ 44%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.25-bicubic-aa=True] PASSED                                                            [ 44%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.25-bicubic-aa=False] PASSED                                                           [ 45%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.5-bilinear-aa=True] PASSED                                                            [ 45%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.5-bilinear-aa=False] PASSED                                                           [ 46%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.5-bicubic-aa=True] PASSED                                                             [ 47%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.5-bicubic-aa=False] PASSED                                                            [ 47%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.75-bilinear-aa=True] PASSED                                                           [ 48%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.75-bilinear-aa=False] PASSED                                                          [ 48%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.75-bicubic-aa=True] PASSED                                                            [ 49%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x0.75-bicubic-aa=False] PASSED                                                           [ 50%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x1.5-bilinear-aa=True] PASSED                                                            [ 50%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x1.5-bilinear-aa=False] PASSED                                                           [ 51%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x1.5-bicubic-aa=True] PASSED                                                             [ 51%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x1.5-bicubic-aa=False] PASSED                                                            [ 52%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x2.0-bilinear-aa=True] PASSED                                                            [ 52%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x2.0-bilinear-aa=False] PASSED                                                           [ 53%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x2.0-bicubic-aa=True] PASSED                                                             [ 54%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x2.0-bicubic-aa=False] PASSED                                                            [ 54%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x4.0-bilinear-aa=True] PASSED                                                            [ 55%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x4.0-bilinear-aa=False] PASSED                                                           [ 55%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x4.0-bicubic-aa=True] PASSED                                                             [ 56%]
neon_interpolate/test_neon_upsample.py::test_resolutions_and_scales[2160x3840-x4.0-bicubic-aa=False] PASSED                                                            [ 57%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[64x32->32x64-bilinear-aa=True] PASSED                                                                          [ 57%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[64x32->32x64-bilinear-aa=False] PASSED                                                                         [ 58%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[64x32->32x64-bicubic-aa=True] PASSED                                                                           [ 58%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[64x32->32x64-bicubic-aa=False] PASSED                                                                          [ 59%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[100x75->50x40-bilinear-aa=True] PASSED                                                                         [ 60%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[100x75->50x40-bilinear-aa=False] PASSED                                                                        [ 60%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[100x75->50x40-bicubic-aa=True] PASSED                                                                          [ 61%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[100x75->50x40-bicubic-aa=False] PASSED                                                                         [ 61%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[37x53->71x29-bilinear-aa=True] PASSED                                                                          [ 62%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[37x53->71x29-bilinear-aa=False] PASSED                                                                         [ 63%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[37x53->71x29-bicubic-aa=True] PASSED                                                                           [ 63%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[37x53->71x29-bicubic-aa=False] PASSED                                                                          [ 64%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[123x77->91x103-bilinear-aa=True] PASSED                                                                        [ 64%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[123x77->91x103-bilinear-aa=False] PASSED                                                                       [ 65%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[123x77->91x103-bicubic-aa=True] PASSED                                                                         [ 66%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[123x77->91x103-bicubic-aa=False] PASSED                                                                        [ 66%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[45x67->89x23-bilinear-aa=True] PASSED                                                                          [ 67%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[45x67->89x23-bilinear-aa=False] PASSED                                                                         [ 67%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[45x67->89x23-bicubic-aa=True] PASSED                                                                           [ 68%]
neon_interpolate/test_neon_upsample.py::test_asymmetric[45x67->89x23-bicubic-aa=False] PASSED                                                                          [ 69%]
neon_interpolate/test_neon_upsample.py::test_small[2x2->4x4-bilinear-aa=True] PASSED                                                                                   [ 69%]
neon_interpolate/test_neon_upsample.py::test_small[2x2->4x4-bilinear-aa=False] PASSED                                                                                  [ 70%]
neon_interpolate/test_neon_upsample.py::test_small[2x2->4x4-bicubic-aa=True] PASSED                                                                                    [ 70%]
neon_interpolate/test_neon_upsample.py::test_small[2x2->4x4-bicubic-aa=False] PASSED                                                                                   [ 71%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->8x8-bilinear-aa=True] PASSED                                                                                   [ 72%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->8x8-bilinear-aa=False] PASSED                                                                                  [ 72%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->8x8-bicubic-aa=True] PASSED                                                                                    [ 73%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->8x8-bicubic-aa=False] PASSED                                                                                   [ 73%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->2x2-bilinear-aa=True] PASSED                                                                                   [ 74%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->2x2-bilinear-aa=False] PASSED                                                                                  [ 75%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->2x2-bicubic-aa=True] PASSED                                                                                    [ 75%]
neon_interpolate/test_neon_upsample.py::test_small[4x4->2x2-bicubic-aa=False] PASSED                                                                                   [ 76%]
neon_interpolate/test_neon_upsample.py::test_small[3x5->7x3-bilinear-aa=True] PASSED                                                                                   [ 76%]
neon_interpolate/test_neon_upsample.py::test_small[3x5->7x3-bilinear-aa=False] PASSED                                                                                  [ 77%]
neon_interpolate/test_neon_upsample.py::test_small[3x5->7x3-bicubic-aa=True] PASSED                                                                                    [ 77%]
neon_interpolate/test_neon_upsample.py::test_small[3x5->7x3-bicubic-aa=False] PASSED                                                                                   [ 78%]
neon_interpolate/test_neon_upsample.py::test_small[5x5->5x5-bilinear-aa=True] PASSED                                                                                   [ 79%]
neon_interpolate/test_neon_upsample.py::test_small[5x5->5x5-bilinear-aa=False] PASSED                                                                                  [ 79%]
neon_interpolate/test_neon_upsample.py::test_small[5x5->5x5-bicubic-aa=True] PASSED                                                                                    [ 80%]
neon_interpolate/test_neon_upsample.py::test_small[5x5->5x5-bicubic-aa=False] PASSED                                                                                   [ 80%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[13x17->19x23-bilinear-aa=True] PASSED                                                                           [ 81%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[13x17->19x23-bilinear-aa=False] PASSED                                                                          [ 82%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[13x17->19x23-bicubic-aa=True] PASSED                                                                            [ 82%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[13x17->19x23-bicubic-aa=False] PASSED                                                                           [ 83%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[31x47->11x59-bilinear-aa=True] PASSED                                                                           [ 83%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[31x47->11x59-bilinear-aa=False] PASSED                                                                          [ 84%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[31x47->11x59-bicubic-aa=True] PASSED                                                                            [ 85%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[31x47->11x59-bicubic-aa=False] PASSED                                                                           [ 85%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[97x61->53x41-bilinear-aa=True] PASSED                                                                           [ 86%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[97x61->53x41-bilinear-aa=False] PASSED                                                                          [ 86%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[97x61->53x41-bicubic-aa=True] PASSED                                                                            [ 87%]
neon_interpolate/test_neon_upsample.py::test_odd_sizes[97x61->53x41-bicubic-aa=False] PASSED                                                                           [ 88%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->16x16-bilinear-aa=True] PASSED                                                                          [ 88%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->16x16-bilinear-aa=False] PASSED                                                                         [ 89%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->16x16-bicubic-aa=True] PASSED                                                                           [ 89%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->16x16-bicubic-aa=False] PASSED                                                                          [ 90%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->32x32-bilinear-aa=True] PASSED                                                                          [ 91%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->32x32-bilinear-aa=False] PASSED                                                                         [ 91%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->32x32-bicubic-aa=True] PASSED                                                                           [ 92%]
neon_interpolate/test_neon_upsample.py::test_large_downscale[->32x32-bicubic-aa=False] PASSED                                                                          [ 92%]
neon_interpolate/test_neon_upsample.py::test_batch[bilinear-aa=True] PASSED                                                                                            [ 93%]
neon_interpolate/test_neon_upsample.py::test_batch[bilinear-aa=False] PASSED                                                                                           [ 94%]
neon_interpolate/test_neon_upsample.py::test_batch[bicubic-aa=True] PASSED                                                                                             [ 94%]
neon_interpolate/test_neon_upsample.py::test_batch[bicubic-aa=False] PASSED                                                                                            [ 95%]
neon_interpolate/test_neon_upsample.py::test_horizontal_only[bilinear-aa=True] PASSED                                                                                  [ 95%]
neon_interpolate/test_neon_upsample.py::test_horizontal_only[bilinear-aa=False] PASSED                                                                                 [ 96%]
neon_interpolate/test_neon_upsample.py::test_horizontal_only[bicubic-aa=True] PASSED                                                                                   [ 97%]
neon_interpolate/test_neon_upsample.py::test_horizontal_only[bicubic-aa=False] PASSED                                                                                  [ 97%]
neon_interpolate/test_neon_upsample.py::test_vertical_only[bilinear-aa=True] PASSED                                                                                    [ 98%]
neon_interpolate/test_neon_upsample.py::test_vertical_only[bilinear-aa=False] PASSED                                                                                   [ 98%]
neon_interpolate/test_neon_upsample.py::test_vertical_only[bicubic-aa=True] PASSED                                                                                     [ 99%]
neon_interpolate/test_neon_upsample.py::test_vertical_only[bicubic-aa=False] PASSED                                                                                    [100%]

============================================================================ 168 passed in 6.59s =============================================================================

```

</details>

----

### Benchmarking

**TL;DR: BRRRRRRRRRRRRRRRRRRRRRRRRRR**

NEON implementation is ~3X - 6X faster than the existing one on relevant cases, and generally at least 2X faster.

```
Speedup (generic / NEON) for different img resolutions and scaling factors

BILINEAR, ANTIALIAS=TRUE
           x0.25      x0.5     x0.75      x1.5      x2.0      x4.0
------------------------------------------------------------------
 64x64      1.97x      2.09x      2.60x      3.59x      4.23x      5.85x
  320p      3.51x      2.77x      3.35x      4.40x      4.94x      6.42x
  720p      3.71x      2.83x      3.45x      4.48x      4.95x      6.33x
    4K      3.76x      2.80x      3.46x      4.46x      5.04x      6.28x

BILINEAR, ANTIALIAS=FALSE
           x0.25      x0.5     x0.75      x1.5      x2.0      x4.0
------------------------------------------------------------------
 64x64      1.50x      2.05x      2.48x      3.72x      4.44x      6.11x
  320p      2.44x      2.92x      3.36x      4.41x      4.97x      6.46x
  720p      2.40x      2.99x      3.43x      4.53x      4.93x      6.47x
    4K      2.52x      2.95x      3.42x      4.55x      4.96x      6.32x

BICUBIC, ANTIALIAS=TRUE
           x0.25      x0.5     x0.75      x1.5      x2.0      x4.0
------------------------------------------------------------------
 64x64      2.29x      2.49x      2.42x      3.43x      3.91x      5.06x
  320p      4.09x      4.05x      2.84x      3.85x      4.31x      5.32x
  720p      4.27x      4.28x      2.90x      3.90x      4.30x      5.16x
    4K      4.28x      4.12x      2.94x      4.05x      4.29x      5.30x

BICUBIC, ANTIALIAS=FALSE
           x0.25      x0.5     x0.75      x1.5      x2.0      x4.0
------------------------------------------------------------------
 64x64      1.60x      2.10x      2.48x      3.46x      3.91x      4.95x
  320p      2.37x      2.77x      3.09x      3.90x      4.33x      5.33x
  720p      2.55x      2.84x      3.17x      3.94x      4.29x      5.19x
    4K      2.39x      2.86x      3.25x      4.06x      4.36x      5.54x
```

Code and details:

<details>

Note that this is using an env variable to force the generic path, see f9a5c87

```py
"""Benchmark uint8 bilinear/bicubic resize: NEON (channels-last) vs generic (channels-first)."""

import torch
from time import perf_counter_ns

def bench(f, *args, num_exp=9, warmup=1, **kwargs):
    for _ in range(warmup):
        f(*args, **kwargs)
    times = []
    for _ in range(num_exp):
        start = perf_counter_ns()
        f(*args, **kwargs)
        end = perf_counter_ns()
        times.append(end - start)
    return torch.tensor(times).float()

resolutions = [
    ("64x64", (1, 3, 64, 64)),
    ("320p", (1, 3, 320, 480)),
    ("720p", (1, 3, 720, 1280)),
    ("4K", (1, 3, 2160, 3840)),
]
scale_factors = [0.25, 0.5, 0.75, 1.5, 2.0, 4.0]
modes = ["bilinear", "bicubic"]
antialias_values = [True, False]

if __name__ == "__main__":
    torch.set_num_threads(1)
    interpolate = torch.nn.functional.interpolate

    col = 10
    header = f"{'':>6}" + "".join(f"{'x' + str(sf):>{col}}" for sf in scale_factors)

    for mode in modes:
        for antialias in antialias_values:
            aa_label = "aa" if antialias else "no-aa"
            cf_results = {}
            cl_results = {}

            for name, shape in resolutions:
                for sf in scale_factors:
                    oh = max(1, int(shape[2] * sf))
                    ow = max(1, int(shape[3] * sf))
                    torch.manual_seed(42)
                    x = torch.randint(0, 256, shape, dtype=torch.uint8)

                    x_cf = x.contiguous()
                    t = bench(interpolate, x_cf, size=(oh, ow), mode=mode, antialias=antialias)
                    cf_results[(name, sf)] = t.median().item() * 1e-6

                    x_cl = x.contiguous(memory_format=torch.channels_last)
                    t = bench(interpolate, x_cl, size=(oh, ow), mode=mode, antialias=antialias)
                    cl_results[(name, sf)] = t.median().item() * 1e-6

            for label, results in [("Channels-first", cf_results), ("Channels-last", cl_results)]:
                print(f"\n{mode} {aa_label} ({label}, ms)")
                print(header)
                print("-" * len(header))
                for name, _ in resolutions:
                    row = f"{name:>6}"
                    for sf in scale_factors:
                        row += f"{results[(name, sf)]:>{col}.2f}"
                    print(row)

            print(f"\nSpeedup (channels-first / channels-last)")
            print(header)
            print("-" * len(header))
            for name, _ in resolutions:
                row = f"{name:>6}"
                for sf in scale_factors:
                    speedup = cf_results[(name, sf)] / cl_results[(name, sf)]
                    row += f"{speedup:>{col}.2f}x"
                print(row)
            print()
```

```
~/dev/pytorch (neon_interpolate_bilinear_antialias*) ยป lscpu                                                                                                                                                                                                                     nicolashug@devgpu026
Architecture:             aarch64
  CPU op-mode(s):         64-bit
  Byte Order:             Little Endian
CPU(s):                   144
  On-line CPU(s) list:    0-143
Vendor ID:                ARM
  Model name:             Neoverse-V2
    Model:                0
    Thread(s) per core:   1
    Core(s) per socket:   72
    Socket(s):            2
    Stepping:             r0p0
    Frequency boost:      disabled
    CPU(s) scaling MHz:   100%
    CPU max MHz:          3393.0000
    CPU min MHz:          81.0000
    BogoMIPS:             2000.00
    Flags:                fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh
Caches (sum of all):
  L1d:                    9 MiB (144 instances)
  L1i:                    9 MiB (144 instances)
  L2:                     144 MiB (144 instances)
  L3:                     228 MiB (2 instances)
NUMA:
  NUMA node(s):           18
  NUMA node0 CPU(s):      0-71
  NUMA node1 CPU(s):      72-143
  NUMA node2 CPU(s):
  NUMA node3 CPU(s):
  NUMA node4 CPU(s):
  NUMA node5 CPU(s):
  NUMA node6 CPU(s):
  NUMA node7 CPU(s):
  NUMA node8 CPU(s):
  NUMA node9 CPU(s):
  NUMA node10 CPU(s):
  NUMA node11 CPU(s):
  NUMA node12 CPU(s):
  NUMA node13 CPU(s):
  NUMA node14 CPU(s):
  NUMA node15 CPU(s):
  NUMA node16 CPU(s):
  NUMA node17 CPU(s):
Vulnerabilities:
  Gather data sampling:   Not affected
  Itlb multihit:          Not affected
  L1tf:                   Not affected
  Mds:                    Not affected
  Meltdown:               Not affected
  Mmio stale data:        Not affected
  Reg file data sampling: Not affected
  Retbleed:               Not affected
  Spec rstack overflow:   Not affected
  Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
  Spectre v1:             Mitigation; __user pointer sanitization
  Spectre v2:             Not affected
  Srbds:                  Not affected
  Tsx async abort:        Not affected
```
</details>

Pull Request resolved: pytorch#176217
Approved by: https://github.com/malfet, https://github.com/mlazos
pytorchmergebot pushed a commit that referenced this pull request Nov 23, 2026
#205668)

## BC-breaking?

No. Outputs are bit-identical to the current NEON kernels.

## Summary (human written only)

This PR implements a ~2X faster NEON kernel for `F.interpolate()` (the original one was implemented in #176217). Results are bitwise identical, extensive testing was done (see scripts below). Most of the speedup come from re-writing the horizontal pass, taking advantage of the `UDOT` (dot product) instruction which is available on a lot of ARM CPUs that we care about: those on GB200 and GB300. Extensive benchmarks were run to justify the new implementation. Perf is also faster on those CPUs that do not support `UDOT`. Another nicety is that this new implementation is much closer to the existing AVX2 implem.

gpt6.1-sol wrote the kernels, I wrote / heavily guided the comments. High-level implementation details are in the code.

## Agent details (if applicable)

The following was written by an AI assistant and reviewed by the author.

Only `aten/src/ATen/native/cpu/UpSampleKernelNEONAntialias.h` changes, and outputs are bit-identical to main (same int16 weights and integer arithmetic). How the kernels work is described in the comments in that header; this description is about why they're faster and how that was measured.

**Why it's faster.** Most of the time, and most of the gain, is in the horizontal pass. The current horizontal kernel computes one output pixel at a time, with an 8-wide vector loop over its K input pixels and scalar code for the rest, so for K < 8 (all upscales and moderate downscales) it is mostly scalar. The new one processes each output pixel's inputs in groups of 4 with Arm's byte dot-product instructions: a single UDOT (USDOT for the negative weights of bicubic and lanczos) does the 4 multiply-adds of all 3 channels, and each loop iteration computes 16 output pixels, which shares the weight loads and stores 4 pixels at a time. On CPUs without these instructions, a multiply-accumulate version of the same kernel is used for K <= 8, and **the current horizontal kernel, kept unchanged**, for K > 8, where it is faster. The vertical pass is also rewritten, for all CPUs (baseline NEON only): one input row at a time, each row's weight broadcast once per output row, specialized for K = 1 to 4, which makes vertical-only resizes 1.3-1.4x faster.

**Which CPUs get it.** The dot-product kernels need the dotprod extension (UDOT) and, for bicubic and lanczos, i8mm (USDOT); they are only called after a cpuinfo check. Grace (Neoverse-V2: GB200, GB300) has both (`asimddp` and `i8mm` in `/proc/cpuinfo` on every core of the Neoverse-V2 machines used here), as does Graviton3 (Neoverse-V1). Graviton2 (Neoverse-N1) has dotprod but not i8mm, so it uses the fallback for bicubic and lanczos.

**Benchmarks.** All on Neoverse-V2, 1 thread, `F.interpolate` on a 3-channel uint8 channels-last tensor, median of 50 calls (20 for 3024x4032). Every comparison was run with the baseline (or one of the variants) both before and after, to check for drift; the two agreed within 1% (median) each time.

1. This PR vs main, same local build, original vs new header: **1.50-2.70x** with the dot-product path, 1.99-2.70x for `antialias=False`; 1.01-2.38x for the fallback (dot products forced off).

| mode | size | main ms | this PR ms | speedup | this PR without dotprod ms | speedup |
|---|---|---|---|---|---|---|
| bilinear aa | 448x448 -> 896x896 | 2.622 | 1.121 | 2.34x | 1.215 | 2.16x |
| bicubic aa | 448x448 -> 896x896 | 2.838 | 1.614 | 1.76x | 1.954 | 1.45x |
| lanczos aa | 448x448 -> 896x896 | 4.407 | 2.083 | 2.12x | 2.397 | 1.84x |
| bilinear | 448x448 -> 896x896 | 2.614 | 1.115 | 2.34x | 1.203 | 2.17x |
| bicubic | 448x448 -> 896x896 | 2.847 | 1.413 | 2.01x | 1.504 | 1.89x |
| bilinear aa | 423x746 -> 416x736 | 1.684 | 0.841 | 2.00x | 1.088 | 1.55x |
| bicubic aa | 423x746 -> 416x736 | 1.642 | 0.961 | 1.71x | 1.205 | 1.36x |
| lanczos aa | 423x746 -> 416x736 | 2.604 | 1.352 | 1.93x | 2.185 | 1.19x |
| bilinear | 423x746 -> 416x736 | 1.653 | 0.687 | 2.41x | 0.759 | 2.18x |
| bicubic | 423x746 -> 416x736 | 1.609 | 0.807 | 1.99x | 0.878 | 1.83x |
| bilinear aa | 800x800 -> 448x448 | 1.783 | 0.920 | 1.94x | 1.211 | 1.47x |
| bicubic aa | 800x800 -> 448x448 | 2.598 | 1.233 | 2.11x | 2.342 | 1.11x |
| lanczos aa | 800x800 -> 448x448 | 3.322 | 1.689 | 1.97x | 3.019 | 1.10x |
| bilinear | 800x800 -> 448x448 | 1.712 | 0.697 | 2.46x | 0.782 | 2.19x |
| bicubic | 800x800 -> 448x448 | 1.560 | 0.777 | 2.01x | 0.866 | 1.80x |
| bilinear aa | 1024x768 -> 496x368 | 1.660 | 0.983 | 1.69x | 1.279 | 1.30x |
| bicubic aa | 1024x768 -> 496x368 | 2.342 | 1.306 | 1.79x | 2.110 | 1.11x |
| lanczos aa | 1024x768 -> 496x368 | 3.365 | 1.794 | 1.88x | 2.923 | 1.15x |
| bilinear | 1024x768 -> 496x368 | 1.767 | 0.722 | 2.45x | 0.809 | 2.18x |
| bicubic | 1024x768 -> 496x368 | 1.587 | 0.796 | 1.99x | 0.883 | 1.80x |
| bilinear aa | 1792x1792 -> 448x448 | 3.885 | 2.497 | 1.56x | 3.848 | 1.01x |
| bicubic aa | 1792x1792 -> 448x448 | 5.450 | 3.620 | 1.51x | 5.047 | 1.08x |
| lanczos aa | 1792x1792 -> 448x448 | 7.610 | 5.065 | 1.50x | 7.073 | 1.08x |
| bilinear | 1792x1792 -> 448x448 | 3.500 | 1.403 | 2.49x | 1.585 | 2.21x |
| bicubic | 1792x1792 -> 448x448 | 2.934 | 1.462 | 2.01x | 1.653 | 1.77x |
| bilinear aa | 3024x4032 -> 768x1024 | 16.212 | 9.141 | 1.77x | 16.038 | 1.01x |
| bicubic aa | 3024x4032 -> 768x1024 | 23.412 | 13.667 | 1.71x | 22.139 | 1.06x |
| lanczos aa | 3024x4032 -> 768x1024 | 31.693 | 18.509 | 1.71x | 29.406 | 1.08x |
| bilinear | 3024x4032 -> 768x1024 | 14.390 | 5.328 | 2.70x | 6.035 | 2.38x |
| bicubic | 3024x4032 -> 768x1024 | 12.572 | 5.627 | 2.23x | 6.309 | 1.99x |

2. The CI-built wheel of this PR (GCC 13, from the `linux-jammy-aarch64-py3.11` build job) vs nightly 2.16.0.dev20261119: **1.31-4.39x** (median 2.03x), so the code from the shipped toolchain gets the same gains. The two builds differ in more than this PR (for some shapes the nightly is slower than the local main build above), so table 1 is the like-for-like comparison.

<details><summary>CI wheel vs nightly</summary>

| mode | size | nightly ms | CI wheel ms | speedup |
|---|---|---|---|---|
| bilinear aa | 448x448 -> 896x896 | 4.173 | 1.224 | 3.41x |
| bicubic aa | 448x448 -> 896x896 | 2.908 | 1.647 | 1.77x |
| lanczos aa | 448x448 -> 896x896 | 5.988 | 2.104 | 2.85x |
| bilinear | 448x448 -> 896x896 | 4.159 | 1.226 | 3.39x |
| bicubic | 448x448 -> 896x896 | 2.905 | 1.403 | 2.07x |
| bilinear aa | 423x746 -> 416x736 | 2.872 | 0.949 | 3.03x |
| bicubic aa | 423x746 -> 416x736 | 1.772 | 1.020 | 1.74x |
| lanczos aa | 423x746 -> 416x736 | 3.814 | 1.526 | 2.50x |
| bilinear | 423x746 -> 416x736 | 2.863 | 0.766 | 3.74x |
| bicubic | 423x746 -> 416x736 | 1.654 | 0.838 | 1.97x |
| bilinear aa | 800x800 -> 448x448 | 2.272 | 1.026 | 2.21x |
| bicubic aa | 800x800 -> 448x448 | 3.636 | 1.465 | 2.48x |
| lanczos aa | 800x800 -> 448x448 | 4.477 | 1.952 | 2.29x |
| bilinear | 800x800 -> 448x448 | 3.103 | 0.784 | 3.96x |
| bicubic | 800x800 -> 448x448 | 1.605 | 0.839 | 1.91x |
| bilinear aa | 1024x768 -> 496x368 | 2.030 | 1.079 | 1.88x |
| bicubic aa | 1024x768 -> 496x368 | 2.881 | 1.543 | 1.87x |
| lanczos aa | 1024x768 -> 496x368 | 4.121 | 2.070 | 1.99x |
| bilinear | 1024x768 -> 496x368 | 3.231 | 0.808 | 4.00x |
| bicubic | 1024x768 -> 496x368 | 1.642 | 0.860 | 1.91x |
| bilinear aa | 1792x1792 -> 448x448 | 3.785 | 2.776 | 1.36x |
| bicubic aa | 1792x1792 -> 448x448 | 5.546 | 4.234 | 1.31x |
| lanczos aa | 1792x1792 -> 448x448 | 7.592 | 5.764 | 1.32x |
| bilinear | 1792x1792 -> 448x448 | 6.646 | 1.577 | 4.21x |
| bicubic | 1792x1792 -> 448x448 | 3.024 | 1.637 | 1.85x |
| bilinear aa | 3024x4032 -> 768x1024 | 17.329 | 10.838 | 1.60x |
| bicubic aa | 3024x4032 -> 768x1024 | 26.292 | 16.462 | 1.60x |
| lanczos aa | 3024x4032 -> 768x1024 | 35.939 | 21.635 | 1.66x |
| bilinear | 3024x4032 -> 768x1024 | 26.169 | 5.957 | 4.39x |
| bicubic | 3024x4032 -> 768x1024 | 12.831 | 6.181 | 2.08x |

</details>

3. Design choices, each measured against the alternatives:
   - 16 output pixels per iteration (4 in each of 4 rows) is the fastest of 1x2, 4x1, 4x2, 4x4, 8x1 and 8x2 (pixels x rows) in every case; median time relative to 4x4 on horizontal-only / 2D resizes: 1x2 2.39x / 2.03x, 4x1 1.21x / 1.14x, 4x2 1.14x / 1.10x, 8x1 1.07x / 1.04x, 8x2 1.06x / 1.04x.
   - The K = 1 to 4 specializations of the vertical pass make it 1.10-1.41x faster for those K (1.00x for K > 4).
   - Without dot products, the multiply-accumulate kernel was 0.79-0.98x of the current horizontal kernel on large antialiased downscales (K > 8), hence keeping the current kernel there.
   - A dot-product vertical pass (4 input rows interleaved per UDOT) was 1.14-1.54x faster for K >= 5 but 0.65-0.69x for K = 2, so it isn't included.

**Compiler.** The dot-product functions are compiled with `__attribute__((target("arch=armv8.2-a+dotprod")))` (`+i8mm` for USDOT); the rest of the file stays at the baseline architecture. With the `target("+dotprod")` spelling, GCC 13 emits UDOT but binutils 2.40 rejects it, as aarch64 CI first showed. With this spelling `UpSampleKernel.cpp` compiles in `pytorch/manylinux2_28_aarch64-builder:cpu-aarch64-main` (GCC 13.3.1) for DEFAULT, SVE128 and SVE256, each containing `udot` and `usdot`, and with clang 21 and GCC 11. The CI wheel's `libtorch_cpu.so` contains them too.

**Tests** (Neoverse-V2): outputs are bit-identical to the nightly's on 790 cases (all 5 mode / antialias combinations, upscales and downscales, 1x1 up to 4032x3024) with the dot-product path, with it forced off and with i8mm forced off (`check_equal.py` below). No kernel reads past the end of its input: 1600 cases with each input ending exactly at a `PROT_NONE` page pass in all three configurations and on main, and with the bounds check removed it crashes on the 4th shape (`guard_page_check.py` below). `pytest test/test_nn.py -k "upsampling or interpolate"` passes, and aarch64 CI is green.

<details><summary>bit-exactness check (check_equal.py)</summary>

```python
"""Check that this PR's NEON kernels give bit-identical F.interpolate outputs to main.

Run once with a build of main (saves the reference outputs), then with this PR:
    python check_equal.py save ref.pt
    python check_equal.py check ref.pt
Inputs are deterministic 3-channel uint8 channels-last tensors, i.e. the NEON path.
"""
import sys

import torch
import torch.nn.functional as F

torch.set_num_threads(1)

def cases():
    g = torch.Generator().manual_seed(0)
    sizes = []
    for _ in range(150):
        H, W = torch.randint(1, 700, (2,), generator=g).tolist()
        h, w = torch.randint(1, 900, (2,), generator=g).tolist()
        sizes.append((H, W, h, w))
    sizes += [(800, 800, 448, 448), (423, 746, 416, 736), (1024, 768, 496, 368), (448, 448, 896, 896),
              (1792, 1792, 448, 448), (3, 5, 1, 1), (1, 1, 7, 9), (17, 1000, 3, 999)]
    for i, (H, W, h, w) in enumerate(sizes):
        x = torch.randint(0, 256, (1, 3, H, W), dtype=torch.uint8, generator=g).contiguous(memory_format=torch.channels_last)
        for mode, aa in [("bilinear", True), ("bilinear", False), ("bicubic", True), ("bicubic", False), ("lanczos", True)]:
            yield (i, H, W, h, w, mode, aa), x, dict(size=(h, w), mode=mode, antialias=aa)

cmd, path = sys.argv[1], sys.argv[2]
print(torch.__version__)
if cmd == "save":
    torch.save({k: F.interpolate(x, **kw) for k, x, kw in cases()}, path)
    print("saved")
else:
    ref = torch.load(path)
    n = bad = 0
    for k, x, kw in cases():
        out = F.interpolate(x, **kw)
        n += 1
        if not torch.equal(out, ref[k]):
            bad += 1
            d = (out.int() - ref[k].int()).abs()
            print("MISMATCH", k, "max diff", int(d.max()), "n diff", int((d > 0).sum()))
    print(f"{n} cases, {bad} mismatches")
```
</details>

<details><summary>over-read check (guard_page_check.py)</summary>

```python
"""Over-read check for the uint8 interpolate kernels: inputs end exactly at an unreadable page.

Usage: python guard_page_check.py
Each input is placed in an mmap so that its last byte is immediately followed by a PROT_NONE page:
any read past the end of the tensor segfaults. Inputs are 3-channel uint8 channels-last with
standard strides, so the NEON path is taken (and the input is used in place, without a copy).
Covers horizontal-only, vertical-only and both-axes resizes (vertical-only reads the input directly
in the vertical pass), up and down, tiny sizes, row lengths that aren't multiples of 16 bytes, and
batches (only the last image ends at the guard page).
"""

import ctypes
import mmap

import torch
import torch.nn.functional as F

torch.set_num_threads(1)
libc = ctypes.CDLL(None, use_errno=True)
libc.mprotect.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]
PAGE = mmap.PAGESIZE
keep = []

def guarded_input(N, H, W, g):
    nbytes = N * H * W * 3
    size = ((nbytes + PAGE - 1) // PAGE + 1) * PAGE
    m = mmap.mmap(-1, size)
    buf = (ctypes.c_char * size).from_buffer(m)
    addr = ctypes.addressof(buf)
    if libc.mprotect(addr + size - PAGE, PAGE, 0) != 0:
        raise OSError(ctypes.get_errno(), "mprotect failed")
    flat = torch.frombuffer(m, dtype=torch.uint8, count=nbytes, offset=size - PAGE - nbytes)
    flat.copy_(torch.randint(0, 256, (nbytes,), dtype=torch.uint8, generator=g))
    keep.append((m, buf))
    x = flat.as_strided((N, 3, H, W), (H * W * 3, 1, W * 3, 3))
    assert x.data_ptr() + nbytes == addr + size - PAGE
    return x

g = torch.Generator().manual_seed(0)
shapes = [
    (1, 1, 1, 1, 3), (1, 1, 1, 3, 1), (1, 2, 3, 1, 1), (1, 3, 5, 7, 9), (1, 7, 1, 3, 1),
    (1, 5, 37, 5, 11), (1, 5, 11, 5, 37), (1, 37, 5, 11, 5), (1, 11, 5, 37, 5),
    (1, 64, 100, 64, 33), (1, 64, 33, 64, 100), (1, 100, 64, 33, 64), (1, 33, 64, 100, 64),
    (1, 448, 448, 896, 896), (1, 800, 800, 448, 448), (1, 423, 746, 416, 736),
    (1, 1792, 1792, 448, 448), (1, 1000, 17, 999, 3), (1, 17, 1000, 3, 999),
    (3, 50, 71, 23, 40), (2, 9, 300, 9, 100), (2, 300, 9, 100, 9),
]
for _ in range(300):
    H, W = torch.randint(1, 260, (2,), generator=g).tolist()
    h, w = torch.randint(1, 260, (2,), generator=g).tolist()
    if torch.rand(1, generator=g) < 0.3:
        h = H
    elif torch.rand(1, generator=g) < 0.3:
        w = W
    shapes.append((int(torch.randint(1, 3, (1,), generator=g)), H, W, h, w))

modes = [("bilinear", True), ("bilinear", False), ("bicubic", True), ("bicubic", False), ("lanczos", True)]
n = 0
for N, H, W, h, w in shapes:
    if (H, W) == (h, w):
        continue
    x = guarded_input(N, H, W, g)
    ref = x.clone(memory_format=torch.channels_last)
    for mode, aa in modes:
        print(f"\r{N}x{H}x{W} -> {h}x{w} {mode} aa={aa}      ", end="", flush=True)
        out = F.interpolate(x, size=(h, w), mode=mode, antialias=aa)
        assert out.is_contiguous(memory_format=torch.channels_last)
        assert torch.equal(out, F.interpolate(ref, size=(h, w), mode=mode, antialias=aa))
        n += 1
print(f"\n{n} cases, no over-read (no segfault), outputs equal to a copy of the input")
```
</details>

<details><summary>benchmark (bench.py)</summary>

```python
"""F.interpolate uint8 timings on 3-channel channels-last inputs (the NEON path), 1 thread.

Run once with a build of main and once with this PR, on the same machine:
    python bench.py main
    python bench.py pr
"""
import sys
import time

import numpy as np
import torch
import torch.nn.functional as F

torch.set_num_threads(1)

def med(f, n):
    for _ in range(3):
        f()
    t = []
    for _ in range(n):
        t0 = time.perf_counter()
        f()
        t.append(time.perf_counter() - t0)
    return 1000 * float(np.median(t))

print(f"# {sys.argv[1]}: torch {torch.__version__}, {torch.backends.cpu.get_cpu_capability()}, 1 thread")
g = torch.Generator().manual_seed(0)
shapes = [((448, 448), (896, 896)), ((423, 746), (416, 736)), ((800, 800), (448, 448)), ((1024, 768), (496, 368)),
          ((1792, 1792), (448, 448)), ((3024, 4032), (768, 1024))]
for (H, W), (h, w) in shapes:
    x = torch.randint(0, 256, (1, 3, H, W), dtype=torch.uint8, generator=g).contiguous(memory_format=torch.channels_last)
    n = 20 if H * W > 4_000_000 else 50
    for mode, aa in [("bilinear", True), ("bicubic", True), ("lanczos", True), ("bilinear", False), ("bicubic", False)]:
        kw = dict(size=(h, w), mode=mode, antialias=aa)
        print(f"{mode}{' aa' if aa else ''}\t{H}x{W} -> {h}x{w}\t{med(lambda: F.interpolate(x, **kw), n):.3f} ms", flush=True)
```
</details>

The "without dotprod" column was measured on the same Neoverse-V2 by building this PR with the dot-product path disabled (`const bool use_dot = false && ...` in `NeonResampleHorizontal`).

Not tested: an actual CPU without `dotprod` (the fallback was exercised by disabling the dot path on Neoverse-V2), a GCC 13 build, a full clang build (only `UpSampleKernel.cpp` was compiled with clang 21), and inputs with 4 channels (the NEON path is 3-channel only, unchanged).

Pull Request resolved: #205668
Approved by: https://github.com/albanD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged module: cpu CPU specific problem (e.g., perf, algorithm) release notes: nn release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants