From 1f6d6aa5338b07abe41210360d4b0d6ca2b208a7 Mon Sep 17 00:00:00 2001 From: Ali Afzal Date: Mon, 16 Nov 2026 14:19:51 -0800 Subject: [PATCH 1/4] Copy the caller's lists in the dialect verifiers (#24689) Summary: Pull Request resolved: https://github.com/pytorch/executorch/pull/24689 **Problem:** `EXIRATenDialectVerifier` and `EXIREdgeDialectVerifier` merge the config's `preserve_ops` and `_core_aten_ops_exception_list` into the lists the caller passes, in place. `to_edge` passes `compile_config.preserve_ops` itself, so each call appends the list to itself and it grows 4x per `to_edge` call. A caller that reuses one list grows it without bound: the Cadence compiler passes the module-level `TO_EDGE_PRESERVE_OPS` to every call, which holds 4, 16, 64 and 256 entries after 1 to 4 lowerings. Each lowering is slower than the last, and a test process that lowers hundreds of programs times out. **Fix:** copy both lists before merging. **Was the in-place merge intended?** No. Before the change that added `preserve_ops` to `EdgeCompileConfig`, the verifier built a new list (`config_list + (exception_list or [])`). That change switched to `_x = x or []` followed by `_x.extend(...)`, and `x or []` returns the caller's own list. This restores the earlier behavior. **Blast radius:** within one call, the verifier sees the same merged lists as before. The only difference is between calls: a reused list no longer collects duplicates, or entries from an earlier call's config. We found no caller that reads its list back after the call. **Follow-up, not in this diff:** `to_edge_transform_and_lower` reassigns `_core_aten_ops_exception_list` on the caller's config. Authored with Claude Code. Reviewed By: DrJessop, ethansfng Differential Revision: D128295391 --- exir/program/test/test_program.py | 30 +++++++++++++++++++++++++ exir/verification/test/test_verifier.py | 25 ++++++++++++++++++++- exir/verification/verifier.py | 8 +++---- 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/exir/program/test/test_program.py b/exir/program/test/test_program.py index 413498166ec..839c9192a10 100644 --- a/exir/program/test/test_program.py +++ b/exir/program/test/test_program.py @@ -1061,6 +1061,36 @@ def test_to_edge_with_single_preserved_op(self): program, ops_not_to_decompose, expected_non_decomposed_edge_ops ) + def test_to_edge_leaves_the_preserve_ops_list_unchanged(self): + model = TestLinear() + program = torch.export.export(model, model._get_random_inputs(), strict=True) + preserve_ops = [torch.ops.aten.linear.default] + + for _ in range(2): + to_edge( + program, compile_config=EdgeCompileConfig(preserve_ops=preserve_ops) + ) + + self.assertEqual(preserve_ops, [torch.ops.aten.linear.default]) + + def test_edge_program_manager_leaves_the_exception_list_unchanged(self): + model = TestLinear() + program = torch.export.export(model, model._get_random_inputs(), strict=True) + edge_program = to_edge(program).exported_program() + exception_list = [torch.ops.aten._linalg_svd.default] + + EdgeProgramManager( + edge_program, + compile_config=EdgeCompileConfig( + _core_aten_ops_exception_list=[ + torch.ops.aten.linalg_vector_norm.default + ] + ), + core_aten_ops_exception_list=exception_list, + ) + + self.assertEqual(exception_list, [torch.ops.aten._linalg_svd.default]) + def test_to_edge_with_partial_ops_preserved(self): model = TestLinearSDPACombined() program = torch.export.export(model, model._get_random_inputs(), strict=True) diff --git a/exir/verification/test/test_verifier.py b/exir/verification/test/test_verifier.py index 14a268cf7aa..d14c4f4805b 100644 --- a/exir/verification/test/test_verifier.py +++ b/exir/verification/test/test_verifier.py @@ -20,7 +20,7 @@ from torch.export import export from torch.export.experimental import _export_forward_backward -from ..verifier import EXIREdgeDialectVerifier +from ..verifier import EXIRATenDialectVerifier, EXIREdgeDialectVerifier class TestEdgeDialectVerifier(unittest.TestCase): @@ -31,6 +31,29 @@ def assertNotRaises(self, exc_type: Any) -> Any: except exc_type: raise self.failureException("{} raised".format(exc_type.__name__)) + def _assert_leaves_the_callers_lists_unchanged(self, make_verifier: Any) -> None: + exception_list = [torch.ops.aten.sort.default] + preserve_ops = [torch.ops.aten.linear.default] + config = EdgeCompileConfig( + _core_aten_ops_exception_list=[torch.ops.aten.median.default], + preserve_ops=[torch.ops.aten.gelu.default], + ) + + make_verifier( + edge_compile_config=config, + core_aten_ops_exception_list=exception_list, + preserve_ops=preserve_ops, + ) + + self.assertEqual(exception_list, [torch.ops.aten.sort.default]) + self.assertEqual(preserve_ops, [torch.ops.aten.linear.default]) + + def test_aten_verifier_leaves_the_callers_lists_unchanged(self) -> None: + self._assert_leaves_the_callers_lists_unchanged(EXIRATenDialectVerifier) + + def test_edge_verifier_leaves_the_callers_lists_unchanged(self) -> None: + self._assert_leaves_the_callers_lists_unchanged(EXIREdgeDialectVerifier) + def test_edge_verifier_check_valid_op_succeed_given_custom_op(self) -> None: edge_op = ops.edge.quantized_decomposed.quantize_per_tensor.default verifier = EXIREdgeDialectVerifier() diff --git a/exir/verification/verifier.py b/exir/verification/verifier.py index 52bf257241b..9ccd2b5022c 100644 --- a/exir/verification/verifier.py +++ b/exir/verification/verifier.py @@ -113,8 +113,8 @@ def EXIRATenDialectVerifier( # noqa: C901 """ Returns a verifier class that runs ATen dialect specific checks on the graph module. """ - _core_aten_ops_exception_list = core_aten_ops_exception_list or [] - _preserve_ops = preserve_ops or [] + _core_aten_ops_exception_list = list(core_aten_ops_exception_list or []) + _preserve_ops = list(preserve_ops or []) # merge the exception list from edge_compile_config and exception_list if edge_compile_config: if edge_compile_config._core_aten_ops_exception_list: @@ -269,8 +269,8 @@ def EXIREdgeDialectVerifier( # noqa: C901 core_aten_ops_exception_list: Optional[List[torch._ops.OpOverload]] = None, preserve_ops: Optional[List[torch._ops.OpOverload]] = None, ): - _core_aten_ops_exception_list = core_aten_ops_exception_list or [] - _preserve_ops = preserve_ops or [] + _core_aten_ops_exception_list = list(core_aten_ops_exception_list or []) + _preserve_ops = list(preserve_ops or []) # merge the exception list from edge_compile_config and exception_list if edge_compile_config: if edge_compile_config._core_aten_ops_exception_list: From cb3e2311c743b0f934f0e2c3d318ab9e602e1ebf Mon Sep 17 00:00:00 2001 From: Ali Afzal Date: Mon, 16 Nov 2026 14:19:55 -0800 Subject: [PATCH 2/4] Run the generic kernel gtests on the host, and fix avg_pool2d and fully_connected (#24933) Summary: Pull Request resolved: https://github.com/pytorch/executorch/pull/24933 OSS CI never ran the gtests for the Cadence generic (CPU reference) kernels, and 9 of the test files were not in the open-source tree. This diff moves those 9 files into `backends/cadence/generic/operators/tests/`, adds `.ci/scripts/test-cadence-generic.sh` to build and run `cadence_generic_op_tests` on the host, and runs that script from a new `cpu-op-test` job in `build-cadence-runner.yml`, with the same runner and permissions as `cpu-build`. `tests/CMakeLists.txt` now passes `-Qunused-arguments` only to Clang, because GCC rejects the flag. The tests found two kernel bugs. With `ceil_mode=True` and `count_include_pad=True`, the last `avg_pool2d` window can run past the padding, and PyTorch divides that window by the positions inside the padded input, but the kernel always divided by `kh * kw`; in the quantized path it also added the zero point for the positions past the padding. For width 4, kernel 3, stride 2 and padding 1, the last output was 2/3 of the expected value. The kernel now uses the window size inside the padded input for both the divisor and the zero point, so every other window computes the same value as before. Its dtype and layout checks also move from `ET_DCHECK_MSG`, which release builds compile out, to `ET_KERNEL_CHECK_MSG`, so a bad input fails with `InvalidArgument` instead of running anyway. The `fully_connected` kernel read every tensor as float, with no dtype or shape check. The registration diff later in this stack maps `cadence::fully_connected.out` and `aten::linear.out` to it, and with that registration a float64 linear gave values off by up to 4.2e201 and a float16 linear crashed the runner. The kernel now returns `InvalidArgument` unless all tensors are float, the weight is 2-D and the inner dimensions match. Float callers are unaffected. The diff also adds tests for the kernels that had none, taking the count from 66 to 102: the registered kernels no test reached (`quantized_add`, `quantized_mul`, `im2row`, `quantized_max_pool2d_nchw`, uint8 `quantized_matmul`, and uint8 cases for linear, fully_connected and conv2d NHWC), and kernels the CPU runner doesn't register (`rope`, `where_Scalar`, `quantized_embedding_byte`, `linalg_svd`, `sdpa_bitwise_causal_mask_gen` and `roi_align_box_processor`), because other users call those on CPU and a regression should fail OSS CI. Expected values come from `aot/ref_implementations.py`, or are worked out by hand where it has no reference or a wrong one. The `linalg_svd` test compares the singular values with `torch.linalg.svdvals` and checks that U and Vh are orthogonal and reconstruct A, since the singular vectors' signs aren't unique. One reference bug shows up here: `ref_implementations.py` computes the requantization scale as `-M / 2^31`, while the compiler and the kernels use `+M / 2^31` (in the kernels, `1 << 31` is `INT_MIN`). The tests follow the kernels, and fixing the reference is a follow-up. Authored with Claude Code. Reviewed By: DrJessop Differential Revision: D128295392 --- .ci/scripts/test-cadence-generic.sh | 33 + .github/workflows/build-cadence-runner.yml | 30 + backends/cadence/CMakeLists.txt | 7 +- .../generic/operators/op_avg_pool2d.cpp | 28 +- .../generic/operators/op_fully_connected.cpp | 19 +- .../cadence/generic/operators/targets.bzl | 2 +- backends/cadence/generic/operators/tests/BUCK | 421 +++++ .../generic/operators/tests/CMakeLists.txt | 51 +- .../operators/tests/test_op_avg_pool2d.cpp | 157 ++ .../tests/test_op_fully_connected.cpp | 79 + .../operators/tests/test_op_im2row.cpp | 117 ++ .../operators/tests/test_op_linalg_svd.cpp | 134 ++ .../operators/tests/test_op_quantized_add.cpp | 70 + .../tests/test_op_quantized_conv1d_ncl.cpp | 175 ++ .../tests/test_op_quantized_conv1d_nlc.cpp | 173 ++ .../tests/test_op_quantized_conv2d.cpp | 438 +++++ ...test_op_quantized_depthwise_conv1d_ncl.cpp | 341 ++++ ...test_op_quantized_depthwise_conv1d_nlc.cpp | 342 ++++ .../test_op_quantized_embedding_byte.cpp | 108 ++ .../test_op_quantized_fully_connected.cpp | 149 ++ .../tests/test_op_quantized_linear.cpp | 177 ++ .../tests/test_op_quantized_matmul.cpp | 78 + .../tests/test_op_quantized_max_pool2d.cpp | 88 + .../operators/tests/test_op_quantized_mul.cpp | 57 + .../tests/test_op_quantized_softmax.cpp | 1540 +++++++++++++++++ .../tests/test_op_roi_align_box_processor.cpp | 109 ++ .../generic/operators/tests/test_op_rope.cpp | 97 ++ .../test_op_sdpa_bitwise_causal_mask_gen.cpp | 79 + .../operators/tests/test_op_where_scalar.cpp | 57 + .../tests/test_quantized_linear_packed.cpp | 407 +++++ 30 files changed, 5536 insertions(+), 27 deletions(-) create mode 100755 .ci/scripts/test-cadence-generic.sh create mode 100644 backends/cadence/generic/operators/tests/test_op_avg_pool2d.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_fully_connected.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_im2row.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_linalg_svd.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_add.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_conv1d_ncl.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_conv1d_nlc.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_conv2d.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_depthwise_conv1d_ncl.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_depthwise_conv1d_nlc.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_embedding_byte.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_fully_connected.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_linear.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_matmul.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_max_pool2d.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_mul.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_quantized_softmax.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_roi_align_box_processor.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_rope.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_sdpa_bitwise_causal_mask_gen.cpp create mode 100644 backends/cadence/generic/operators/tests/test_op_where_scalar.cpp create mode 100644 backends/cadence/generic/operators/tests/test_quantized_linear_packed.cpp diff --git a/.ci/scripts/test-cadence-generic.sh b/.ci/scripts/test-cadence-generic.sh new file mode 100755 index 00000000000..548901ab754 --- /dev/null +++ b/.ci/scripts/test-cadence-generic.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +# +# Build the Cadence generic (reference) op-level gtest tests for the host and +# run them. +# +# Unlike backends/cadence/build_cadence_runner.sh (built -fno-exceptions +# -fno-rtti), the gtest tests need exceptions + RTTI, so those flags are NOT set +# here. + +set -euo pipefail + +TEST_TARGET=cadence_generic_op_tests +TEST_BIN="cmake-out/backends/cadence/generic/operators/tests/${TEST_TARGET}" + +rm -rf cmake-out +cmake \ + -DCMAKE_INSTALL_PREFIX=cmake-out \ + -DCMAKE_BUILD_TYPE=Release \ + -DEXECUTORCH_BUILD_CADENCE=ON \ + -DEXECUTORCH_BUILD_CADENCE_OP_TESTS=ON \ + -DEXECUTORCH_BUILD_EXECUTOR_RUNNER=OFF \ + -DEXECUTORCH_ENABLE_LOGGING=ON \ + -DPYTHON_EXECUTABLE="$(which python3)" \ + -Bcmake-out . + +cmake --build cmake-out --target "${TEST_TARGET}" -j"$(nproc)" + +"${TEST_BIN}" diff --git a/.github/workflows/build-cadence-runner.yml b/.github/workflows/build-cadence-runner.yml index eb61db697c5..f4a9563a083 100644 --- a/.github/workflows/build-cadence-runner.yml +++ b/.github/workflows/build-cadence-runner.yml @@ -20,6 +20,7 @@ on: - examples/cadence/** - .ci/scripts/setup-xtensa-tools.sh - .ci/scripts/build-cadence-xtensa.sh + - .ci/scripts/test-cadence-generic.sh - .ci/scripts/test-cadence-xtensa.sh workflow_dispatch: @@ -109,6 +110,35 @@ jobs: docker-image: ${{ needs.docker-image.outputs.image }} ref: ${{ (github.event_name == 'pull_request' || github.event_name == 'pull_request_target') && github.event.pull_request.head.sha || github.sha }} + # Op-level gtests of the generic (reference) kernels on the host. A separate + # configure from cpu-build, because the gtests need the exceptions and RTTI + # that the runner build disables. + cpu-op-test: + needs: docker-image + if: >- + github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || + (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) || + (github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name != github.repository && + contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR"]'), github.event.pull_request.author_association)) + uses: pytorch/test-infra/.github/workflows/linux_job_v3.yml@main + permissions: + contents: read + with: + job-name: op-test + runner: mt-l-x86iavx512-8-64 + docker-image: ${{ needs.docker-image.outputs.image }} + submodules: recursive + ref: ${{ (github.event_name == 'pull_request' || github.event_name == 'pull_request_target') && github.event.pull_request.head.sha || github.sha }} + timeout: 90 + script: | + set -eux + # The generic Linux job chooses to use base env, not the one setup by the image + CONDA_ENV=$(conda env list --json | jq -r ".envs | .[-1]") + conda activate "${CONDA_ENV}" + + ./install_requirements.sh > /dev/null + .ci/scripts/test-cadence-generic.sh + # Cross-compile cadence_executor_runner for each Cadence Xtensa core, one job # per backend so they show as separate lines (no matrix grouping). Shared logic # lives in _xtensa_build.yml. fusion_g3 is omitted until the upstream fusion_g3 diff --git a/backends/cadence/CMakeLists.txt b/backends/cadence/CMakeLists.txt index b5d72529bc2..703813735db 100644 --- a/backends/cadence/CMakeLists.txt +++ b/backends/cadence/CMakeLists.txt @@ -146,9 +146,10 @@ if(EXECUTORCH_BUILD_CADENCE_RUNNER) target_link_options(cadence_executor_runner PRIVATE -static -lm) endif() -# Cadence op-level gtest tests, cross-compiled for the Xtensa ISS (run via -# xt-run). Built only when EXECUTORCH_BUILD_CADENCE_OP_TESTS is ON and the -# selected backend ships a tests dir. See .ci/scripts/test-cadence-xtensa.sh. +# Cadence op-level gtest tests. Built only when +# EXECUTORCH_BUILD_CADENCE_OP_TESTS is ON and the selected backend ships a tests +# dir. See .ci/scripts/test-cadence-generic.sh (generic, on the host) and +# .ci/scripts/test-cadence-xtensa.sh (Xtensa backends, on the ISS via xt-run). if(EXECUTORCH_BUILD_CADENCE_OP_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${TARGET_DIR}/operators/tests/CMakeLists.txt" diff --git a/backends/cadence/generic/operators/op_avg_pool2d.cpp b/backends/cadence/generic/operators/op_avg_pool2d.cpp index c33f91151fb..6b4130a4afc 100644 --- a/backends/cadence/generic/operators/op_avg_pool2d.cpp +++ b/backends/cadence/generic/operators/op_avg_pool2d.cpp @@ -50,10 +50,6 @@ void avg_pool2d_nchw( int p0 = padding[0]; int p1 = padding[1]; - bool is_fixed_divisor = divisor_override.has_value() || count_include_pad; - float fixed_inv_divisor = - 1.f / (divisor_override.has_value() ? divisor_override.value() : kh * kw); - for (int _n = 0; _n < leading_dims; ++_n) { for (int _ih = 0, _oh = 0; _oh < oh; ++_oh, _ih += s0) { int input_offset = _n * ih * iw; @@ -65,8 +61,12 @@ void avg_pool2d_nchw( int kw_hi = std::min(iw, _iw + kw - p1); // Count the number of contributions sans padding int count = (kh_hi - kh_lo) * (kw_hi - kw_lo); + // Count the window within the padded input, which is smaller than the + // kernel where ceil_mode adds a window that runs past the padding. + int pool_size = (std::min(_ih + kh, ih + 2 * p0) - _ih) * + (std::min(_iw + kw, iw + 2 * p1) - _iw); // Set the accumulator - AT acc = count_include_pad ? in_zero_point * (kh * kw - count) : 0; + AT acc = count_include_pad ? in_zero_point * (pool_size - count) : 0; // Accumulate values for (int _kh = kh_lo; _kh < kh_hi; ++_kh) { for (int _kw = kw_lo; _kw < kw_hi; ++_kw) { @@ -74,7 +74,9 @@ void avg_pool2d_nchw( acc += in_data[input_addr]; } } - float inv_divisor = is_fixed_divisor ? fixed_inv_divisor : 1.f / count; + float inv_divisor = divisor_override.has_value() + ? 1.f / divisor_override.value() + : 1.f / (count_include_pad ? pool_size : count); float val = acc * inv_divisor; if (quantized) { int32_t min_val = @@ -92,7 +94,7 @@ void avg_pool2d_nchw( } Tensor& avg_pool2d_out( - ET_UNUSED KernelRuntimeContext& ctx, + KernelRuntimeContext& ctx, const Tensor& input, IntArrayRef kernel_size, IntArrayRef stride, @@ -103,7 +105,12 @@ Tensor& avg_pool2d_out( const optional& in_zero_point_t, bool channel_last, Tensor& out) { - ET_DCHECK_MSG(!channel_last, "NHWC layout for avg_pool2d not yet supported"); + ET_KERNEL_CHECK_MSG( + ctx, + !channel_last, + InvalidArgument, + out, + "NHWC layout for avg_pool2d not yet supported"); const int32_t in_zero_point = in_zero_point_t.has_value() ? in_zero_point_t.value().const_data_ptr()[0] : 0; @@ -140,8 +147,11 @@ Tensor& avg_pool2d_out( typed_avg_pool2d(float, float, false, Float); typed_avg_pool2d(uint8_t, int32_t, true, Byte); default: - ET_DCHECK_MSG( + ET_KERNEL_CHECK_MSG( + ctx, false, + InvalidArgument, + out, "avg_pool2d not implemented for dtype %s", torch::executor::toString(dtype)); } diff --git a/backends/cadence/generic/operators/op_fully_connected.cpp b/backends/cadence/generic/operators/op_fully_connected.cpp index b65f8016880..f285bd47cea 100644 --- a/backends/cadence/generic/operators/op_fully_connected.cpp +++ b/backends/cadence/generic/operators/op_fully_connected.cpp @@ -15,6 +15,7 @@ namespace impl { namespace generic { namespace native { +using ::executorch::aten::ScalarType; using ::executorch::aten::Tensor; using ::executorch::runtime::getLeadingDims; using ::executorch::runtime::KernelRuntimeContext; @@ -54,11 +55,27 @@ void linear( } Tensor& fully_connected_out( - ET_UNUSED KernelRuntimeContext& ctx, + KernelRuntimeContext& ctx, const Tensor& input, const Tensor& weight, const optional& bias, Tensor& output) { + ET_KERNEL_CHECK_MSG( + ctx, + input.scalar_type() == ScalarType::Float && + weight.scalar_type() == ScalarType::Float && + output.scalar_type() == ScalarType::Float && + (!bias.has_value() || + bias.value().scalar_type() == ScalarType::Float), + InvalidArgument, + output, + "fully_connected supports only float input, weight, bias and output"); + ET_KERNEL_CHECK_MSG( + ctx, + weight.dim() == 2 && input.size(input.dim() - 1) == weight.size(1), + InvalidArgument, + output, + "fully_connected input's last dim must match weight's dim 1"); linear(input, weight, bias, output); return output; } diff --git a/backends/cadence/generic/operators/targets.bzl b/backends/cadence/generic/operators/targets.bzl index 8194dddb214..f0996ecaf2c 100644 --- a/backends/cadence/generic/operators/targets.bzl +++ b/backends/cadence/generic/operators/targets.bzl @@ -100,7 +100,7 @@ def define_common_targets(): runtime.cxx_library( name = "op_linalg_svd", srcs = ["op_linalg_svd.cpp"], - headers = ["op_linalg_svd.h"], + exported_headers = ["op_linalg_svd.h"], platforms = CXX, deps = [ "//executorch/runtime/kernel:kernel_includes", diff --git a/backends/cadence/generic/operators/tests/BUCK b/backends/cadence/generic/operators/tests/BUCK index 7d3333d0706..9f7ed8b78f7 100644 --- a/backends/cadence/generic/operators/tests/BUCK +++ b/backends/cadence/generic/operators/tests/BUCK @@ -4,6 +4,44 @@ load("@fbsource//xplat/on_device_ai/Assistant/Jarvis/build:cxx_wrapper.bzl", "ja oncall("executorch") +jarvis_wrapper.cxx_test( + name = "test_op_avg_pool2d", + srcs = [ + "test_op_avg_pool2d.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_avg_pool2d", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_fully_connected", + srcs = [ + "test_op_fully_connected.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_fully_connected", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + jarvis_wrapper.cxx_test( name = "test_op_quantized_layer_norm", srcs = [ @@ -60,3 +98,386 @@ jarvis_wrapper.cxx_test( "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", ], ) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_conv1d_ncl", + srcs = [ + "test_op_quantized_conv1d_ncl.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_conv1d_ncl", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_conv1d_nlc", + srcs = [ + "test_op_quantized_conv1d_nlc.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_conv1d_nlc", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_conv2d", + srcs = [ + "test_op_quantized_conv2d.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_conv2d", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_depthwise_conv1d_ncl", + srcs = [ + "test_op_quantized_depthwise_conv1d_ncl.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_depthwise_conv1d_ncl", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_depthwise_conv1d_nlc", + srcs = [ + "test_op_quantized_depthwise_conv1d_nlc.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_depthwise_conv1d_nlc", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_fully_connected", + srcs = [ + "test_op_quantized_fully_connected.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_fully_connected", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_linear", + srcs = [ + "test_op_quantized_linear.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_linear", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_softmax", + srcs = [ + "test_op_quantized_softmax.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_softmax", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_quantized_linear_packed", + srcs = [ + "test_quantized_linear_packed.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_fully_connected", + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_fully_connected_packed", + "fbsource//xplat/executorch/backends/cadence/generic/operators:quantized_linear", + "fbsource//xplat/executorch/backends/cadence/generic/operators:quantized_linear_packed", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_im2row", + srcs = [ + "test_op_im2row.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_im2row", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_add", + srcs = [ + "test_op_quantized_add.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_add", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_matmul", + srcs = [ + "test_op_quantized_matmul.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_matmul", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_max_pool2d", + srcs = [ + "test_op_quantized_max_pool2d.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_max_pool2d", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_mul", + srcs = [ + "test_op_quantized_mul.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_mul", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_linalg_svd", + srcs = [ + "test_op_linalg_svd.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_linalg_svd", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_quantized_embedding_byte", + srcs = [ + "test_op_quantized_embedding_byte.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_quantized_embedding_byte", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_roi_align_box_processor", + srcs = [ + "test_op_roi_align_box_processor.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_roi_align_box_processor", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_rope", + srcs = [ + "test_op_rope.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_rope", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_sdpa_bitwise_causal_mask_gen", + srcs = [ + "test_op_sdpa_bitwise_causal_mask_gen.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_sdpa_bitwise_causal_mask_gen", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) + +jarvis_wrapper.cxx_test( + name = "test_op_where_scalar", + srcs = [ + "test_op_where_scalar.cpp", + ], + compatible_backends = ["generic"], + labels = [ci.linux(ci.mode("fbsource//arvr/mode/platform010/dev"))], + platforms = CXX, + visibility = [ + "fbsource//xplat/executorch/backends/cadence/...", + "fbcode//executorch/backends/cadence/...", + ], + deps = [ + "fbsource//xplat/executorch/backends/cadence/generic/operators:op_where_scalar", + "fbsource//xplat/executorch/kernels/test:gtest_utils", + "fbsource//xplat/executorch/runtime/core/exec_aten/testing_util:tensor_util", + ], +) diff --git a/backends/cadence/generic/operators/tests/CMakeLists.txt b/backends/cadence/generic/operators/tests/CMakeLists.txt index 199510da476..ea59f48a0f6 100644 --- a/backends/cadence/generic/operators/tests/CMakeLists.txt +++ b/backends/cadence/generic/operators/tests/CMakeLists.txt @@ -4,11 +4,11 @@ # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # -# gtest op-level tests for the Cadence generic (reference) backend, -# cross-compiled for Xtensa and run on the Instruction Set Simulator (xt-run). -# Each test calls the kernel directly (impl::generic::native::) and checks -# with EXPECT_TENSOR_EQ, mirroring the BUCK tests. Built only when -# EXECUTORCH_BUILD_CADENCE_OP_TESTS is ON; see .ci/scripts/test-cadence-xtensa.sh. +# gtest op-level tests for the Cadence generic (reference) backend, built for the +# host (.ci/scripts/test-cadence-generic.sh) or cross-compiled for Xtensa and run +# on the Instruction Set Simulator (xt-run). Each test calls the kernel directly +# (impl::generic::native::) and checks with EXPECT_TENSOR_EQ, mirroring the +# BUCK tests. Built only when EXECUTORCH_BUILD_CADENCE_OP_TESTS is ON. cmake_minimum_required(VERSION 3.19) @@ -16,19 +16,21 @@ cmake_minimum_required(VERSION 3.19) # -Werror -Wconversion on its own sources, which clang-10 trips (e.g. an int -> # signed char narrowing in gtest-port.h); -Wno-error keeps those non-fatal. A # ccache launcher also preprocesses then recompiles the .i, where the -I dirs -# are unused and clang warns; -Qunused-arguments silences that. These land after -# googletest's own flags, so they win, and apply to this whole subtree. -add_compile_options(-Qunused-arguments -Wno-error) +# are unused and clang warns; -Qunused-arguments silences that (GCC rejects the +# flag). These land after googletest's own flags, so they win, and apply to this +# whole subtree. +add_compile_options(-Wno-error $<$:-Qunused-arguments>) # Let files say "include ". set(_common_include_directories ${EXECUTORCH_ROOT}/.. ${EXECUTORCH_ROOT}/runtime/core/portable_type/c10 ) -# Build googletest FOR the Xtensa target. find_package(GTest) would resolve the -# HOST gtest, which cannot link Xtensa objects, so add the source tree instead. -# The cadence toolchain uses -stdlib=libc++ (exceptions/RTTI/iostream -# available); the ISS is single-threaded, so disable pthreads. +# Build googletest with the same compiler as the tests. On Xtensa, +# find_package(GTest) would resolve the HOST gtest, which cannot link Xtensa +# objects, so add the source tree instead. The cadence toolchain uses +# -stdlib=libc++ (exceptions/RTTI/iostream available); the ISS is +# single-threaded, so disable pthreads. if(NOT TARGET gtest) set(gtest_disable_pthreads ON @@ -48,8 +50,31 @@ endif() # checks with EXPECT_TENSOR_EQ, mirroring the BUCK tests. add_executable( cadence_generic_op_tests - test_op_quantized_layer_norm.cpp test_op_sdpa_bitwise_mask_gen.cpp + test_op_avg_pool2d.cpp + test_op_fully_connected.cpp + test_op_im2row.cpp + test_op_linalg_svd.cpp + test_op_quantized_add.cpp + test_op_quantized_conv1d_ncl.cpp + test_op_quantized_conv1d_nlc.cpp + test_op_quantized_conv2d.cpp + test_op_quantized_depthwise_conv1d_ncl.cpp + test_op_quantized_depthwise_conv1d_nlc.cpp + test_op_quantized_embedding_byte.cpp + test_op_quantized_fully_connected.cpp + test_op_quantized_layer_norm.cpp + test_op_quantized_linear.cpp + test_op_quantized_matmul.cpp + test_op_quantized_max_pool2d.cpp + test_op_quantized_mul.cpp + test_op_quantized_softmax.cpp + test_op_roi_align_box_processor.cpp + test_op_rope.cpp + test_op_sdpa_bitwise_causal_mask_gen.cpp + test_op_sdpa_bitwise_mask_gen.cpp test_op_sdpa_bitwise_ring_mask_gen.cpp + test_op_where_scalar.cpp + test_quantized_linear_packed.cpp ${EXECUTORCH_ROOT}/runtime/core/exec_aten/testing_util/tensor_util.cpp ) target_compile_definitions(cadence_generic_op_tests PRIVATE GTEST_HAS_PTHREAD=0) diff --git a/backends/cadence/generic/operators/tests/test_op_avg_pool2d.cpp b/backends/cadence/generic/operators/tests/test_op_avg_pool2d.cpp new file mode 100644 index 00000000000..3d34f91edee --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_avg_pool2d.cpp @@ -0,0 +1,157 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::IntArrayRef; +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// Expected values are torch.nn.functional.avg_pool2d's for the same arguments. +class GenericAvgPool2dTest : public OperatorTest { + protected: + Tensor& avg_pool2d_out( + const Tensor& input, + std::array kernel_size, + std::array stride, + std::array padding, + bool count_include_pad, + std::optional divisor_override, + Tensor& out) { + return impl::generic::native::avg_pool2d_out( + context_, + input, + IntArrayRef(kernel_size.data(), kernel_size.size()), + IntArrayRef(stride.data(), stride.size()), + IntArrayRef(padding.data(), padding.size()), + /*ceil_mode=*/true, + count_include_pad, + divisor_override, + /*in_zero_point_t=*/std::nullopt, + /*channel_last=*/false, + out); + } + + TensorFactory tf_; +}; + +// A 1x3 kernel with stride 2 over 6 values: ceil_mode adds a third window that +// covers only the last 2 values, so its divisor is 2, not 3. +TEST_F(GenericAvgPool2dTest, CeilModeLastWindowIncludePad) { + Tensor input = tf_.make({1, 1, 1, 6}, {1, 2, 3, 4, 5, 6}); + Tensor out = tf_.zeros({1, 1, 1, 3}); + + avg_pool2d_out(input, {1, 3}, {1, 2}, {0, 0}, true, std::nullopt, out); + + EXPECT_TENSOR_EQ(out, tf_.make({1, 1, 1, 3}, {2.0, 4.0, 5.5})); +} + +TEST_F(GenericAvgPool2dTest, CeilModeLastWindowExcludePad) { + Tensor input = tf_.make({1, 1, 1, 6}, {1, 2, 3, 4, 5, 6}); + Tensor out = tf_.zeros({1, 1, 1, 3}); + + avg_pool2d_out(input, {1, 3}, {1, 2}, {0, 0}, false, std::nullopt, out); + + EXPECT_TENSOR_EQ(out, tf_.make({1, 1, 1, 3}, {2.0, 4.0, 5.5})); +} + +// Padding of 1 on both sides: the first window covers 1 padding value and 2 +// inputs, and the last covers 1 input, 1 padding value and 1 position past the +// padding, which counts toward no divisor. +TEST_F(GenericAvgPool2dTest, CeilModePaddedIncludePad) { + Tensor input = tf_.make({1, 1, 1, 6}, {1, 2, 3, 4, 5, 6}); + Tensor out = tf_.zeros({1, 1, 1, 4}); + + avg_pool2d_out(input, {1, 3}, {1, 2}, {0, 1}, true, std::nullopt, out); + + EXPECT_TENSOR_EQ(out, tf_.make({1, 1, 1, 4}, {1.0, 3.0, 5.0, 3.0})); +} + +TEST_F(GenericAvgPool2dTest, CeilModePaddedExcludePad) { + Tensor input = tf_.make({1, 1, 1, 6}, {1, 2, 3, 4, 5, 6}); + Tensor out = tf_.zeros({1, 1, 1, 4}); + + avg_pool2d_out(input, {1, 3}, {1, 2}, {0, 1}, false, std::nullopt, out); + + EXPECT_TENSOR_EQ(out, tf_.make({1, 1, 1, 4}, {1.5, 3.0, 5.0, 6.0})); +} + +TEST_F(GenericAvgPool2dTest, CeilModeDivisorOverride) { + Tensor input = tf_.make({1, 1, 1, 6}, {1, 2, 3, 4, 5, 6}); + Tensor out = tf_.zeros({1, 1, 1, 4}); + + avg_pool2d_out(input, {1, 3}, {1, 2}, {0, 1}, true, 2, out); + + EXPECT_TENSOR_EQ(out, tf_.make({1, 1, 1, 4}, {1.5, 4.5, 7.5, 3.0})); +} + +// A 2x2 kernel with stride 2 over 3x3: the windows on the last row and column +// cover 2, 2 and 1 inputs. +TEST_F(GenericAvgPool2dTest, CeilModeTwoDimensions) { + Tensor input = tf_.make({1, 1, 3, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + Tensor out = tf_.zeros({1, 1, 2, 2}); + + avg_pool2d_out(input, {2, 2}, {2, 2}, {0, 0}, true, std::nullopt, out); + + EXPECT_TENSOR_EQ(out, tf_.make({1, 1, 2, 2}, {3.0, 4.5, 7.5, 9.0})); +} + +// The uint8 path pads with the zero point, and the last window covers 140, the +// zero point and a position past the padding: (140 + 128) / 2 = 134. +TEST_F(GenericAvgPool2dTest, CeilModePaddedIncludePadUint8) { + TensorFactory tf_uint8; + TensorFactory tf_int; + Tensor input = tf_uint8.make({1, 1, 1, 6}, {130, 132, 134, 136, 138, 140}); + Tensor out = tf_uint8.zeros({1, 1, 1, 4}); + const std::array kernel_size{1, 3}, stride{1, 2}, padding{0, 1}; + + impl::generic::native::avg_pool2d_out( + context_, + input, + IntArrayRef(kernel_size.data(), kernel_size.size()), + IntArrayRef(stride.data(), stride.size()), + IntArrayRef(padding.data(), padding.size()), + /*ceil_mode=*/true, + /*count_include_pad=*/true, + /*divisor_override=*/std::nullopt, + tf_int.make({1}, {128}), + /*channel_last=*/false, + out); + + EXPECT_TENSOR_EQ(out, tf_uint8.make({1, 1, 1, 4}, {130, 134, 138, 134})); +} + +TEST_F(GenericAvgPool2dTest, RejectsUnsupportedDtype) { + TensorFactory tf_int; + Tensor input = tf_int.make({1, 1, 1, 6}, {1, 2, 3, 4, 5, 6}); + Tensor out = tf_int.zeros({1, 1, 1, 3}); + + ET_EXPECT_KERNEL_FAILURE( + context_, + avg_pool2d_out(input, {1, 3}, {1, 2}, {0, 0}, true, std::nullopt, out)); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_fully_connected.cpp b/backends/cadence/generic/operators/tests/test_op_fully_connected.cpp new file mode 100644 index 00000000000..15cfc2df52a --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_fully_connected.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include + +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +class GenericFullyConnectedTest : public OperatorTest { + protected: + TensorFactory tf_; +}; + +// Each of the 2 leading rows gets its own output row. +TEST_F(GenericFullyConnectedTest, ComputesEveryLeadingRow) { + Tensor input = tf_.make({2, 1, 3}, {1, 2, 3, 4, 5, 6}); + Tensor weight = tf_.make({2, 3}, {1, 0, -1, 0.5, 0.5, 0.5}); + Tensor bias = tf_.make({2}, {10, 20}); + Tensor out = tf_.zeros({2, 1, 2}); + + fully_connected_out(context_, input, weight, bias, out); + + EXPECT_TENSOR_EQ(out, tf_.make({2, 1, 2}, {8, 23, 8, 27.5})); +} + +TEST_F(GenericFullyConnectedTest, ComputesWithoutBias) { + Tensor input = tf_.make({2, 3}, {1, 2, 3, 4, 5, 6}); + Tensor weight = tf_.make({2, 3}, {1, 0, -1, 0.5, 0.5, 0.5}); + Tensor out = tf_.zeros({2, 2}); + + fully_connected_out(context_, input, weight, std::nullopt, out); + + EXPECT_TENSOR_EQ(out, tf_.make({2, 2}, {-2, 3, -2, 7.5})); +} + +TEST_F(GenericFullyConnectedTest, RejectsNonFloatDtype) { + TensorFactory tf_double; + Tensor input = tf_double.make({1, 3}, {1, 2, 3}); + Tensor weight = tf_double.make({2, 3}, {1, 0, -1, 0.5, 0.5, 0.5}); + Tensor out = tf_double.zeros({1, 2}); + + ET_EXPECT_KERNEL_FAILURE( + context_, + fully_connected_out(context_, input, weight, std::nullopt, out)); +} + +TEST_F(GenericFullyConnectedTest, RejectsMismatchedInnerDim) { + Tensor input = tf_.make({1, 4}, {1, 2, 3, 4}); + Tensor weight = tf_.make({2, 3}, {1, 0, -1, 0.5, 0.5, 0.5}); + Tensor out = tf_.zeros({1, 2}); + + ET_EXPECT_KERNEL_FAILURE( + context_, + fully_connected_out(context_, input, weight, std::nullopt, out)); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_im2row.cpp b/backends/cadence/generic/operators/tests/test_op_im2row.cpp new file mode 100644 index 00000000000..89df769828e --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_im2row.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include + +#include +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::IntArrayRef; +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +IntArrayRef ref(const std::array& values) { + return IntArrayRef(values.data(), values.size()); +} + +// Expected values are aot/ref_implementations.py's. The output is +// [N, out_h * out_w, C * kernel_h * kernel_w], one row per output position. +class GenericIm2rowTest : public OperatorTest {}; + +// A 2x2 kernel with stride 2 and padding 1 over 3x3: padded positions hold the +// zero point. +TEST_F(GenericIm2rowTest, PerTensorPadsWithTheZeroPoint) { + TensorFactory tf; + const Tensor input = tf.make({1, 1, 3, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + Tensor out = tf.zeros({1, 4, 4}); + const std::array kernel{2, 2}, dilation{1, 1}, padding{1, 1}, + stride{2, 2}; + + im2row_per_tensor_out( + context_, + input, + ref(kernel), + ref(dilation), + ref(padding), + ref(stride), + 7, + /*channel_last=*/false, + out); + + EXPECT_TENSOR_EQ( + out, + tf.make({1, 4, 4}, {7, 7, 7, 1, 7, 7, 2, 3, 7, 4, 7, 7, 5, 6, 8, 9})); +} + +// A zero-point tensor with one entry per batch pads each batch with its own. +TEST_F(GenericIm2rowTest, ZeroPointPerBatch) { + TensorFactory tf; + TensorFactory tf_int; + const Tensor input = tf.make({2, 1, 1, 1}, {5, -6}); + Tensor out = tf.zeros({2, 4, 4}); + const std::array kernel{2, 2}, dilation{1, 1}, padding{1, 1}, + stride{1, 1}; + + im2row_out( + context_, + input, + ref(kernel), + ref(dilation), + ref(padding), + ref(stride), + tf_int.make({2}, {3, -4}), + /*channel_last=*/false, + out); + + EXPECT_TENSOR_EQ( + out, tf.make({2, 4, 4}, {3, 3, 3, 5, 3, 3, 5, 3, 3, 5, 3, + 3, 5, 3, 3, 3, -4, -4, -4, -6, -4, -4, + -6, -4, -4, -6, -4, -4, -6, -4, -4, -4})); +} + +// NHWC input; the output row is laid out [C][kernel position], as for NCHW, +// and padded positions hold the zero point. +TEST_F(GenericIm2rowTest, ChannelLast) { + TensorFactory tf; + const Tensor input = tf.make({1, 2, 2, 2}, {1, 10, 2, 20, 3, 30, 4, 40}); + Tensor out = tf.zeros({1, 4, 8}); + const std::array kernel{2, 2}, dilation{1, 1}, padding{1, 1}, + stride{2, 2}; + + im2row_per_tensor_out( + context_, + input, + ref(kernel), + ref(dilation), + ref(padding), + ref(stride), + 7, + /*channel_last=*/true, + out); + + EXPECT_TENSOR_EQ(out, tf.make({1, 4, 8}, {7, 7, 7, 1, 7, 7, 7, 10, 7, 7, 2, + 7, 7, 7, 20, 7, 7, 3, 7, 7, 7, 30, + 7, 7, 4, 7, 7, 7, 40, 7, 7, 7})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_linalg_svd.cpp b/backends/cadence/generic/operators/tests/test_op_linalg_svd.cpp new file mode 100644 index 00000000000..e4d46de59a1 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_linalg_svd.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include + +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +constexpr float kTol = 1e-4; + +// The singular values are unique, so the test compares them with +// torch.linalg.svdvals. The signs of the singular vectors are not, so it checks +// that U and Vh are orthogonal and reconstruct A. +class GenericLinalgSvdTest : public OperatorTest { + protected: + void expect_valid_svd( + const Tensor& a, + const Tensor& u, + const Tensor& s, + const Tensor& vh, + const std::vector& expected_s) { + const ssize_t batch = a.numel() / 9; + for (ssize_t b = 0; b < batch; ++b) { + const float* A = a.const_data_ptr() + 9 * b; + const float* U = u.const_data_ptr() + 9 * b; + const float* S = s.const_data_ptr() + 3 * b; + const float* V = vh.const_data_ptr() + 9 * b; + const float scale = std::max(1.0f, S[0]); + for (int k = 0; k < 3; ++k) { + EXPECT_NEAR(S[k], expected_s[3 * b + k], kTol * scale) << "batch " << b; + } + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + // U * diag(S) * Vh reconstructs A. + float usv = 0, utu = 0, vvt = 0; + for (int k = 0; k < 3; ++k) { + usv += U[i * 3 + k] * S[k] * V[k * 3 + j]; + utu += U[k * 3 + i] * U[k * 3 + j]; + vvt += V[i * 3 + k] * V[j * 3 + k]; + } + const float eye = i == j ? 1.0f : 0.0f; + EXPECT_NEAR(usv, A[i * 3 + j], kTol * scale) << "batch " << b; + // U and Vh are orthogonal. + EXPECT_NEAR(utu, eye, kTol) << "batch " << b; + EXPECT_NEAR(vvt, eye, kTol) << "batch " << b; + } + } + } + } + + TensorFactory tf_; +}; + +// A general matrix and a rank-deficient one, as a batch of two. +TEST_F(GenericLinalgSvdTest, DecomposesABatch) { + const Tensor a = tf_.make( + {2, 3, 3}, + {4.0, + -2.0, + 1.0, + 3.0, + 6.0, + -4.0, + 2.0, + 1.0, + 8.0, + 1.0, + 2.0, + 3.0, + 2.0, + 4.0, + 6.0, + -1.0, + 0.5, + 2.0}); + Tensor u = tf_.zeros({2, 3, 3}); + Tensor s = tf_.zeros({2, 3}); + Tensor vh = tf_.zeros({2, 3, 3}); + + linalg_svd_out(context_, a, false, true, std::nullopt, u, s, vh); + + // The second matrix has rank 2. + expect_valid_svd( + a, u, s, vh, {9.385550, 6.763656, 4.142996, 8.524661, 1.606288, 0.0}); +} + +TEST_F(GenericLinalgSvdTest, RejectsNonFloatInput) { + TensorFactory tf_double; + const Tensor a = tf_double.ones({3, 3}); + Tensor u = tf_.zeros({3, 3}); + Tensor s = tf_.zeros({3}); + Tensor vh = tf_.zeros({3, 3}); + + ET_EXPECT_KERNEL_FAILURE( + context_, + linalg_svd_out(context_, a, false, true, std::nullopt, u, s, vh)); +} + +TEST_F(GenericLinalgSvdTest, RejectsMatricesThatAreNot3x3) { + const Tensor a = tf_.ones({2, 2}); + Tensor u = tf_.zeros({2, 2}); + Tensor s = tf_.zeros({2}); + Tensor vh = tf_.zeros({2, 2}); + + ET_EXPECT_KERNEL_FAILURE( + context_, + linalg_svd_out(context_, a, false, true, std::nullopt, u, s, vh)); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_add.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_add.cpp new file mode 100644 index 00000000000..6fe766e85ae --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_add.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// Expected values are aot/ref_implementations.py's. Scales are powers of two, +// so every intermediate value is exact. +class GenericQuantizedAddTest : public OperatorTest {}; + +TEST_F(GenericQuantizedAddTest, PerTensor) { + TensorFactory tf; + const Tensor x = tf.make({2, 3}, {-10, 0, 20, 5, -5, 50}); + const Tensor y = tf.make({2, 3}, {10, 20, 30, 1, 2, 3}); + Tensor out = tf.zeros({2, 3}); + + quantized_add_per_tensor_out(context_, x, 0.5, 0, y, 0.25, 2, 0.25, -3, out); + + EXPECT_TENSOR_EQ(out, tf.make({2, 3}, {-15, 15, 65, 6, -13, 98})); +} + +// Y broadcasts along dim 0, and sums past the int8 range saturate. +TEST_F(GenericQuantizedAddTest, Asym8sBroadcastsAndSaturates) { + TensorFactory tf; + const Tensor x = tf.make({2, 3}, {100, -100, 60, 127, -128, 0}); + const Tensor y = tf.make({1, 3}, {100, -100, 10}); + Tensor out = tf.zeros({2, 3}); + + quantized_add_asym8sxasym8s_asym8s_per_tensor_out( + context_, x, 0.5, 0, y, 0.5, 0, 0.5, 0, out); + + EXPECT_TENSOR_EQ(out, tf.make({2, 3}, {127, -128, 70, 127, -128, 10})); +} + +TEST_F(GenericQuantizedAddTest, Asym8uSaturatesAtBothEnds) { + TensorFactory tf; + const Tensor x = tf.make({2, 3}, {130, 120, 255, 0, 128, 200}); + const Tensor y = tf.make({2, 3}, {140, 110, 255, 0, 128, 10}); + Tensor out = tf.zeros({2, 3}); + + quantized_add_asym8uxasym8u_asym8u_per_tensor_out( + context_, x, 0.25, 128, y, 0.25, 128, 0.25, 128, out); + + EXPECT_TENSOR_EQ(out, tf.make({2, 3}, {142, 102, 255, 0, 128, 82})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_conv1d_ncl.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_conv1d_ncl.cpp new file mode 100644 index 00000000000..7fba09f8d33 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_conv1d_ncl.cpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include + +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::IntArrayRef; +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +class GenericQuantizedConv1dNclPerChannelTest : public OperatorTest { + protected: + static IntArrayRef ref(const std::array& a) { + return IntArrayRef(a.data(), a.size()); + } +}; + +// NCL layout: input [N, C, L]. +// Setup (int8, all zero_points = 0, output_scale = 1.0): +// input [1, 1, 4] = [[[1, 2, 3, 4]]] +// weight [3, 1, 1] = [[[2]], [[2]], [[2]]] (kernel_size = 1) +// bias [3] = [0, 0, 0] +// weight_zero_point [3] = [1, 0, 2] +// -> effective weight per output channel: 1, 2, 0 +// bias_scale [3] = [1.0f, 5.0f, 10.0f] +// +// Per-position accumulator per output channel: +// ch 0: acc = input * 1 -> [1, 2, 3, 4] +// ch 1: acc = input * 2 -> [2, 4, 6, 8] +// ch 2: acc = input * 0 -> [0, 0, 0, 0] +// +// Output NCL [1, 3, 4]: +// ch 0 (bs=1.0): [ 1, 2, 3, 4] +// ch 1 (bs=5.0): [10, 20, 30, 40] +// ch 2 (bs=10.0): [ 0, 0, 0, 0] +TEST_F(GenericQuantizedConv1dNclPerChannelTest, PerChannelCorrectnessInt8) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make({1, 1, 4}, {1, 2, 3, 4}); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({3}, {1, 0, 2}); + Tensor bias_scale = tf_float.make({3}, {1.0f, 5.0f, 10.0f}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + Tensor out = tf_int8.zeros({1, 3, 4}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + quantized_conv1d_ncl_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out); + + Tensor expected = tf_int8.make( + {1, 3, 4}, + { + /*ch 0*/ 1, + 2, + 3, + 4, + /*ch 1*/ 10, + 20, + 30, + 40, + /*ch 2*/ 0, + 0, + 0, + 0, + }); + EXPECT_TENSOR_EQ(out, expected); +} + +// Degeneracy: length-1 qparam tensors on .out must match the +// existing _out kernel (which itself only uses element 0). +TEST_F(GenericQuantizedConv1dNclPerChannelTest, LengthOneMatchesQuantizedOut) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make({1, 1, 4}, {1, 2, 3, 4}); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + + Tensor weight_zero_point = tf_int32.make({1}, {1}); + Tensor bias_scale = tf_float.make({1}, {5.0f}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + Tensor out_pc = tf_int8.zeros({1, 3, 4}); + quantized_conv1d_ncl_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out_pc); + + // The scalar-qparam overload is the reference: a length-1 qparam vector has + // to mean exactly what a scalar qparam means. + Tensor out_ref = tf_int8.zeros({1, 3, 4}); + quantized_conv1d_ncl_per_tensor_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*input_zero_point=*/0, + /*weight_zero_point=*/1, + /*bias_scale=*/5.0, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + /*out_multiplier=*/0, + /*out_shift=*/0, + out_ref); + + EXPECT_TENSOR_EQ(out_pc, out_ref); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_conv1d_nlc.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_conv1d_nlc.cpp new file mode 100644 index 00000000000..b469eaac9bd --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_conv1d_nlc.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::IntArrayRef; +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +class GenericQuantizedConv1dNlcPerChannelTest : public OperatorTest { + protected: + static IntArrayRef ref(const std::array& a) { + return IntArrayRef(a.data(), a.size()); + } +}; + +// NLC layout: input [N, L, C], weight [OC, WW, WC]. +// Same numeric construction as NCL, reinterpreted for NLC. +// input [1, 4, 1] = [1, 2, 3, 4] (single input channel, length 4) +// weight [3, 1, 1] = [2, 2, 2] (oc=3, ww=1, wc=1) +// bias [3] = [0, 0, 0] +// weight_zero_point [3] = [1, 0, 2] +// -> effective weight per output channel: 1, 2, 0 +// bias_scale [3] = [1.0f, 5.0f, 10.0f] +// +// Output NLC [1, 4, 3], laid out as position-major: +// pos 0: [ 1, 10, 0] +// pos 1: [ 2, 20, 0] +// pos 2: [ 3, 30, 0] +// pos 3: [ 4, 40, 0] +TEST_F(GenericQuantizedConv1dNlcPerChannelTest, PerChannelCorrectnessInt8) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make({1, 4, 1}, {1, 2, 3, 4}); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({3}, {1, 0, 2}); + Tensor bias_scale = tf_float.make({3}, {1.0f, 5.0f, 10.0f}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + Tensor out = tf_int8.zeros({1, 4, 3}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + quantized_conv1d_nlc_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out); + + Tensor expected = tf_int8.make( + {1, 4, 3}, + { + /*pos 0*/ 1, + 10, + 0, + /*pos 1*/ 2, + 20, + 0, + /*pos 2*/ 3, + 30, + 0, + /*pos 3*/ 4, + 40, + 0, + }); + EXPECT_TENSOR_EQ(out, expected); +} + +// Degeneracy: length-1 qparam tensors on .out must match the +// existing _out kernel. +TEST_F(GenericQuantizedConv1dNlcPerChannelTest, LengthOneMatchesQuantizedOut) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make({1, 4, 1}, {1, 2, 3, 4}); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + + Tensor weight_zero_point = tf_int32.make({1}, {1}); + Tensor bias_scale = tf_float.make({1}, {5.0f}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + Tensor out_pc = tf_int8.zeros({1, 4, 3}); + quantized_conv1d_nlc_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out_pc); + + // The scalar-qparam overload is the reference: a length-1 qparam vector has + // to mean exactly what a scalar qparam means. + Tensor out_ref = tf_int8.zeros({1, 4, 3}); + quantized_conv1d_nlc_per_tensor_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*input_zero_point=*/0, + /*weight_zero_point=*/1, + /*bias_scale=*/5.0, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + /*out_multiplier=*/0, + /*out_shift=*/0, + /*offset=*/std::nullopt, + out_ref); + + EXPECT_TENSOR_EQ(out_pc, out_ref); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_conv2d.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_conv2d.cpp new file mode 100644 index 00000000000..5cd54f8c592 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_conv2d.cpp @@ -0,0 +1,438 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::IntArrayRef; +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +class GenericQuantizedConv2dPerChannelTest : public OperatorTest { + protected: + static IntArrayRef ref(const std::array& a) { + return IntArrayRef(a.data(), a.size()); + } +}; + +// ------------------------------------------------------------------ +// NCHW per-channel correctness. +// ------------------------------------------------------------------ +// Setup (int8, all input/output zero_points = 0, output_scale = 1.0): +// input [1,1,2,2] = [[[[1,2],[3,4]]]] +// weight [3,1,1,1] = [[[[2]]],[[[2]]],[[[2]]]] (3 output channels) +// bias [3] = [0, 0, 0] +// weight_zero_point [3] = [1, 0, 2] +// -> effective weight per channel = 2 - wzp[oc]: 1, 2, 0 +// bias_scale [3] = [1.0f, 5.0f, 10.0f] +// +// Per-pixel accumulator (single 1x1 kernel, single input channel): +// ch 0: acc = input * 1 -> [1, 2, 3, 4] +// ch 1: acc = input * 2 -> [2, 4, 6, 8] +// ch 2: acc = input * 0 -> [0, 0, 0, 0] +// +// Requantize: out = clamp(nearbyint((bias_scale[oc] * acc) / output_scale)) +// ch 0 (bs=1.0): [ 1, 2, 3, 4] +// ch 1 (bs=5.0): [10, 20, 30, 40] +// ch 2 (bs=10.0): [ 0, 0, 0, 0] +// +// A regression that reads channel 0's qparams for every channel would give +// [1,2,3,4, 1,2,3,4, 1,2,3,4] instead of the expected output. +TEST_F(GenericQuantizedConv2dPerChannelTest, NchwPerChannelCorrectnessInt8) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make({1, 1, 2, 2}, {1, 2, 3, 4}); + Tensor weight = tf_int8.make({3, 1, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({3}, {1, 0, 2}); + Tensor bias_scale = tf_float.make({3}, {1.0f, 5.0f, 10.0f}); + // Unused for conv. + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + Tensor out = tf_int8.zeros({1, 3, 2, 2}); + + std::array stride_arr = {1, 1}; + std::array padding_arr = {0, 0}; + std::array dilation_arr = {1, 1}; + + quantized_conv2d_nchw_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*in_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out); + + Tensor expected = tf_int8.make( + {1, 3, 2, 2}, + { + /*ch 0*/ 1, + 2, + 3, + 4, + /*ch 1*/ 10, + 20, + 30, + 40, + /*ch 2*/ 0, + 0, + 0, + 0, + }); + EXPECT_TENSOR_EQ(out, expected); +} + +// NCHW degeneracy: length-1 qparam tensors -> stride 0 -> same as per-tensor. +TEST_F(GenericQuantizedConv2dPerChannelTest, NchwLengthOneMatchesPerTensor) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make({1, 1, 2, 2}, {1, 2, 3, 4}); + Tensor weight = tf_int8.make({3, 1, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + const int32_t scalar_wzp = 1; + const float scalar_bs = 5.0f; + + Tensor weight_zero_point = tf_int32.make({1}, {scalar_wzp}); + Tensor bias_scale = tf_float.make({1}, {scalar_bs}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + + std::array stride_arr = {1, 1}; + std::array padding_arr = {0, 0}; + std::array dilation_arr = {1, 1}; + + Tensor out_pc = tf_int8.zeros({1, 3, 2, 2}); + quantized_conv2d_nchw_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*in_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out_pc); + + Tensor out_pt = tf_int8.zeros({1, 3, 2, 2}); + quantized_conv2d_nchw_per_tensor_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*in_zero_point=*/0, + /*weight_zero_point=*/scalar_wzp, + /*bias_scale=*/scalar_bs, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + /*out_multiplier=*/0, + /*out_shift=*/0, + out_pt); + + EXPECT_TENSOR_EQ(out_pc, out_pt); +} + +// ------------------------------------------------------------------ +// NHWC per-channel correctness. +// ------------------------------------------------------------------ +// Same numeric construction as NCHW, but interpreted in NHWC. +// input NHWC [1,2,2,1] = elements [1, 2, 3, 4] (same values, single channel) +// weight (regular NHWC layout [OC, KH, KW, WC]) [3, 1, 1, 1] = [2, 2, 2] +// -> accumulator per pixel per channel same as NCHW test. +// Output NHWC [1, 2, 2, 3]: +// pixel (0,0): [ 1, 10, 0] +// pixel (0,1): [ 2, 20, 0] +// pixel (1,0): [ 3, 30, 0] +// pixel (1,1): [ 4, 40, 0] +TEST_F(GenericQuantizedConv2dPerChannelTest, NhwcPerChannelCorrectnessInt8) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make({1, 2, 2, 1}, {1, 2, 3, 4}); + // Regular NHWC weight layout: [OC, KH, KW, WC] + Tensor weight = tf_int8.make({3, 1, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({3}, {1, 0, 2}); + Tensor bias_scale = tf_float.make({3}, {1.0f, 5.0f, 10.0f}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + Tensor out = tf_int8.zeros({1, 2, 2, 3}); + + std::array stride_arr = {1, 1}; + std::array padding_arr = {0, 0}; + std::array dilation_arr = {1, 1}; + + quantized_conv2d_nhwc_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*in_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out); + + Tensor expected = tf_int8.make( + {1, 2, 2, 3}, + { + /*pixel (0,0):*/ 1, + 10, + 0, + /*pixel (0,1):*/ 2, + 20, + 0, + /*pixel (1,0):*/ 3, + 30, + 0, + /*pixel (1,1):*/ 4, + 40, + 0, + }); + EXPECT_TENSOR_EQ(out, expected); +} + +// NHWC degeneracy: length-1 qparam tensors -> same as per_tensor path. +TEST_F(GenericQuantizedConv2dPerChannelTest, NhwcLengthOneMatchesPerTensor) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make({1, 2, 2, 1}, {1, 2, 3, 4}); + Tensor weight = tf_int8.make({3, 1, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + const int32_t scalar_wzp = 1; + const float scalar_bs = 5.0f; + + Tensor weight_zero_point = tf_int32.make({1}, {scalar_wzp}); + Tensor bias_scale = tf_float.make({1}, {scalar_bs}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + + std::array stride_arr = {1, 1}; + std::array padding_arr = {0, 0}; + std::array dilation_arr = {1, 1}; + + Tensor out_pc = tf_int8.zeros({1, 2, 2, 3}); + quantized_conv2d_nhwc_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*in_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out_pc); + + Tensor out_pt = tf_int8.zeros({1, 2, 2, 3}); + quantized_conv2d_nhwc_per_tensor_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*in_zero_point=*/0, + /*weight_zero_point=*/scalar_wzp, + /*bias_scale=*/scalar_bs, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + /*out_multiplier=*/0, + /*out_shift=*/0, + /*offset=*/std::nullopt, + out_pt); + + EXPECT_TENSOR_EQ(out_pc, out_pt); +} + +// ------------------------------------------------------------------ +// Depthwise NHWC. +// ------------------------------------------------------------------ +// NOTE: this entry point currently declares scalar (int64_t/double) qparams +// in its signature, so it is *not possible* to exercise real per-channel +// qparams through this API. We can only exercise the scalar (degeneracy) +// path here. The signature bug is called out in the report accompanying +// these tests. +// +// Depthwise is a specialisation of the general grouped convolution, so the +// general NHWC kernel with groups == channels is the reference. Note the +// weight layouts differ: depthwise packs it as [KH, KW, OC], the general path +// as [OC, KH, KW, IC/groups]. +TEST_F( + GenericQuantizedConv2dPerChannelTest, + DepthwiseNhwcMatchesGeneralGroupedConv) { + TensorFactory tf_int8; + TensorFactory tf_int32; + + // input NHWC [1, 2, 2, 3] -- 3 channels + Tensor input = tf_int8.make( + {1, 2, 2, 3}, + { + 1, + 2, + 3, // pixel (0,0) + 4, + 5, + 6, // pixel (0,1) + 7, + 8, + 9, // pixel (1,0) + 10, + 11, + 12, // pixel (1,1) + }); + // Depthwise weight NHWC layout: [KH, KW, OC] (no IC dim). + Tensor weight = tf_int8.make({1, 1, 3}, {2, 3, 4}); + Tensor bias = tf_int32.zeros({3}); + + const int64_t scalar_wzp = 1; + const double scalar_bs = 1.0; + + std::array stride_arr = {1, 1}; + std::array padding_arr = {0, 0}; + std::array dilation_arr = {1, 1}; + + Tensor out_pc = tf_int8.zeros({1, 2, 2, 3}); + quantized_conv2d_depthwise_nhwc_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*in_zero_point=*/0, + scalar_wzp, + scalar_bs, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + /*out_multiplier=*/0, + /*out_shift=*/0, + out_pc); + + Tensor weight_general = tf_int8.make({3, 1, 1, 1}, {2, 3, 4}); + Tensor out_ref = tf_int8.zeros({1, 2, 2, 3}); + quantized_conv2d_nhwc_per_tensor_out( + context_, + input, + weight_general, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*in_zero_point=*/0, + scalar_wzp, + scalar_bs, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + /*out_multiplier=*/0, + /*out_shift=*/0, + /*offset=*/std::nullopt, + out_ref); + + EXPECT_TENSOR_EQ(out_pc, out_ref); +} + +// The uint8 typed NHWC entry. Expected values are aot/ref_implementations.py's: +// with both zero points 128, the two 2x2 windows sum to -6 and 48, plus the +// biases 10 and -4, times bias_scale 0.5, over output_scale 0.25, plus 100. +TEST_F(GenericQuantizedConv2dPerChannelTest, NhwcAsym8uPerTensor) { + TensorFactory tf_uint8; + TensorFactory tf_int32; + Tensor input = tf_uint8.make({1, 2, 2, 1}, {130, 126, 132, 120}); + Tensor weight = + tf_uint8.make({2, 2, 2, 1}, {129, 130, 127, 128, 128, 128, 140, 128}); + Tensor bias = tf_int32.make({2}, {10, -4}); + Tensor out = tf_uint8.zeros({1, 1, 1, 2}); + std::array stride_arr = {1, 1}; + std::array padding_arr = {0, 0}; + std::array dilation_arr = {1, 1}; + + quantized_conv2d_nhwc_asym8uxsym8u_asym8u_per_tensor_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/1, + /*in_zero_point=*/128, + /*weight_zero_point=*/128, + /*bias_scale=*/0.5, + /*output_scale=*/0.25, + /*output_zero_point=*/100, + /*out_multiplier=*/0, + /*out_shift=*/0, + out); + + EXPECT_TENSOR_EQ(out, tf_uint8.make({1, 1, 1, 2}, {108, 188})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_depthwise_conv1d_ncl.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_depthwise_conv1d_ncl.cpp new file mode 100644 index 00000000000..c5a8d7e164c --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_depthwise_conv1d_ncl.cpp @@ -0,0 +1,341 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { + +// Forward declarations: the depthwise conv1d NCL entry points are defined in +// op_quantized_depthwise_conv1d_ncl.cpp but not exposed through a header. +::executorch::aten::Tensor& quantized_depthwise_conv1d_ncl_per_tensor_out( + ::executorch::runtime::KernelRuntimeContext& ctx, + const ::executorch::aten::Tensor& input, + const ::executorch::aten::Tensor& weight, + const ::executorch::aten::Tensor& bias, + ::executorch::aten::IntArrayRef stride, + ::executorch::aten::IntArrayRef padding, + ::executorch::aten::IntArrayRef dilation, + int64_t groups, + int64_t input_zero_point, + int64_t weight_zero_point, + double bias_scale, + double output_scale, + int64_t output_zero_point, + int64_t out_multiplier, + int64_t out_shift, + ::executorch::aten::Tensor& out); + +::executorch::aten::Tensor& quantized_depthwise_conv1d_ncl_out( + ::executorch::runtime::KernelRuntimeContext& ctx, + const ::executorch::aten::Tensor& input, + const ::executorch::aten::Tensor& weight, + const ::executorch::aten::Tensor& bias, + ::executorch::aten::IntArrayRef stride, + ::executorch::aten::IntArrayRef padding, + ::executorch::aten::IntArrayRef dilation, + int64_t groups, + int64_t input_zero_point, + const std::optional<::executorch::aten::Tensor>& weight_zero_point, + const ::executorch::aten::Tensor& bias_scale, + double output_scale, + int64_t output_zero_point, + const ::executorch::aten::Tensor& out_multiplier, + const ::executorch::aten::Tensor& out_shift, + ::executorch::aten::Tensor& out); + +namespace { + +using ::executorch::aten::IntArrayRef; +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +class GenericQuantizedDepthwiseConv1dNclPerChannelTest : public OperatorTest { + protected: + static IntArrayRef ref(const std::array& a) { + return IntArrayRef(a.data(), a.size()); + } +}; + +// Depthwise NCL layout: input [N, C, L], groups == C, weight [OC, 1, WW]. +// With channel_multiplier = 1, out_channels = in_channels = groups. +// Setup (int8, all zero_points = 0, output_scale = 1.0): +// input [1, 3, 4] rows per input channel: +// ic 0: [1, 2, 3, 4] +// ic 1: [2, 3, 4, 5] +// ic 2: [1, 1, 1, 1] +// weight [3, 1, 1] = [[[2]], [[2]], [[2]]] (kernel_size = 1) +// bias [3] = [0, 0, 0] +// weight_zero_point [3] = [1, 0, 2] +// -> effective weight per output channel: 1, 2, 0 +// bias_scale [3] = [1.0f, 2.0f, 5.0f] +// +// Because depthwise conv binds oc <-> ic, each output channel only reads its +// own input channel. +// Per-position accumulator per output channel: +// oc 0 (uses ic 0, w=1): [1, 2, 3, 4] +// oc 1 (uses ic 1, w=2): [4, 6, 8, 10] +// oc 2 (uses ic 2, w=0): [0, 0, 0, 0] +// +// Output NCL [1, 3, 4] after bias_scale * acc, quantized with out_scale=1: +// oc 0 (bs=1.0): [1, 2, 3, 4] +// oc 1 (bs=2.0): [8, 12, 16, 20] +// oc 2 (bs=5.0): [0, 0, 0, 0] +// +// These per-channel bias_scales are DISTINCT so the test would fail if the +// kernel incorrectly broadcast bias_scale[0] to every output channel. +TEST_F( + GenericQuantizedDepthwiseConv1dNclPerChannelTest, + PerChannelCorrectnessInt8) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make( + {1, 3, 4}, + { + /*ic 0*/ 1, + 2, + 3, + 4, + /*ic 1*/ 2, + 3, + 4, + 5, + /*ic 2*/ 1, + 1, + 1, + 1, + }); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({3}, {1, 0, 2}); + Tensor bias_scale = tf_float.make({3}, {1.0f, 2.0f, 5.0f}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + Tensor out = tf_int8.zeros({1, 3, 4}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + quantized_depthwise_conv1d_ncl_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out); + + Tensor expected = tf_int8.make( + {1, 3, 4}, + { + /*oc 0*/ 1, + 2, + 3, + 4, + /*oc 1*/ 8, + 12, + 16, + 20, + /*oc 2*/ 0, + 0, + 0, + 0, + }); + EXPECT_TENSOR_EQ(out, expected); +} + +// Degeneracy: length-1 qparam tensors through the per-channel _out entry point +// must produce the same output as the per_tensor_out entry point with the +// equivalent scalar qparams. +TEST_F( + GenericQuantizedDepthwiseConv1dNclPerChannelTest, + LengthOneMatchesPerTensorOut) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make( + {1, 3, 4}, + { + /*ic 0*/ 1, + 2, + 3, + 4, + /*ic 1*/ 2, + 3, + 4, + 5, + /*ic 2*/ 1, + 1, + 1, + 1, + }); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + + const int64_t scalar_wzp = 1; + const double scalar_bs = 2.0; + + Tensor weight_zero_point = + tf_int32.make({1}, {static_cast(scalar_wzp)}); + Tensor bias_scale = tf_float.make({1}, {static_cast(scalar_bs)}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + Tensor out_pc = tf_int8.zeros({1, 3, 4}); + quantized_depthwise_conv1d_ncl_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out_pc); + + Tensor out_pt = tf_int8.zeros({1, 3, 4}); + quantized_depthwise_conv1d_ncl_per_tensor_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*input_zero_point=*/0, + scalar_wzp, + scalar_bs, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + /*out_multiplier=*/0, + /*out_shift=*/0, + out_pt); + + EXPECT_TENSOR_EQ(out_pc, out_pt); +} + +// Absent weight_zero_point means a symmetric weight: every channel's zero point +// is zero, so the result must match an explicit all-zero tensor. +// Same input as above with weight 2 everywhere and bias_scale [1, 2, 5]: +// oc 0 (bs=1.0): [2, 4, 6, 8] +// oc 1 (bs=2.0): [8, 12, 16, 20] +// oc 2 (bs=5.0): [10, 10, 10, 10] +TEST_F( + GenericQuantizedDepthwiseConv1dNclPerChannelTest, + AbsentWeightZeroPointMatchesAllZeros) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make( + {1, 3, 4}, + { + /*ic 0*/ 1, + 2, + 3, + 4, + /*ic 1*/ 2, + 3, + 4, + 5, + /*ic 2*/ 1, + 1, + 1, + 1, + }); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + Tensor bias_scale = tf_float.make({3}, {1.0f, 2.0f, 5.0f}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + const auto run = [&](const std::optional& weight_zero_point) { + Tensor out = tf_int8.zeros({1, 3, 4}); + quantized_depthwise_conv1d_ncl_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out); + return out; + }; + + Tensor expected = tf_int8.make( + {1, 3, 4}, + { + /*oc 0*/ 2, + 4, + 6, + 8, + /*oc 1*/ 8, + 12, + 16, + 20, + /*oc 2*/ 10, + 10, + 10, + 10, + }); + EXPECT_TENSOR_EQ(run(std::nullopt), expected); + EXPECT_TENSOR_EQ(run(tf_int32.zeros({3})), expected); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_depthwise_conv1d_nlc.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_depthwise_conv1d_nlc.cpp new file mode 100644 index 00000000000..09fc32d54ac --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_depthwise_conv1d_nlc.cpp @@ -0,0 +1,342 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { + +// Forward declarations: the depthwise conv1d NLC entry points are defined in +// op_quantized_depthwise_conv1d_nlc.cpp but not exposed through a header. +::executorch::aten::Tensor& quantized_depthwise_conv1d_nlc_per_tensor_out( + ::executorch::runtime::KernelRuntimeContext& ctx, + const ::executorch::aten::Tensor& input, + const ::executorch::aten::Tensor& weight, + const ::executorch::aten::Tensor& bias, + ::executorch::aten::IntArrayRef stride, + ::executorch::aten::IntArrayRef padding, + ::executorch::aten::IntArrayRef dilation, + int64_t groups, + int64_t input_zero_point, + int64_t weight_zero_point, + double bias_scale, + double output_scale, + int64_t output_zero_point, + int64_t out_multiplier, + int64_t out_shift, + ::executorch::aten::Tensor& out); + +::executorch::aten::Tensor& quantized_depthwise_conv1d_nlc_out( + ::executorch::runtime::KernelRuntimeContext& ctx, + const ::executorch::aten::Tensor& input, + const ::executorch::aten::Tensor& weight, + const ::executorch::aten::Tensor& bias, + ::executorch::aten::IntArrayRef stride, + ::executorch::aten::IntArrayRef padding, + ::executorch::aten::IntArrayRef dilation, + int64_t groups, + int64_t input_zero_point, + const std::optional<::executorch::aten::Tensor>& weight_zero_point, + const ::executorch::aten::Tensor& bias_scale, + double output_scale, + int64_t output_zero_point, + const ::executorch::aten::Tensor& out_multiplier, + const ::executorch::aten::Tensor& out_shift, + ::executorch::aten::Tensor& out); + +namespace { + +using ::executorch::aten::IntArrayRef; +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +class GenericQuantizedDepthwiseConv1dNlcPerChannelTest : public OperatorTest { + protected: + static IntArrayRef ref(const std::array& a) { + return IntArrayRef(a.data(), a.size()); + } +}; + +// Depthwise NLC layout: input [N, L, C], groups == C, weight [OC, WW, 1]. +// Same numeric construction as the NCL depthwise test, reinterpreted for NLC. +// Setup (int8, all zero_points = 0, output_scale = 1.0): +// input NLC [1, 4, 3] (position-major, channel innermost): +// pos 0: [ic0=1, ic1=2, ic2=1] +// pos 1: [ic0=2, ic1=3, ic2=1] +// pos 2: [ic0=3, ic1=4, ic2=1] +// pos 3: [ic0=4, ic1=5, ic2=1] +// weight [3, 1, 1] = [[[2]], [[2]], [[2]]] +// bias [3] = [0, 0, 0] +// weight_zero_point [3] = [1, 0, 2] +// -> effective weight per output channel: 1, 2, 0 +// bias_scale [3] = [1.0f, 2.0f, 5.0f] +// +// Per-position accumulator per output channel (each oc reads its own ic): +// oc 0 (uses ic 0, w=1): [1, 2, 3, 4] +// oc 1 (uses ic 1, w=2): [4, 6, 8, 10] +// oc 2 (uses ic 2, w=0): [0, 0, 0, 0] +// +// Output NLC [1, 4, 3], laid out position-major: +// pos 0: [oc0=1, oc1=8, oc2=0] +// pos 1: [oc0=2, oc1=12, oc2=0] +// pos 2: [oc0=3, oc1=16, oc2=0] +// pos 3: [oc0=4, oc1=20, oc2=0] +// +// These per-channel bias_scales are DISTINCT so the test would fail if the +// kernel incorrectly broadcast bias_scale[0] to every output channel. +TEST_F( + GenericQuantizedDepthwiseConv1dNlcPerChannelTest, + PerChannelCorrectnessInt8) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make( + {1, 4, 3}, + { + /*pos 0*/ 1, + 2, + 1, + /*pos 1*/ 2, + 3, + 1, + /*pos 2*/ 3, + 4, + 1, + /*pos 3*/ 4, + 5, + 1, + }); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({3}, {1, 0, 2}); + Tensor bias_scale = tf_float.make({3}, {1.0f, 2.0f, 5.0f}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + Tensor out = tf_int8.zeros({1, 4, 3}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + quantized_depthwise_conv1d_nlc_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out); + + Tensor expected = tf_int8.make( + {1, 4, 3}, + { + /*pos 0*/ 1, + 8, + 0, + /*pos 1*/ 2, + 12, + 0, + /*pos 2*/ 3, + 16, + 0, + /*pos 3*/ 4, + 20, + 0, + }); + EXPECT_TENSOR_EQ(out, expected); +} + +// Degeneracy: length-1 qparam tensors through the per-channel _out entry point +// must produce the same output as the per_tensor_out entry point with the +// equivalent scalar qparams. +TEST_F( + GenericQuantizedDepthwiseConv1dNlcPerChannelTest, + LengthOneMatchesPerTensorOut) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make( + {1, 4, 3}, + { + /*pos 0*/ 1, + 2, + 1, + /*pos 1*/ 2, + 3, + 1, + /*pos 2*/ 3, + 4, + 1, + /*pos 3*/ 4, + 5, + 1, + }); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + + const int64_t scalar_wzp = 1; + const double scalar_bs = 2.0; + + Tensor weight_zero_point = + tf_int32.make({1}, {static_cast(scalar_wzp)}); + Tensor bias_scale = tf_float.make({1}, {static_cast(scalar_bs)}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + Tensor out_pc = tf_int8.zeros({1, 4, 3}); + quantized_depthwise_conv1d_nlc_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out_pc); + + Tensor out_pt = tf_int8.zeros({1, 4, 3}); + quantized_depthwise_conv1d_nlc_per_tensor_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*input_zero_point=*/0, + scalar_wzp, + scalar_bs, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + /*out_multiplier=*/0, + /*out_shift=*/0, + out_pt); + + EXPECT_TENSOR_EQ(out_pc, out_pt); +} + +// Absent weight_zero_point means a symmetric weight: every channel's zero point +// is zero, so the result must match an explicit all-zero tensor. +// Same input as above with weight 2 everywhere and bias_scale [1, 2, 5]: +// pos 0: [oc0=2, oc1=8, oc2=10] +// pos 1: [oc0=4, oc1=12, oc2=10] +// pos 2: [oc0=6, oc1=16, oc2=10] +// pos 3: [oc0=8, oc1=20, oc2=10] +TEST_F( + GenericQuantizedDepthwiseConv1dNlcPerChannelTest, + AbsentWeightZeroPointMatchesAllZeros) { + TensorFactory tf_int8; + TensorFactory tf_int32; + TensorFactory tf_float; + + Tensor input = tf_int8.make( + {1, 4, 3}, + { + /*pos 0*/ 1, + 2, + 1, + /*pos 1*/ 2, + 3, + 1, + /*pos 2*/ 3, + 4, + 1, + /*pos 3*/ 4, + 5, + 1, + }); + Tensor weight = tf_int8.make({3, 1, 1}, {2, 2, 2}); + Tensor bias = tf_int32.zeros({3}); + Tensor bias_scale = tf_float.make({3}, {1.0f, 2.0f, 5.0f}); + Tensor out_multiplier = tf_int32.make({1}, {0}); + Tensor out_shift = tf_int32.make({1}, {0}); + + std::array stride_arr = {1}; + std::array padding_arr = {0}; + std::array dilation_arr = {1}; + + const auto run = [&](const std::optional& weight_zero_point) { + Tensor out = tf_int8.zeros({1, 4, 3}); + quantized_depthwise_conv1d_nlc_out( + context_, + input, + weight, + bias, + ref(stride_arr), + ref(padding_arr), + ref(dilation_arr), + /*groups=*/3, + /*input_zero_point=*/0, + weight_zero_point, + bias_scale, + /*output_scale=*/1.0, + /*output_zero_point=*/0, + out_multiplier, + out_shift, + out); + return out; + }; + + Tensor expected = tf_int8.make( + {1, 4, 3}, + { + /*pos 0*/ 2, + 8, + 10, + /*pos 1*/ 4, + 12, + 10, + /*pos 2*/ 6, + 16, + 10, + /*pos 3*/ 8, + 20, + 10, + }); + EXPECT_TENSOR_EQ(run(std::nullopt), expected); + EXPECT_TENSOR_EQ(run(tf_int32.zeros({3})), expected); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_embedding_byte.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_embedding_byte.cpp new file mode 100644 index 00000000000..13c1743260e --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_embedding_byte.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// Expected values are aot/ref_implementations.py's. +class GenericQuantizedEmbeddingByteTest : public OperatorTest { + protected: + TensorFactory tf_char_; + TensorFactory tf_float_; + TensorFactory tf_long_; + const Tensor weight_ = + tf_char_.make({3, 4}, {10, 20, 30, 40, -8, 0, 8, 16, 127, -128, 1, -1}); +}; + +// One scale and zero point per row; an index can repeat. +TEST_F(GenericQuantizedEmbeddingByteTest, PerRowScalesAndZeroPoints) { + Tensor out = tf_float_.zeros({3, 4}); + + quantized_embedding_byte_out( + context_, + weight_, + tf_float_.make({3}, {0.5, 0.25, 2.0}), + tf_char_.make({3}, {2, -4, 1}), + tf_long_.make({3}, {2, 0, 0}), + /*pruned_weights=*/false, + out); + + EXPECT_TENSOR_EQ( + out, + tf_float_.make( + {3, 4}, + {252.0, + -258.0, + 0.0, + -4.0, + 4.0, + 9.0, + 14.0, + 19.0, + 4.0, + 9.0, + 14.0, + 19.0})); +} + +// Two groups of two columns per row, each with its own scale, and no zero +// points. +TEST_F(GenericQuantizedEmbeddingByteTest, GroupedScalesWithoutZeroPoints) { + Tensor out = tf_float_.zeros({2, 4}); + + quantized_embedding_byte_out( + context_, + weight_, + tf_float_.make({3, 2}, {0.5, 2.0, 0.25, 1.0, 1.0, 0.125}), + std::nullopt, + tf_long_.make({2}, {1, 2}), + /*pruned_weights=*/false, + out); + + EXPECT_TENSOR_EQ( + out, + tf_float_.make( + {2, 4}, {-2.0, 0.0, 8.0, 16.0, 127.0, -128.0, 0.125, -0.125})); +} + +TEST_F(GenericQuantizedEmbeddingByteTest, Uint8) { + TensorFactory tf_byte; + Tensor out = tf_float_.zeros({2, 4}); + + quantized_embedding_byte_out( + context_, + tf_byte.make({2, 4}, {128, 130, 126, 255, 0, 1, 2, 3}), + tf_float_.make({2}, {0.5, 4.0}), + tf_byte.make({2}, {128, 1}), + tf_long_.make({2}, {0, 1}), + /*pruned_weights=*/false, + out); + + EXPECT_TENSOR_EQ( + out, tf_float_.make({2, 4}, {0.0, 1.0, -1.0, 63.5, -4.0, 0.0, 4.0, 8.0})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_fully_connected.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_fully_connected.cpp new file mode 100644 index 00000000000..d8fa550d8a4 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_fully_connected.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +class GenericQuantizedFullyConnectedPerChannelTest : public OperatorTest {}; + +// Per-channel correctness. Same construction as the linear test, since FC +// dispatches to the same underlying `quantized_linear_` kernel. See that test +// for the derivation of the expected values. +TEST_F( + GenericQuantizedFullyConnectedPerChannelTest, + PerChannelCorrectnessInt8) { + TensorFactory tf_int8; + TensorFactory tf_int32; + + Tensor in = tf_int8.make({1, 2}, {10, 10}); + Tensor weight = tf_int8.make({3, 2}, {1, 1, 2, 2, 4, 4}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({1}, {0}); + Tensor out_multiplier = tf_int32.make( + {3}, + { + (1 << 27), // 1/16 + (1 << 28), // 1/8 + (1 << 29), // 1/4 + }); + Tensor out_shift = tf_int32.make({3}, {0, 0, 0}); + Tensor out = tf_int8.zeros({1, 3}); + + quantized_fully_connected_out( + context_, + in, + weight, + bias, + /*in_zero_point=*/0, + weight_zero_point, + out_multiplier, + out_shift, + /*out_zero_point=*/0, + /*offset=*/std::nullopt, + out); + + // ch 0: 20 * 0.0625 = 1.25 -> 1 + // ch 1: 40 * 0.125 = 5.0 -> 5 + // ch 2: 80 * 0.25 = 20.0 -> 20 + Tensor expected = tf_int8.make({1, 3}, {1, 5, 20}); + EXPECT_TENSOR_EQ(out, expected); +} + +// Degeneracy: length-1 qparam tensors on the .out entry point must +// match the existing per_tensor_out kernel with equivalent scalar qparams. +TEST_F( + GenericQuantizedFullyConnectedPerChannelTest, + LengthOneMatchesPerTensor) { + TensorFactory tf_int8; + TensorFactory tf_int32; + + Tensor in = tf_int8.make({1, 2}, {10, 10}); + Tensor weight = tf_int8.make({3, 2}, {1, 1, 2, 2, 4, 4}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({1}, {0}); + const int32_t scalar_multiplier = (1 << 28); // 1/8 + const int32_t scalar_shift = 0; + Tensor out_multiplier = tf_int32.make({1}, {scalar_multiplier}); + Tensor out_shift = tf_int32.make({1}, {scalar_shift}); + + Tensor out_pc = tf_int8.zeros({1, 3}); + quantized_fully_connected_out( + context_, + in, + weight, + bias, + /*in_zero_point=*/0, + weight_zero_point, + out_multiplier, + out_shift, + /*out_zero_point=*/0, + /*offset=*/std::nullopt, + out_pc); + + Tensor out_pt = tf_int8.zeros({1, 3}); + quantized_fully_connected_per_tensor_out( + context_, + in, + weight, + bias, + /*in_zero_point=*/0, + /*weight_zero_point=*/0, + /*out_multiplier=*/scalar_multiplier, + /*out_shift=*/scalar_shift, + /*out_zero_point=*/0, + /*offset=*/std::nullopt, + out_pt); + + EXPECT_TENSOR_EQ(out_pc, out_pt); +} + +// The uint8 typed entry, on the first row of the linear test's input. +// Expected values are aot/ref_implementations.py's with the multiplier negated, +// for the reason test_op_quantized_linear.cpp gives. +TEST_F(GenericQuantizedFullyConnectedPerChannelTest, Asym8uPerTensor) { + TensorFactory tf_uint8; + TensorFactory tf_int32; + Tensor in = tf_uint8.make({1, 3}, {130, 125, 140}); + Tensor weight = tf_uint8.make({2, 3}, {129, 131, 128, 127, 126, 135}); + Tensor bias = tf_int32.make({2}, {4, -8}); + Tensor out = tf_uint8.zeros({1, 2}); + + quantized_fully_connected_asym8uxasym8u_asym8u_per_tensor_out( + context_, + in, + weight, + bias, + /*in_zero_point=*/128, + /*weight_zero_point=*/128, + /*out_multiplier=*/(1 << 29), + /*out_shift=*/0, + /*out_zero_point=*/100, + /*offset=*/std::nullopt, + out); + + EXPECT_TENSOR_EQ(out, tf_uint8.make({1, 2}, {99, 120})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_linear.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_linear.cpp new file mode 100644 index 00000000000..c264fe65c15 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_linear.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +class GenericQuantizedLinearPerChannelTest : public OperatorTest {}; + +// Per-channel correctness. Uses distinct out_multiplier/out_shift per output +// channel so a regression that reads `[0]` for every channel produces visibly +// wrong values on channels 1..N-1. +// +// Setup (all zero_points = 0): +// src (int8, [1,2]) = [[10, 10]] +// weight (int8, [3,2]) = [[1, 1], [2, 2], [4, 4]] -> distinct rows +// bias (int32, [3]) = [0, 0, 0] +// weight_zero_point ([1]) = [0] (per-tensor weight zp) +// out_multiplier ([3]) = per-channel, produces requant scales +// [1/16, 1/8, 1/4] +// out_shift ([3]) = [0, 0, 0] +// +// Sums (integer accum from formula bias + sum_k (src-zp)*(w-wzp)): +// ch 0: 10*1 + 10*1 = 20 +// ch 1: 10*2 + 10*2 = 40 +// ch 2: 10*4 + 10*4 = 80 +// +// requant_scale[j] = out_multiplier[j] / 2^31 * 2^out_shift[j] +// ch 0: 2^27/2^31 * 1 = 1/16 = 0.0625 +// ch 1: 1/8 = 0.125 +// ch 2: 1/4 = 0.25 +// +// out[j] = clamp(out_zp + nearbyint(requant_scale[j] * sum)) +// ch 0: 20*0.0625 = 1.25 -> 1 +// ch 1: 40*0.125 = 5.0 -> 5 +// ch 2: 80*0.25 = 20.0 -> 20 +// +// A buggy implementation that always reads out_multiplier/out_shift[0] would +// use scale=0.0625 for every channel, yielding [1, 2, 5] instead of [1, 5, 20]. +TEST_F(GenericQuantizedLinearPerChannelTest, PerChannelCorrectnessInt8) { + TensorFactory tf_int8; + TensorFactory tf_int32; + + Tensor src = tf_int8.make({1, 2}, {10, 10}); + Tensor weight = tf_int8.make({3, 2}, {1, 1, 2, 2, 4, 4}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({1}, {0}); + // Positive Q31 multipliers by the existing kernel convention: + // requant_scale = out_multiplier / 2^31 (the two negatives in the C++ + // formula cancel). See existing tests, e.g. HiFi conv2d_out. + Tensor out_multiplier = tf_int32.make( + {3}, + { + (1 << 27), // 1/16 + (1 << 28), // 1/8 + (1 << 29), // 1/4 + }); + Tensor out_shift = tf_int32.make({3}, {0, 0, 0}); + Tensor out = tf_int8.zeros({1, 3}); + + quantized_linear_out( + context_, + src, + weight, + bias, + /*src_zero_point=*/0, + weight_zero_point, + out_multiplier, + out_shift, + /*out_zero_point=*/0, + /*offset=*/std::nullopt, + out); + + Tensor expected = tf_int8.make({1, 3}, {1, 5, 20}); + EXPECT_TENSOR_EQ(out, expected); +} + +// Degeneracy: length-1 qparam tensors on the .out entry point must +// match the existing per_tensor_out kernel with equivalent scalar qparams. +// Pins the stride-selection logic (numel() > 1 ? 1 : 0). +TEST_F(GenericQuantizedLinearPerChannelTest, LengthOneMatchesPerTensor) { + TensorFactory tf_int8; + TensorFactory tf_int32; + + Tensor src = tf_int8.make({1, 2}, {10, 10}); + Tensor weight = tf_int8.make({3, 2}, {1, 1, 2, 2, 4, 4}); + Tensor bias = tf_int32.zeros({3}); + Tensor weight_zero_point = tf_int32.make({1}, {0}); + // Single scalar-equivalent qparam (positive Q31 multiplier). + const int32_t scalar_multiplier = (1 << 28); // 1/8 + const int32_t scalar_shift = 0; + Tensor out_multiplier = tf_int32.make({1}, {scalar_multiplier}); + Tensor out_shift = tf_int32.make({1}, {scalar_shift}); + + Tensor out_pc = tf_int8.zeros({1, 3}); + quantized_linear_out( + context_, + src, + weight, + bias, + /*src_zero_point=*/0, + weight_zero_point, + out_multiplier, + out_shift, + /*out_zero_point=*/0, + /*offset=*/std::nullopt, + out_pc); + + Tensor out_pt = tf_int8.zeros({1, 3}); + quantized_linear_per_tensor_out( + context_, + src, + weight, + bias, + /*src_zero_point=*/0, + /*weight_zero_point=*/0, + /*out_multiplier=*/scalar_multiplier, + /*out_shift=*/scalar_shift, + /*out_zero_point=*/0, + /*offset=*/std::nullopt, + out_pt); + + EXPECT_TENSOR_EQ(out_pc, out_pt); +} + +// The uint8 typed entry. The kernel computes -out_multiplier / (1 << 31), and +// 1 << 31 is INT_MIN, so the scale is +out_multiplier / 2^31, as +// quantize_tensor_multiplier produces. aot/ref_implementations.py computes +// -out_multiplier / 2^31, so the expected values come from it with the +// multiplier negated: (src - 128) @ (weight - 128)^T + bias = +// [[-3, 80], [-4, 0]], times 1/4, plus 100. +TEST_F(GenericQuantizedLinearPerChannelTest, Asym8uPerTensor) { + TensorFactory tf_uint8; + TensorFactory tf_int32; + Tensor src = tf_uint8.make({2, 3}, {130, 125, 140, 120, 128, 128}); + Tensor weight = tf_uint8.make({2, 3}, {129, 131, 128, 127, 126, 135}); + Tensor bias = tf_int32.make({2}, {4, -8}); + Tensor out = tf_uint8.zeros({2, 2}); + + quantized_linear_asym8uxasym8u_asym8u_per_tensor_out( + context_, + src, + weight, + bias, + /*src_zero_point=*/128, + /*weight_zero_point=*/128, + /*out_multiplier=*/(1 << 29), + /*out_shift=*/0, + /*out_zero_point=*/100, + /*offset=*/std::nullopt, + out); + + EXPECT_TENSOR_EQ(out, tf_uint8.make({2, 2}, {99, 120, 99, 100})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_matmul.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_matmul.cpp new file mode 100644 index 00000000000..c9173c19ae1 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_matmul.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include + +#include +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// The kernel computes -out_multiplier / (1 << 31) * 2^out_shift, and 1 << 31 is +// INT_MIN, so the scale is +out_multiplier / 2^31 * 2^out_shift, as +// quantize_tensor_multiplier produces: 1 << 29 is 1/4. +// aot/ref_implementations.py computes -out_multiplier / 2^31, so the expected +// values come from it with -(1 << 29). +constexpr int64_t kQuarter = 1 << 29; + +class GenericQuantizedMatmulAsym8uTest : public OperatorTest { + protected: + TensorFactory tf_; +}; + +// (X - 128) @ (Y - 128) = [[-7, 88], [-8, 8]], times 1/4, plus 100. +TEST_F(GenericQuantizedMatmulAsym8uTest, Asym8u) { + const Tensor x = tf_.make({2, 3}, {130, 125, 140, 120, 128, 128}); + const Tensor y = tf_.make({3, 2}, {129, 127, 131, 126, 128, 135}); + Tensor out = tf_.zeros({2, 2}); + + quantized_matmul_asym8uxasym8u_asym8u_out( + context_, x, 128, y, 128, std::nullopt, kQuarter, 0, 100, false, out); + + EXPECT_TENSOR_EQ(out, tf_.make({2, 2}, {98, 122, 98, 102})); +} + +TEST_F(GenericQuantizedMatmulAsym8uTest, Asym8uTransposed) { + const Tensor x = tf_.make({2, 3}, {130, 125, 140, 120, 128, 128}); + const Tensor y_t = tf_.make({2, 3}, {129, 131, 128, 127, 126, 135}); + Tensor out = tf_.zeros({2, 2}); + + quantized_matmul_asym8uxasym8u_asym8u_out( + context_, x, 128, y_t, 128, std::nullopt, kQuarter, 0, 100, true, out); + + EXPECT_TENSOR_EQ(out, tf_.make({2, 2}, {98, 122, 98, 102})); +} + +TEST_F(GenericQuantizedMatmulAsym8uTest, Asym8uSaturatesAtBothEnds) { + const Tensor x = tf_.make({2, 3}, {255, 255, 255, 0, 0, 0}); + const Tensor y = tf_.make({3, 2}, {255, 0, 255, 0, 255, 0}); + Tensor out = tf_.zeros({2, 2}); + + quantized_matmul_asym8uxasym8u_asym8u_out( + context_, x, 128, y, 128, std::nullopt, kQuarter, 0, 128, false, out); + + EXPECT_TENSOR_EQ(out, tf_.make({2, 2}, {255, 0, 0, 255})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_max_pool2d.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_max_pool2d.cpp new file mode 100644 index 00000000000..296e93b4cae --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_max_pool2d.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include + +#include +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::IntArrayRef; +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// Expected values are aot/ref_implementations.py's. +class GenericQuantizedMaxPool2dNchwTest : public OperatorTest { + protected: + Tensor& max_pool( + const Tensor& input, + std::array padding, + bool ceil_mode, + Tensor& out) { + const std::array kernel{2, 2}, stride{2, 2}, dilation{1, 1}; + return quantized_max_pool2d_nchw_out( + context_, + input, + IntArrayRef(kernel.data(), 2), + IntArrayRef(stride.data(), 2), + IntArrayRef(padding.data(), 2), + IntArrayRef(dilation.data(), 2), + ceil_mode, + out); + } + + TensorFactory tf_; +}; + +TEST_F(GenericQuantizedMaxPool2dNchwTest, TwoByTwoStrideTwo) { + const Tensor input = tf_.make( + {1, 1, 4, 4}, {1, 5, -3, 2, 4, -8, 7, 0, -1, -2, -3, -4, 9, 6, -7, 8}); + Tensor out = tf_.zeros({1, 1, 2, 2}); + + max_pool(input, {0, 0}, /*ceil_mode=*/false, out); + + EXPECT_TENSOR_EQ(out, tf_.make({1, 1, 2, 2}, {5, 7, 9, 8})); +} + +// Every input is negative, so a padded position that counted as 0 would win. +TEST_F(GenericQuantizedMaxPool2dNchwTest, PaddingNeverWins) { + const Tensor input = + tf_.make({1, 1, 3, 3}, {-5, -6, -7, -8, -9, -10, -11, -12, -13}); + Tensor out = tf_.zeros({1, 1, 2, 2}); + + max_pool(input, {1, 1}, /*ceil_mode=*/false, out); + + EXPECT_TENSOR_EQ(out, tf_.make({1, 1, 2, 2}, {-5, -6, -8, -9})); +} + +// ceil_mode adds the windows that cover only the last row and column. +TEST_F(GenericQuantizedMaxPool2dNchwTest, CeilMode) { + const Tensor input = + tf_.make({1, 1, 3, 3}, {-5, -6, -7, -8, -9, -10, -11, -12, -13}); + Tensor out = tf_.zeros({1, 1, 2, 2}); + + max_pool(input, {0, 0}, /*ceil_mode=*/true, out); + + EXPECT_TENSOR_EQ(out, tf_.make({1, 1, 2, 2}, {-5, -7, -11, -13})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_mul.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_mul.cpp new file mode 100644 index 00000000000..3122786c527 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_mul.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// Expected values are aot/ref_implementations.py's. Scales are powers of two, +// so every intermediate value is exact. +class GenericQuantizedMulTest : public OperatorTest {}; + +// Y broadcasts along dim 0. +TEST_F(GenericQuantizedMulTest, PerTensorBroadcasts) { + TensorFactory tf; + const Tensor x = tf.make({2, 3}, {2, -3, 4, 5, 6, -7}); + const Tensor y = tf.make({1, 3}, {2, 4, -2}); + Tensor out = tf.zeros({2, 3}); + + quantized_mul_per_tensor_out(context_, x, 0.5, 0, y, 0.5, 0, 0.25, 0, out); + + EXPECT_TENSOR_EQ(out, tf.make({2, 3}, {4, -12, -8, 10, 24, 14})); +} + +TEST_F(GenericQuantizedMulTest, PerTensorSaturatesWithZeroPoints) { + TensorFactory tf; + const Tensor x = tf.make({1, 3}, {100, -100, 3}); + const Tensor y = tf.make({1, 3}, {100, 100, 4}); + Tensor out = tf.zeros({1, 3}); + + quantized_mul_per_tensor_out(context_, x, 0.5, 0, y, 0.5, 2, 0.5, -1, out); + + EXPECT_TENSOR_EQ(out, tf.make({1, 3}, {127, -128, 2})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_softmax.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_softmax.cpp new file mode 100644 index 00000000000..f08af743191 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_quantized_softmax.cpp @@ -0,0 +1,1540 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::KernelRuntimeContext; +using ::executorch::runtime::testing::TensorFactory; + +class GenericQuantizedSoftmaxTest : public OperatorTest { + public: + protected: + // Helper that accepts explicit mask_type value + Tensor& quantized_softmax_per_tensor_out( + const Tensor& input, + const Tensor& mask, + int64_t dim, + int64_t mask_type, + const Tensor& pos, + double in_scale, + int64_t in_zero_point, + double out_scale, + int64_t out_zero_point, + Tensor& output) { + return impl::generic::native::quantized_softmax_per_tensor_out( + context_, + input, + mask, + dim, + mask_type, + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + } +}; + +// Test basic softmax without masking (mask_type = 0) +// Uses a 4x16 input tensor with explicit data values +TEST_F(GenericQuantizedSoftmaxTest, BasicSoftmaxInt8NoMask) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 4; + constexpr int kNumCols = 16; + + // ============================================================ + // Input tensor: 4 rows x 16 cols (64 elements) + // Row 0: values 10-25 (dequantized: 1.0 to 2.5) + // Row 1: values 20-35 (dequantized: 2.0 to 3.5) + // Row 2: uniform values (dequantized: all 5.0) + // Row 3: alternating pattern + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 1 + 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, + // Row 2 + 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, + // Row 3 + 10, 30, 10, 30, 10, 30, 10, 30, 10, 30, 10, 30, 10, 30, 10, 30 + }); + // clang-format on + + // ============================================================ + // Output tensor: 4 rows x 16 cols, initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused when mask_type = 0) + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: single element (unused when mask_type = 0) + // ============================================================ + Tensor pos = tf_int64.make({1}, {0}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Expected output tensor + // Softmax is computed on dequantized values, then requantized. + // Row 0: dequantized [1.0, 1.1, ..., 2.5], softmax applied + // Row 1: dequantized [2.0, 2.1, ..., 3.5], softmax applied + // Row 2: dequantized [5.0, 5.0, ..., 5.0], uniform -> ~8 each (127/16) + // Row 3: dequantized alternating [1.0, 3.0, ...], bimodal distribution + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: increasing values [1.0-2.5], softmax gives increasing probs + 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 14, 15, + // Row 1: increasing values [2.0-3.5], softmax gives increasing probs + 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 14, 15, + // Row 2: uniform input -> uniform output (~8 each, 127/16 ≈ 7.9) + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + // Row 3: alternating [1.0, 3.0] -> bimodal [low, high, low, high, ...] + 2, 14, 2, 14, 2, 14, 2, 14, 2, 14, 2, 14, 2, 14, 2, 14 + }); + // clang-format on + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, // dim = last dimension + 0, // mask_type = 0 (no masking) + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + EXPECT_TENSOR_EQ(output, expected); +} + +// Test softmax with uint8 input type using larger tensor +TEST_F(GenericQuantizedSoftmaxTest, BasicSoftmaxUInt8NoMask) { + TensorFactory tf_uint8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 8; + constexpr int kNumCols = 32; + + // ============================================================ + // Input tensor: 8 rows x 32 cols (256 elements) + // Pattern: (i % 32) + 10 for each element + // ============================================================ + // clang-format off + Tensor input = tf_uint8.make( + {kNumRows, kNumCols}, + { + // Row 0 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Row 1 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Row 2 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Row 3 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Row 4 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Row 5 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Row 6 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Row 7 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 + }); + // clang-format on + + // ============================================================ + // Output tensor: 8 rows x 32 cols, initialized to zeros + // ============================================================ + Tensor output = tf_uint8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused) + // ============================================================ + Tensor mask = tf_uint8.make({1}, {0}); + + // ============================================================ + // Position tensor: single element (unused) + // ============================================================ + Tensor pos = tf_int64.make({1}, {0}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 255.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Expected output tensor + // All rows have the same increasing pattern, softmax distribution + // ============================================================ + // clang-format off + Tensor expected = tf_uint8.make( + {kNumRows, kNumCols}, + { + // Row 0: increasing values [1.0-4.1], softmax distribution + 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 13, 14, 15, 17, 19, 21, 23, 25, + // Row 1 + 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 13, 14, 15, 17, 19, 21, 23, 25, + // Row 2 + 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 13, 14, 15, 17, 19, 21, 23, 25, + // Row 3 + 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 13, 14, 15, 17, 19, 21, 23, 25, + // Row 4 + 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 13, 14, 15, 17, 19, 21, 23, 25, + // Row 5 + 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 13, 14, 15, 17, 19, 21, 23, 25, + // Row 6 + 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 13, 14, 15, 17, 19, 21, 23, 25, + // Row 7 + 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 13, 14, 15, 17, 19, 21, 23, 25 + }); + // clang-format on + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 0, // mask_type = 0 + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + EXPECT_TENSOR_EQ(output, expected); +} + +// Test softmax with int16 input type +TEST_F(GenericQuantizedSoftmaxTest, BasicSoftmaxInt16NoMask) { + TensorFactory tf_int16; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 4; + constexpr int kNumCols = 16; + + // ============================================================ + // Input tensor: 4 rows x 16 cols + // Pattern: increasing values per row + // ============================================================ + // clang-format off + Tensor input = tf_int16.make( + {kNumRows, kNumCols}, + { + // Row 0: 100, 110, 120, ..., 250 + 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, + // Row 1 + 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, + // Row 2 + 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, + // Row 3 + 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250 + }); + // clang-format on + + // ============================================================ + // Output tensor: 4 rows x 16 cols, initialized to zeros + // ============================================================ + Tensor output = tf_int16.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused) + // ============================================================ + Tensor mask = tf_int16.make({1}, {0}); + + // ============================================================ + // Position tensor: single element (unused) + // ============================================================ + Tensor pos = tf_int64.make({1}, {0}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.01; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 32767.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 0, + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + // ============================================================ + // Expected output tensor + // All rows have the same increasing pattern, softmax distribution + // With scale=0.00003 and zero_point=0, values are in int16 range + // ============================================================ + // clang-format off + Tensor expected = tf_int16.make( + {kNumRows, kNumCols}, + { + // Row 0: increasing values [1.0-2.5], softmax distribution + 872, 963, 1065, 1177, 1301, 1437, 1588, 1756, 1940, 2144, 2370, 2619, 2894, 3199, 3535, 3907, + // Row 1 + 872, 963, 1065, 1177, 1301, 1437, 1588, 1756, 1940, 2144, 2370, 2619, 2894, 3199, 3535, 3907, + // Row 2 + 872, 963, 1065, 1177, 1301, 1437, 1588, 1756, 1940, 2144, 2370, 2619, 2894, 3199, 3535, 3907, + // Row 3 + 872, 963, 1065, 1177, 1301, 1437, 1588, 1756, 1940, 2144, 2370, 2619, 2894, 3199, 3535, 3907 + }); + // clang-format on + + EXPECT_TENSOR_EQ(output, expected); +} + +// Test softmax with position-based causal masking (mask_type = 1) +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxWithCausalMaskingInt8) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions: 8 rows x 16 cols (simulating attention matrix) + // ============================================================ + constexpr int kNumRows = 8; + constexpr int kNumCols = 16; + + // ============================================================ + // Input tensor: attention scores + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 1 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 2 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 3 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 4 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 5 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 6 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 7 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 + }); + // clang-format on + + // ============================================================ + // Output tensor: 8 rows x 16 cols, initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused when pos is used) + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: start attending from position 3 + // ============================================================ + Tensor pos = tf_int64.make({1}, {3}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // mask_type = 1 (position-based causal masking) + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + // ============================================================ + // Expected output tensor + // Causal masking with pos=3: row i attends to positions 0..(3+i) + // Row 0 (pos=3): attend 0-3, mask 4-15 + // Row 1 (pos=4): attend 0-4, mask 5-15 + // Row 2 (pos=5): attend 0-5, mask 6-15 + // Row 3 (pos=6): attend 0-6, mask 7-15 + // Row 4 (pos=7): attend 0-7, mask 8-15 + // Row 5 (pos=8): attend 0-8, mask 9-15 + // Row 6 (pos=9): attend 0-9, mask 10-15 + // Row 7 (pos=10): attend 0-10, mask 11-15 + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: attend cols 0-3, mask cols 4-15 + 27, 30, 33, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 1: attend cols 0-4, mask cols 5-15 + 21, 23, 25, 28, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 2: attend cols 0-5, mask cols 6-15 + 16, 18, 20, 22, 24, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 3: attend cols 0-6, mask cols 7-15 + 13, 15, 16, 18, 20, 22, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 4: attend cols 0-7, mask cols 8-15 + 11, 12, 13, 15, 16, 18, 20, 22, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 5: attend cols 0-8, mask cols 9-15 + 9, 10, 11, 12, 14, 15, 17, 18, 20, 0, 0, 0, 0, 0, 0, 0, + // Row 6: attend cols 0-9, mask cols 10-15 + 8, 9, 9, 10, 12, 13, 14, 16, 17, 19, 0, 0, 0, 0, 0, 0, + // Row 7: attend cols 0-10, mask cols 11-15 + 7, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 0, 0, 0, 0, 0 + }); + // clang-format on + + EXPECT_TENSOR_EQ(output, expected); +} + +// Test softmax with uniform input (all same values) +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxUniformInputInt8) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 4; + constexpr int kNumCols = 16; + + // ============================================================ + // Input tensor: all same values (uniform) = 50 + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0 + 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, + // Row 1 + 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, + // Row 2 + 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, + // Row 3 + 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused) + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: single element (unused) + // ============================================================ + Tensor pos = tf_int64.make({1}, {0}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 0, + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + // ============================================================ + // Expected output tensor + // Uniform input: all outputs should be approximately equal (1/16 per element) + // Expected value: 127 / 16 ≈ 8 + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: uniform output + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + // Row 1 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + // Row 2 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + // Row 3 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 + }); + // clang-format on + + EXPECT_TENSOR_EQ(output, expected); +} + +// Test softmax with negative position value (all positions masked) +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxAllMaskedInt8) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 4; + constexpr int kNumCols = 16; + + // ============================================================ + // Input tensor: various values + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0 + 10, 20, 30, 40, 50, 60, 10, 20, 30, 40, 50, 60, 10, 20, 30, 40, + // Row 1 + 10, 20, 30, 40, 50, 60, 10, 20, 30, 40, 50, 60, 10, 20, 30, 40, + // Row 2 + 10, 20, 30, 40, 50, 60, 10, 20, 30, 40, 50, 60, 10, 20, 30, 40, + // Row 3 + 10, 20, 30, 40, 50, 60, 10, 20, 30, 40, 50, 60, 10, 20, 30, 40 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused) + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: -1 means all positions masked + // ============================================================ + Tensor pos = tf_int64.make({1}, {-1}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // mask_type = 1 + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + // ============================================================ + // Expected output tensor + // All positions are masked, so all outputs should be zero + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: all masked + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 1 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 2 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 3 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }); + // clang-format on + + EXPECT_TENSOR_EQ(output, expected); +} + +// Test softmax with large position value (no positions masked) +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxNoneMaskedInt8) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 4; + constexpr int kNumCols = 16; + + // ============================================================ + // Input tensor: increasing pattern + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 1 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 2 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + // Row 3 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused) + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: 1000 > size, so no masking + // ============================================================ + Tensor pos = tf_int64.make({1}, {1000}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // mask_type = 1 + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + // ============================================================ + // Expected output tensor + // No masking (mask_type=0), all positions attended + // Same pattern as BasicSoftmaxInt8NoMask + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: increasing values, softmax distribution + 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 14, 15, + // Row 1 + 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 14, 15, + // Row 2 + 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 14, 15, + // Row 3 + 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 14, 15 + }); + // clang-format on + + EXPECT_TENSOR_EQ(output, expected); +} + +// Test softmax with single element per row +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxSingleElementInt8) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions: multiple rows, single column + // ============================================================ + constexpr int kNumRows = 8; + constexpr int kNumCols = 1; + + // ============================================================ + // Input tensor: various single values + // ============================================================ + Tensor input = + tf_int8.make({kNumRows, kNumCols}, {10, 20, 30, 40, 50, 60, 70, 80}); + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused) + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: single element (unused) + // ============================================================ + Tensor pos = tf_int64.make({1}, {0}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 0, + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + // Single element softmax should output 1.0 (quantized as 127 for all rows) + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + 127, // Row 0 + 127, // Row 1 + 127, // Row 2 + 127, // Row 3 + 127, // Row 4 + 127, // Row 5 + 127, // Row 6 + 127, // Row 7 + }); + // clang-format on + EXPECT_TENSOR_EQ(output, expected); +} + +// Test softmax with int16 position tensor for causal masking +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxCausalMaskingInt16Pos) { + TensorFactory tf_int16; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 4; + constexpr int kNumCols = 16; + + // ============================================================ + // Input tensor: increasing values + // ============================================================ + // clang-format off + Tensor input = tf_int16.make( + {kNumRows, kNumCols}, + { + // Row 0 + 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, + // Row 1 + 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, + // Row 2 + 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, + // Row 3 + 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int16.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused) + // ============================================================ + Tensor mask = tf_int16.make({1}, {0}); + + // ============================================================ + // Position tensor as int16: start from position 5 + // ============================================================ + Tensor pos = tf_int16.make({1}, {5}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.01; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 32767.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // mask_type = 1 + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + // Compare with expected output tensor + // Row 0 (pos=5): positions 0-5 attended (exponential growth), positions 6-15 + // masked (0) Row 1 (pos=5+1=6): positions 0-6 attended, positions 7-15 masked + // Row 2 (pos=5+2=7): positions 0-7 attended, positions 8-15 masked + // Row 3 (pos=5+3=8): positions 0-8 attended, positions 9-15 masked + // clang-format off + Tensor expected = tf_int16.make( + {kNumRows, kNumCols}, + { + // Row 0: positions 0-5 attended (exp growth), 6-15 masked + 4192, 4633, 5120, 5658, 6253, 6911, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 1: positions 0-6 attended, 7-15 masked + 3399, 3757, 4152, 4589, 5071, 5605, 6194, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 2: positions 0-7 attended, 8-15 masked + 2812, 3108, 3434, 3796, 4195, 4636, 5124, 5663, 0, 0, 0, 0, 0, 0, 0, 0, + // Row 3: positions 0-8 attended, 9-15 masked + 2361, 2609, 2884, 3187, 3522, 3893, 4302, 4754, 5255, 0, 0, 0, 0, 0, 0, 0, + }); + // clang-format on + EXPECT_TENSOR_EQ(output, expected); +} + +// Test numerical accuracy: verify softmax with known values +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxNumericalAccuracyKnown) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions: 2 rows x 4 cols + // ============================================================ + constexpr int kNumRows = 2; + constexpr int kNumCols = 4; + + // ============================================================ + // Input tensor: [0, 1, 2, 3] repeated + // softmax([0, 1, 2, 3]) = [0.0321, 0.0871, 0.2369, 0.6439] + // ============================================================ + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + {// Row 0 + 0, + 1, + 2, + 3, + // Row 1 + 0, + 1, + 2, + 3}); + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: single element (unused) + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: single element (unused) + // ============================================================ + Tensor pos = tf_int64.make({1}, {0}); + + // ============================================================ + // Quantization parameters + // With out_scale = 0.01, expected quantized values: [3, 9, 24, 64] + // ============================================================ + const double in_scale = 1.0; + const int64_t in_zero_point = 0; + const double out_scale = 0.01; + const int64_t out_zero_point = 0; + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 0, + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + // Compare with expected output tensor + // Both rows have identical input [0, 1, 2, 3], so both have the same + // softmax distribution: approx [0.032, 0.087, 0.237, 0.644] + // Quantized with scale=0.01, zero_point=0: [3, 9, 24, 64] + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: softmax([0,1,2,3]) quantized + 3, 9, 24, 64, + // Row 1: identical distribution + 3, 9, 24, 64, + }); + // clang-format on + EXPECT_TENSOR_EQ(output, expected); +} + +// Test causal masking with larger sequence for attention-like patterns +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxCausalMaskingLargeSequence) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions: simulating multi-head attention + // ============================================================ + constexpr int kNumHeads = 4; + constexpr int kSeqLen = 32; + + // ============================================================ + // Input tensor: attention scores (128 elements) + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumHeads, kSeqLen}, + { + // Head 0 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Head 1 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Head 2 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + // Head 3 + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumHeads, kSeqLen}); + + // ============================================================ + // Mask tensor: single element (unused) + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: start with position 7 + // ============================================================ + Tensor pos = tf_int64.make({1}, {7}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // Causal masking + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + // Compare with expected output tensor + // Head 0 (pos=7): positions 0-7 attended, positions 8-31 masked + // Head 1 (pos=8): positions 0-8 attended, positions 9-31 masked + // Head 2 (pos=9): positions 0-9 attended, positions 10-31 masked + // Head 3 (pos=10): positions 0-10 attended, positions 11-31 masked + // clang-format off + Tensor expected = tf_int8.make( + {kNumHeads, kSeqLen}, + { + // Head 0: positions 0-7 attended, 8-31 masked + 11, 12, 13, 15, 16, 18, 20, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Head 1: positions 0-8 attended, 9-31 masked + 9, 10, 11, 12, 14, 15, 17, 18, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Head 2: positions 0-9 attended, 10-31 masked + 8, 9, 9, 10, 12, 13, 14, 16, 17, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // Head 3: positions 0-10 attended, 11-31 masked + 7, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + }); + // clang-format on + EXPECT_TENSOR_EQ(output, expected); +} + +// ============================================================ +// Test softmax with basePosValue = 0 (only first position attended) +// ============================================================ +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxFirstPositionOnlyInt8) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 4; + constexpr int kNumCols = 8; + + // ============================================================ + // Input tensor: 4 rows x 8 cols + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0 + 50, 40, 30, 20, 10, 10, 10, 10, + // Row 1 + 50, 40, 30, 20, 10, 10, 10, 10, + // Row 2 + 50, 40, 30, 20, 10, 10, 10, 10, + // Row 3 + 50, 40, 30, 20, 10, 10, 10, 10 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: unused + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: 0 means only first position attended + // Row 0: pos=0 (only col 0 attended) + // Row 1: pos=1 (cols 0-1 attended) + // Row 2: pos=2 (cols 0-2 attended) + // Row 3: pos=3 (cols 0-3 attended) + // ============================================================ + Tensor pos = tf_int64.make({1}, {0}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Expected output tensor + // Row 0: pos=0, only col 0 attended -> softmax([5.0]) = [1.0] -> [127] + // Row 1: pos=1, cols 0-1 attended -> softmax([5.0, 4.0]) + // = exp([5,4]) / sum = [148.4, 54.6] / 203 = [0.73, 0.27] + // Quantized at scale=1/127: [93, 34] + // Row 2: pos=2, cols 0-2 attended -> softmax([5.0, 4.0, 3.0]) + // = exp([5,4,3]) / sum = [148.4, 54.6, 20.1] / 223.1 = [0.665, 0.245, + // 0.09] Quantized at scale=1/127: [84, 31, 11] + // Row 3: pos=3, cols 0-3 attended -> softmax([5.0, 4.0, 3.0, 2.0]) + // = exp([5,4,3,2]) / sum = [148.4, 54.6, 20.1, 7.4] / 230.5 = [0.644, + // 0.237, 0.087, 0.032] Quantized at scale=1/127: [82, 30, 11, 4] + // Masked positions get out_zero_point = 0 + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: only col 0 attended + 127, 0, 0, 0, 0, 0, 0, 0, + // Row 1: cols 0-1 attended + 93, 34, 0, 0, 0, 0, 0, 0, + // Row 2: cols 0-2 attended + 84, 31, 11, 0, 0, 0, 0, 0, + // Row 3: cols 0-3 attended + 82, 30, 11, 4, 0, 0, 0, 0 + }); + // clang-format on + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // mask_type = 1 + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + EXPECT_TENSOR_EQ(output, expected); +} + +// ============================================================ +// Test softmax with single row +// ============================================================ +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxSingleRowInt8) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumCols = 8; + + // ============================================================ + // Input tensor: 1 row x 8 cols + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {1, kNumCols}, + { + 100, 90, 80, 70, 60, 50, 40, 30 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({1, kNumCols}); + + // ============================================================ + // Mask tensor: unused + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: 3 means positions 0-3 are attended + // ============================================================ + Tensor pos = tf_int64.make({1}, {3}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Expected output tensor + // pos=3: cols 0-3 attended + // Input dequantized values: [10.0, 9.0, 8.0, 7.0, ...] + // softmax([10.0, 9.0, 8.0, 7.0]) = [0.643, 0.236, 0.087, 0.032] + // Quantized at out_scale = 1/127: [82, 30, 11, 4] + // Masked positions get out_zero_point = 0 + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {1, kNumCols}, + { + 82, 30, 11, 4, 0, 0, 0, 0 + }); + // clang-format on + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // mask_type = 1 + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + EXPECT_TENSOR_EQ(output, expected); +} + +// ============================================================ +// Test softmax with Int16 position tensor +// ============================================================ +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxWithInt16PositionTensor) { + TensorFactory tf_int8; + TensorFactory tf_int16; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 2; + constexpr int kNumCols = 8; + + // ============================================================ + // Input tensor: 2 rows x 8 cols + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0 + 10, 20, 30, 40, 50, 60, 70, 80, + // Row 1 + 10, 20, 30, 40, 50, 60, 70, 80 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: unused + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: Int16 type with value 2 + // Row 0: pos=2 (cols 0-2 attended) + // Row 1: pos=3 (cols 0-3 attended) + // ============================================================ + Tensor pos = tf_int16.make({1}, {2}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Expected output tensor + // Row 0: pos=2, cols 0-2 attended + // Input dequantized values: [1.0, 2.0, 3.0, ...] + // softmax([1.0, 2.0, 3.0]) = exp([1,2,3]) / sum + // Quantized at out_scale = 1/127 (values verified from implementation) + // Row 1: pos=3, cols 0-3 attended + // softmax([1.0, 2.0, 3.0, 4.0]) = exp([1,2,3,4]) / sum + // Masked positions get out_zero_point = 0 + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: cols 0-2 attended + 11, 31, 84, 0, 0, 0, 0, 0, + // Row 1: cols 0-3 attended + 4, 11, 30, 82, 0, 0, 0, 0 + }); + // clang-format on + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // mask_type = 1 + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + EXPECT_TENSOR_EQ(output, expected); +} + +// ============================================================ +// Test softmax with non-zero output zero_point +// ============================================================ +TEST_F(GenericQuantizedSoftmaxTest, SoftmaxWithNonZeroOutputZeroPoint) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions + // ============================================================ + constexpr int kNumRows = 2; + constexpr int kNumCols = 8; + + // ============================================================ + // Input tensor + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0 + 10, 20, 30, 40, 50, 60, 70, 80, + // Row 1 + 10, 20, 30, 40, 50, 60, 70, 80 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask and position tensors + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + Tensor pos = tf_int64.make({1}, {-1}); // All masked + + // ============================================================ + // Quantization parameters with non-zero output zero_point + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 64; // Non-zero zero_point + + // ============================================================ + // Expected output tensor + // All positions masked -> all outputs should be out_zero_point = 64 + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: all masked + 64, 64, 64, 64, 64, 64, 64, 64, + // Row 1: all masked + 64, 64, 64, 64, 64, 64, 64, 64 + }); + // clang-format on + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // mask_type = 1 + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + EXPECT_TENSOR_EQ(output, expected); +} + +// ============================================================ +// Test full causal masking pattern (simulates transformer attention) +// ============================================================ +TEST_F(GenericQuantizedSoftmaxTest, CausalMaskingSimulationInt8) { + TensorFactory tf_int8; + TensorFactory tf_int64; + + // ============================================================ + // Tensor dimensions - 8x8 simulates 8 token positions + // ============================================================ + constexpr int kNumRows = 8; + constexpr int kNumCols = 8; + + // ============================================================ + // Input tensor: uniform values (no preference for any position) + // All values are the same to make expected output predictable + // ============================================================ + // clang-format off + Tensor input = tf_int8.make( + {kNumRows, kNumCols}, + { + 50, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 50, 50, 50, 50, 50, 50 + }); + // clang-format on + + // ============================================================ + // Output tensor: initialized to zeros + // ============================================================ + Tensor output = tf_int8.zeros({kNumRows, kNumCols}); + + // ============================================================ + // Mask tensor: unused + // ============================================================ + Tensor mask = tf_int8.make({1}, {0}); + + // ============================================================ + // Position tensor: 0 means first token + // Row 0: pos=0, cols 0 attended + // Row 1: pos=1, cols 0-1 attended + // ... + // Row 7: pos=7, cols 0-7 attended + // ============================================================ + Tensor pos = tf_int64.make({1}, {0}); + + // ============================================================ + // Quantization parameters + // ============================================================ + const double in_scale = 0.1; + const int64_t in_zero_point = 0; + const double out_scale = 1.0 / 127.0; + const int64_t out_zero_point = 0; + + // ============================================================ + // Expected output tensor + // With uniform inputs, softmax distributes probability evenly + // among attended positions: + // Row 0: 1 attended -> [127, 0, 0, 0, 0, 0, 0, 0] + // Row 1: 2 attended -> [64, 64, 0, 0, 0, 0, 0, 0] + // Row 2: 3 attended -> [42, 42, 42, 0, 0, 0, 0, 0] + // Row 3: 4 attended -> [32, 32, 32, 32, 0, 0, 0, 0] + // Row 4: 5 attended -> [25, 25, 25, 25, 25, 0, 0, 0] + // Row 5: 6 attended -> [21, 21, 21, 21, 21, 21, 0, 0] + // Row 6: 7 attended -> [18, 18, 18, 18, 18, 18, 18, 0] + // Row 7: 8 attended -> [16, 16, 16, 16, 16, 16, 16, 16] + // Note: These are exact quantized values (127/n rounded) + // ============================================================ + // clang-format off + Tensor expected = tf_int8.make( + {kNumRows, kNumCols}, + { + // Row 0: 1 attended (127/1 = 127) + 127, 0, 0, 0, 0, 0, 0, 0, + // Row 1: 2 attended (127/2 ≈ 63-64) + 64, 64, 0, 0, 0, 0, 0, 0, + // Row 2: 3 attended (127/3 ≈ 42) + 42, 42, 42, 0, 0, 0, 0, 0, + // Row 3: 4 attended (127/4 ≈ 32) + 32, 32, 32, 32, 0, 0, 0, 0, + // Row 4: 5 attended (127/5 ≈ 25) + 25, 25, 25, 25, 25, 0, 0, 0, + // Row 5: 6 attended (127/6 ≈ 21) + 21, 21, 21, 21, 21, 21, 0, 0, + // Row 6: 7 attended (127/7 ≈ 18) + 18, 18, 18, 18, 18, 18, 18, 0, + // Row 7: 8 attended (127/8 ≈ 16) + 16, 16, 16, 16, 16, 16, 16, 16 + }); + // clang-format on + + // ============================================================ + // Execute softmax + // ============================================================ + quantized_softmax_per_tensor_out( + input, + mask, + -1, + 1, // mask_type = 1 + pos, + in_scale, + in_zero_point, + out_scale, + out_zero_point, + output); + + EXPECT_TENSOR_EQ(output, expected); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_roi_align_box_processor.cpp b/backends/cadence/generic/operators/tests/test_op_roi_align_box_processor.cpp new file mode 100644 index 00000000000..74f2facaff1 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_roi_align_box_processor.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include + +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +using Fields = std::array; + +// Each box becomes 80 bytes: 22 signed 29-bit fields, packed LSB first. The +// fields are the anchor (x, y), then 10 x address increments and 10 y address +// increments, all in fixed point with 16 fractional bits (1.0 == 65536). There +// is no reference implementation, so the expected fields are worked out below. +Fields unpack(const uint8_t* bytes) { + Fields fields{}; + for (int f = 0; f < 22; ++f) { + uint32_t v = 0; + for (int bit = 0; bit < 29; ++bit) { + const int pos = f * 29 + bit; + v |= static_cast((bytes[pos / 8] >> (pos % 8)) & 1) << bit; + } + fields[f] = static_cast(v << 3) >> 3; // sign-extend 29 bits + } + return fields; +} + +// For an output of 2x2 with sampling_ratio 1, a box w wide and h tall has steps +// sx = w / 2 and sy = h / 2. The anchor is the top-left corner plus half a +// step. With iteration shape {2, 2, 1, 1, 1, K}, the x increments come out as +// [sx, -sx, sx, -sx, -sx, -sx] and the y increments as [0, sy, -sy, sy, -sy, +// -sy]; the last one repeats to fill 10. +Fields +expected_fields(int32_t anchor_x, int32_t anchor_y, int32_t sx, int32_t sy) { + Fields f{}; + f[0] = anchor_x; + f[1] = anchor_y; + const std::array x{sx, -sx, sx, -sx, -sx, -sx}; + const std::array y{0, sy, -sy, sy, -sy, -sy}; + for (int i = 0; i < 10; ++i) { + f[2 + i] = x[i < 6 ? i : 5]; + f[12 + i] = y[i < 6 ? i : 5]; + } + return f; +} + +constexpr int32_t kOne = 1 << 16; + +class GenericRoiAlignBoxProcessorTest : public OperatorTest { + protected: + TensorFactory tf_float_; + TensorFactory tf_byte_; +}; + +// Box 0 spans (0, 0)-(4, 4): steps 2 and 2, anchor (1, 1). Box 1 spans (8, 0)- +// (12, 8): steps 2 and 4, anchor (9, 2). +TEST_F(GenericRoiAlignBoxProcessorTest, TwoBoxes) { + const Tensor rois = tf_float_.make({2, 5}, {0, 0, 0, 4, 4, 0, 8, 0, 12, 8}); + Tensor out = tf_byte_.zeros({2, 80}); + + roi_align_box_processor_out(context_, rois, 2, 2, 1, /*aligned=*/false, out); + + const uint8_t* data = out.const_data_ptr(); + EXPECT_EQ(unpack(data), expected_fields(kOne, kOne, 2 * kOne, 2 * kOne)); + EXPECT_EQ( + unpack(data + 80), + expected_fields(9 * kOne, 2 * kOne, 2 * kOne, 4 * kOne)); + // 22 fields take 638 bits; the last 2 bits of each box stay 0. + EXPECT_EQ(data[79] >> 6, 0); + EXPECT_EQ(data[159] >> 6, 0); +} + +// aligned moves the corner by half a pixel, so the anchor is (0.5, 0.5); the +// steps do not change. +TEST_F(GenericRoiAlignBoxProcessorTest, Aligned) { + const Tensor rois = tf_float_.make({1, 5}, {0, 0, 0, 4, 4}); + Tensor out = tf_byte_.zeros({1, 80}); + + roi_align_box_processor_out(context_, rois, 2, 2, 1, /*aligned=*/true, out); + + EXPECT_EQ( + unpack(out.const_data_ptr()), + expected_fields(kOne / 2, kOne / 2, 2 * kOne, 2 * kOne)); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_rope.cpp b/backends/cadence/generic/operators/tests/test_op_rope.cpp new file mode 100644 index 00000000000..8c0e6581a9e --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_rope.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// Expected values are aot/ref_implementations.py's. sin and cos are small +// exact values rather than real angles, so every product is exact. The input is +// [1, seq=2, heads=1, head_dim=4], and sin and cos have one row per token. +class GenericRopeTest : public OperatorTest { + protected: + TensorFactory tf_; + const Tensor input_ = + tf_.make({1, 2, 1, 4}, {1.0, 2.0, 3.0, 4.0, -1.0, 0.5, 2.0, -2.0}); + const Tensor sin_ = tf_.make({3, 2}, {0.0, 1.0, 0.5, -1.0, 1.0, 0.25}); + const Tensor cos_ = tf_.make({3, 2}, {1.0, 0.0, 0.5, 0.0, 0.0, 2.0}); + const Tensor sin_2_ = tf_.make({2, 2}, {0.0, 1.0, 0.5, -1.0}); + const Tensor cos_2_ = tf_.make({2, 2}, {1.0, 0.0, 0.5, 0.0}); +}; + +TEST_F(GenericRopeTest, InterleavedPairs) { + Tensor out = tf_.zeros({1, 2, 1, 4}); + + rope_out(context_, input_, sin_2_, cos_2_, std::nullopt, out); + + EXPECT_TENSOR_EQ( + out, + tf_.make({1, 2, 1, 4}, {1.0, 2.0, -4.0, 3.0, -0.75, -0.25, -2.0, -2.0})); +} + +// Token 0 takes row 2 of sin and cos, and token 1 takes row 0. +TEST_F(GenericRopeTest, PositionsSelectTheRows) { + const Tensor expected = + tf_.make({1, 2, 1, 4}, {-2.0, 1.0, 5.0, 8.75, -1.0, 0.5, 2.0, 2.0}); + TensorFactory tf_int; + TensorFactory tf_long; + Tensor out = tf_.zeros({1, 2, 1, 4}); + + rope_out(context_, input_, sin_, cos_, tf_int.make({2}, {2, 0}), out); + EXPECT_TENSOR_EQ(out, expected); + + out = tf_.zeros({1, 2, 1, 4}); + rope_out(context_, input_, sin_, cos_, tf_long.make({2}, {2, 0}), out); + EXPECT_TENSOR_EQ(out, expected); +} + +// Each head's first half x0 rotates with its second half x1: the output is +// [x0 * cos - x1 * sin, x1 * cos + x0 * sin]. These values are worked out by +// hand: ref_implementations.py's rope_rotate_stacked_halves mixes tokens when +// seq * heads > 1. Token 0 has x0 = [1, 2], x1 = [3, 4], sin = [0, 1] and +// cos = [1, 0], so it gives [1, -4, 3, 2]. +TEST_F(GenericRopeTest, StackedHalves) { + Tensor out = tf_.zeros({1, 2, 1, 4}); + + rope_rotate_stacked_halves_out( + context_, input_, sin_2_, cos_2_, std::nullopt, out); + + EXPECT_TENSOR_EQ( + out, + tf_.make({1, 2, 1, 4}, {1.0, -4.0, 3.0, 2.0, -1.5, -2.0, 0.5, -0.5})); +} + +TEST_F(GenericRopeTest, StackedHalvesWithPositions) { + TensorFactory tf_long; + Tensor out = tf_.zeros({1, 2, 1, 4}); + + rope_rotate_stacked_halves_out( + context_, input_, sin_, cos_, tf_long.make({2}, {2, 0}), out); + + EXPECT_TENSOR_EQ( + out, tf_.make({1, 2, 1, 4}, {-3.0, 3.0, 1.0, 8.5, -1.0, 2.0, 2.0, 0.5})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_sdpa_bitwise_causal_mask_gen.cpp b/backends/cadence/generic/operators/tests/test_op_sdpa_bitwise_causal_mask_gen.cpp new file mode 100644 index 00000000000..dfcbe5a3270 --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_sdpa_bitwise_causal_mask_gen.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// Expected values are aot/ref_implementations.py's. Each row packs key_length +// bits LSB first, 8 keys per byte; a set bit masks a key, so position p leaves +// keys 0..p visible. +class GenericSdpaBitwiseCausalMaskGenTest : public OperatorTest { + protected: + TensorFactory tf_byte_; + TensorFactory tf_int_; + TensorFactory tf_long_; +}; + +// Position 20 is past the 16 keys, so its row shows them all. +TEST_F(GenericSdpaBitwiseCausalMaskGenTest, Int32Positions) { + Tensor out = tf_byte_.zeros({4, 2}); + + sdpa_bitwise_causal_mask_gen_out( + context_, tf_int_.make({4}, {0, 3, 9, 20}), 16, out); + + EXPECT_TENSOR_EQ( + out, tf_byte_.make({4, 2}, {254, 255, 240, 255, 0, 252, 0, 0})); +} + +// Positions 7 and 8 straddle the byte boundary. +TEST_F(GenericSdpaBitwiseCausalMaskGenTest, Int64Positions) { + Tensor out = tf_byte_.zeros({2, 2}); + + sdpa_bitwise_causal_mask_gen_out( + context_, tf_long_.make({2}, {7, 8}), 16, out); + + EXPECT_TENSOR_EQ(out, tf_byte_.make({2, 2}, {0, 255, 0, 254})); +} + +TEST_F(GenericSdpaBitwiseCausalMaskGenTest, RejectsKeyLengthNotAMultipleOf8) { + Tensor out = tf_byte_.zeros({1, 2}); + + ET_EXPECT_KERNEL_FAILURE( + context_, + sdpa_bitwise_causal_mask_gen_out( + context_, tf_int_.make({1}, {0}), 12, out)); +} + +TEST_F(GenericSdpaBitwiseCausalMaskGenTest, RejectsANegativePosition) { + Tensor out = tf_byte_.zeros({2, 2}); + + ET_EXPECT_KERNEL_FAILURE( + context_, + sdpa_bitwise_causal_mask_gen_out( + context_, tf_int_.make({2}, {1, -1}), 16, out)); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_op_where_scalar.cpp b/backends/cadence/generic/operators/tests/test_op_where_scalar.cpp new file mode 100644 index 00000000000..1efc22a8f2c --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_op_where_scalar.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include + +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::ScalarType; +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// Expected values are aot/ref_implementations.py's. +class GenericWhereScalarTest : public OperatorTest { + protected: + TensorFactory tf_bool_; + TensorFactory tf_; +}; + +TEST_F(GenericWhereScalarTest, SelectsPerElement) { + const Tensor condition = + tf_bool_.make({2, 3}, {true, false, true, false, false, true}); + Tensor out = tf_.zeros({2, 3}); + + where_Scalar_out(context_, condition, 1.5, -2.25, out); + + EXPECT_TENSOR_EQ(out, tf_.make({2, 3}, {1.5, -2.25, 1.5, -2.25, -2.25, 1.5})); +} + +// The scalars arrive as double and the output is float. +TEST_F(GenericWhereScalarTest, NarrowsTheScalarsToFloat) { + const Tensor condition = tf_bool_.make({2}, {true, false}); + Tensor out = tf_.zeros({2}); + + where_Scalar_out(context_, condition, 0.1, 1e-50, out); + + EXPECT_TENSOR_EQ(out, tf_.make({2}, {0.1f, 0.0f})); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl diff --git a/backends/cadence/generic/operators/tests/test_quantized_linear_packed.cpp b/backends/cadence/generic/operators/tests/test_quantized_linear_packed.cpp new file mode 100644 index 00000000000..6f6386e25ea --- /dev/null +++ b/backends/cadence/generic/operators/tests/test_quantized_linear_packed.cpp @@ -0,0 +1,407 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace impl { +namespace generic { +namespace native { +namespace { + +using ::executorch::aten::Tensor; +using ::executorch::runtime::testing::TensorFactory; + +// Mirror of the AoT packer in +// executorch/backends/cadence/aot/weight_packing.py. Kept independent of the +// kernel's decode path on purpose: the test is only meaningful if the two +// sides are written separately and still agree. +std::vector pack6( + const std::vector& values, + const size_t in_dim) { + // Planar 4+2, per row: + // plane A (in_dim/2 B): byte k = low nibbles of values k, k+in_dim/2 + // plane B (in_dim/4 B): byte m = 2-bit fields of m, m+Q, m+2Q, m+3Q + // Pairing k with k+in_dim/2 is what makes a decoder emit natural k order. + EXPECT_EQ(in_dim % 4, 0u); + EXPECT_EQ(values.size() % in_dim, 0u); + const size_t half = in_dim / 2, quarter = in_dim / 4; + std::vector out; + for (size_t base = 0; base < values.size(); base += in_dim) { + for (size_t k = 0; k < half; ++k) { + const uint8_t lo = static_cast(values[base + k] + 32) & 0x0F; + const uint8_t hi = + static_cast(values[base + k + half] + 32) & 0x0F; + out.push_back(lo | (hi << 4)); + } + for (size_t m = 0; m < quarter; ++m) { + uint8_t b = 0; + for (size_t q = 0; q < 4; ++q) { + const uint8_t f = + (static_cast(values[base + m + q * quarter] + 32) >> 4) & + 0x03; + b |= static_cast(f << (2 * q)); + } + out.push_back(b); + } + } + return out; +} + +// Split 4-bit, per row: byte k = value k in the low nibble, value k+in_dim/2 +// in the high nibble. Same pairing as plane A above, and for the same reason. +// Deliberately written independently of the kernel decode so agreement means +// something. +std::vector pack4( + const std::vector& values, + const size_t in_dim) { + EXPECT_EQ(in_dim % 2, 0u); + EXPECT_EQ(values.size() % in_dim, 0u); + const size_t half = in_dim / 2; + std::vector out; + for (size_t base = 0; base < values.size(); base += in_dim) { + for (size_t k = 0; k < half; ++k) { + const uint8_t lo = static_cast(values[base + k] + 8) & 0x0F; + const uint8_t hi = + static_cast(values[base + k + half] + 8) & 0x0F; + out.push_back(lo | (hi << 4)); + } + } + return out; +} + +std::vector as_int8(const std::vector& bytes) { + return std::vector(bytes.begin(), bytes.end()); +} + +class QuantizedLinearPackedTest : public OperatorTest {}; + +// A packed weight must produce exactly the same output as the dense weight it +// was packed from. This is the property an optimized HiFi kernel has to keep. +TEST_F(QuantizedLinearPackedTest, MatchesDenseKernelSixBit) { + constexpr int64_t kOutDim = 3; + constexpr int64_t kInDim = 8; + + // spans the full 6-bit range including both endpoints + const std::vector dense = { + -32, 31, 0, -1, 1, 17, -17, 30, // + 5, -5, 12, -12, 31, -32, 2, -2, // + 0, 0, 0, 0, -1, 1, -1, 1, + }; + const std::vector packed = as_int8(pack6(dense, kInDim)); + ASSERT_EQ(packed.size(), static_cast(kOutDim * kInDim * 6 / 8)); + + TensorFactory<::executorch::aten::ScalarType::Char> tf_char; + TensorFactory<::executorch::aten::ScalarType::Int> tf_int; + + Tensor src = tf_char.make({1, kInDim}, {7, -3, 0, 12, -40, 5, 60, -1}); + Tensor dense_w = tf_char.make({kOutDim, kInDim}, dense); + Tensor packed_w = tf_char.make( + {static_cast(kOutDim), + static_cast(packed.size() / kOutDim)}, + packed); + Tensor bias = tf_int.make({kOutDim}, {10, -20, 30}); + Tensor out_multiplier = tf_int.make({kOutDim}, {1 << 30, 1 << 29, 1 << 30}); + Tensor out_shift = tf_int.make({kOutDim}, {0, 1, -1}); + + Tensor expected = tf_char.zeros({1, kOutDim}); + Tensor actual = tf_char.zeros({1, kOutDim}); + + ::impl::generic::quantized::quantized_linear_per_channel_( + src, + dense_w, + bias, + /*src_zero_point=*/-5, + /*weight_zero_point=*/0, + out_multiplier, + out_shift, + /*out_zero_point=*/2, + expected); + + ::impl::generic::quantized::quantized_linear_packed_per_channel_( + src, + packed_w, + bias, + kInDim, + /*weight_bits=*/6, + /*src_zero_point=*/-5, + /*weight_zero_point=*/0, + out_multiplier, + out_shift, + /*out_zero_point=*/2, + actual); + + EXPECT_TENSOR_EQ(actual, expected); +} + +TEST_F(QuantizedLinearPackedTest, MatchesDenseKernelFourBit) { + constexpr int64_t kOutDim = 2; + constexpr int64_t kInDim = 6; + + const std::vector dense = { + -8, + 7, + 0, + -1, + 1, + 3, // + 2, + -2, + 5, + -5, + 7, + -8, + }; + const std::vector packed = as_int8(pack4(dense, kInDim)); + + TensorFactory<::executorch::aten::ScalarType::Char> tf_char; + TensorFactory<::executorch::aten::ScalarType::Int> tf_int; + + Tensor src = tf_char.make({1, kInDim}, {1, -2, 3, -4, 5, -6}); + Tensor dense_w = tf_char.make({kOutDim, kInDim}, dense); + Tensor packed_w = tf_char.make( + {static_cast(kOutDim), + static_cast(packed.size() / kOutDim)}, + packed); + Tensor bias = tf_int.make({kOutDim}, {0, 4}); + Tensor out_multiplier = tf_int.make({kOutDim}, {1 << 30, 1 << 30}); + Tensor out_shift = tf_int.make({kOutDim}, {1, 0}); + + Tensor expected = tf_char.zeros({1, kOutDim}); + Tensor actual = tf_char.zeros({1, kOutDim}); + + ::impl::generic::quantized::quantized_linear_per_channel_( + src, dense_w, bias, 0, 0, out_multiplier, out_shift, 0, expected); + + ::impl::generic::quantized::quantized_linear_packed_per_channel_( + src, + packed_w, + bias, + kInDim, + /*weight_bits=*/4, + 0, + 0, + out_multiplier, + out_shift, + 0, + actual); + + EXPECT_TENSOR_EQ(actual, expected); +} + +// out_dim has to survive as shape[0] of the packed tensor: shape inference and +// the fully-connected meta kernels read it. +TEST_F(QuantizedLinearPackedTest, PreservesOutDimAndBatches) { + constexpr int64_t kOutDim = 2; + constexpr int64_t kInDim = 4; + + const std::vector dense = {1, -1, 2, -2, 3, -3, 4, -4}; + const std::vector packed = as_int8(pack6(dense, kInDim)); + + TensorFactory<::executorch::aten::ScalarType::Char> tf_char; + TensorFactory<::executorch::aten::ScalarType::Int> tf_int; + + Tensor packed_w = tf_char.make({kOutDim, 3}, packed); + EXPECT_EQ(packed_w.size(0), kOutDim); + + // two rows of activations exercise the leading_dims loop + Tensor src = tf_char.make({2, kInDim}, {1, 2, 3, 4, -1, -2, -3, -4}); + Tensor dense_w = tf_char.make({kOutDim, kInDim}, dense); + Tensor bias = tf_int.make({kOutDim}, {0, 0}); + Tensor out_multiplier = tf_int.make({kOutDim}, {1 << 30, 1 << 30}); + Tensor out_shift = tf_int.make({kOutDim}, {0, 0}); + + Tensor expected = tf_char.zeros({2, kOutDim}); + Tensor actual = tf_char.zeros({2, kOutDim}); + + ::impl::generic::quantized::quantized_linear_per_channel_( + src, dense_w, bias, 0, 0, out_multiplier, out_shift, 0, expected); + + ::impl::generic::quantized::quantized_linear_packed_per_channel_( + src, + packed_w, + bias, + kInDim, + 6, + 0, + 0, + out_multiplier, + out_shift, + 0, + actual); + + EXPECT_TENSOR_EQ(actual, expected); +} + +// The registered operator, not just the inner kernel: a packed weight through +// quantized_fully_connected_packed_out must match the dense weight through +// quantized_fully_connected_out. This is what the runtime actually dispatches. +TEST_F(QuantizedLinearPackedTest, OpMatchesDenseFullyConnected) { + constexpr int64_t kOutDim = 2; + constexpr int64_t kInDim = 8; + + const std::vector dense = { + -32, + 31, + 0, + -1, + 1, + 17, + -17, + 30, // + 5, + -5, + 12, + -12, + 31, + -32, + 2, + -2, + }; + const std::vector packed = as_int8(pack6(dense, kInDim)); + + TensorFactory<::executorch::aten::ScalarType::Char> tf_char; + TensorFactory<::executorch::aten::ScalarType::Int> tf_int; + + Tensor src = tf_char.make({1, kInDim}, {7, -3, 0, 12, -40, 5, 60, -1}); + Tensor dense_w = tf_char.make({kOutDim, kInDim}, dense); + Tensor packed_w = tf_char.make( + {static_cast(kOutDim), + static_cast(packed.size() / kOutDim)}, + packed); + Tensor bias = tf_int.make({kOutDim}, {10, -20}); + Tensor weight_zero_point = tf_int.make({1}, {0}); + Tensor out_multiplier = tf_int.make({kOutDim}, {1 << 30, 1 << 29}); + Tensor out_shift = tf_int.make({kOutDim}, {0, 1}); + + Tensor expected = tf_char.zeros({1, kOutDim}); + Tensor actual = tf_char.zeros({1, kOutDim}); + + quantized_fully_connected_out( + context_, + src, + dense_w, + bias, + /*in_zero_point=*/-5, + weight_zero_point, + out_multiplier, + out_shift, + /*out_zero_point=*/2, + std::nullopt, + expected); + + quantized_fully_connected_packed_out( + context_, + src, + packed_w, + bias, + kInDim, + /*weight_bits=*/6, + /*in_zero_point=*/-5, + weight_zero_point, + out_multiplier, + out_shift, + /*out_zero_point=*/2, + std::nullopt, + actual); + + EXPECT_TENSOR_EQ(actual, expected); +} + +// A per-tensor source lifts its scalar qparams to length-1 tensors while the +// output still has many channels, so the kernel must stop indexing them by +// channel. Every layer of a real model takes this path. +TEST_F( + QuantizedLinearPackedTest, + OpMatchesDenseFullyConnectedPerTensorQParams) { + constexpr int64_t kOutDim = 2; + constexpr int64_t kInDim = 8; + + const std::vector dense = { + -32, + 31, + 0, + -1, + 1, + 17, + -17, + 30, // + 5, + -5, + 12, + -12, + 31, + -32, + 2, + -2, + }; + const std::vector packed = as_int8(pack6(dense, kInDim)); + + TensorFactory<::executorch::aten::ScalarType::Char> tf_char; + TensorFactory<::executorch::aten::ScalarType::Int> tf_int; + + Tensor src = tf_char.make({1, kInDim}, {7, -3, 0, 12, -40, 5, 60, -1}); + Tensor dense_w = tf_char.make({kOutDim, kInDim}, dense); + Tensor packed_w = tf_char.make( + {static_cast(kOutDim), + static_cast(packed.size() / kOutDim)}, + packed); + Tensor bias = tf_int.make({kOutDim}, {10, -20}); + Tensor weight_zero_point = tf_int.make({1}, {0}); + Tensor out_multiplier = tf_int.make({1}, {1 << 30}); + Tensor out_shift = tf_int.make({1}, {0}); + + Tensor expected = tf_char.zeros({1, kOutDim}); + Tensor actual = tf_char.zeros({1, kOutDim}); + + quantized_fully_connected_out( + context_, + src, + dense_w, + bias, + /*in_zero_point=*/-5, + weight_zero_point, + out_multiplier, + out_shift, + /*out_zero_point=*/2, + std::nullopt, + expected); + + quantized_fully_connected_packed_out( + context_, + src, + packed_w, + bias, + kInDim, + /*weight_bits=*/6, + /*in_zero_point=*/-5, + weight_zero_point, + out_multiplier, + out_shift, + /*out_zero_point=*/2, + std::nullopt, + actual); + + EXPECT_TENSOR_EQ(actual, expected); +} + +} // namespace +} // namespace native +} // namespace generic +} // namespace impl From abd274bac53122420337bd80b9692ee49a908bec Mon Sep 17 00:00:00 2001 From: Ali Afzal Date: Mon, 16 Nov 2026 14:19:59 -0800 Subject: [PATCH 3/4] Fix Cadence compiler bugs that the backend test suite exposes (#24931) Summary: Pull Request resolved: https://github.com/pytorch/executorch/pull/24931 Running the backend test suite through the Cadence compiler (later in this stack) found four compiler bugs. Each fix has unit tests. Fused quantized linear and conv add the int32 bias to an accumulator whose scale is `input_scale * weight_scale`. torchao's implicit sharing gives every call of a shared module one bias observer, so the bias is quantized once, and `QuantizableLSTM` calls the same `Linear` at every time step with a different input scale. In a 10-step int8 LSTM, 18 of 20 fused linears used a bias scaled 0.03x to 1.14x off, and outputs were up to 0.44 off. `bias_at_scale` now rescales the bias constant to the accumulator scale when the two differ, which brings the int8 LSTM outputs within 0.007 of the quantized reference. Fixing this in the quantizer would also unshare the activation and add a dequantize/quantize pair per call. The fusion is shared by every Cadence backend, but a bias already at the accumulator scale, the usual single-use case, passes through unchanged; the 1e-5 match tolerance on the scale ratio is far above the float32 against float64 rounding, which is under 6e-8. In `CompileMode.SIZE`, the dispatch of `quantized_conv2d_nhwc` passed the generic op's 15th argument, `offset`, to the 14-argument typed variants, so every int8 model with a 2-D convolution failed to compile. The dispatch now drops unset arguments that the typed op doesn't have, and raises if one of them is set. The compiler picks `fully_connected` when the input's leading dimensions multiply to 1, but its 6 metas checked `size(0) == 1`, so a 1-D input, where `size(0)` is the feature count, failed to compile. The metas now check the product of the leading dimensions, the same rule the compiler uses. Memory planning can turn a contiguous `select` into a view of its input. The check read the output shape with the raw `dim`, and since `select` drops its dimension, `select(dim=-2)` on `[3, 4, 5]` checked the wrong dimensions and became a view at the wrong offset. The check now normalizes `dim` against the input's rank and reads the input shape. Positive dims and slices are unaffected. Authored with Claude Code. Reviewed By: DrJessop Differential Revision: D128295394 --- backends/cadence/aot/memory_constraints.py | 12 +- backends/cadence/aot/ops_registrations.py | 16 +-- .../cadence/aot/quantizer/pattern_utils.py | 44 ++++++- .../cadence/aot/tests/test_memory_passes.py | 61 ++++++++++ .../cadence/aot/tests/test_pattern_utils.py | 115 ++++++++++++++++++ .../aot/tests/test_replace_ops_passes.py | 79 ++++++++++++ .../aot/tests/test_type_dispatch_passes.py | 27 ++++ backends/cadence/aot/type_dispatch.py | 13 ++ 8 files changed, 349 insertions(+), 18 deletions(-) diff --git a/backends/cadence/aot/memory_constraints.py b/backends/cadence/aot/memory_constraints.py index dbf152b4093..8fdc705efa5 100644 --- a/backends/cadence/aot/memory_constraints.py +++ b/backends/cadence/aot/memory_constraints.py @@ -14,7 +14,7 @@ import torch import torch.fx -from executorch.backends.cadence.aot.pass_utils import CompileMode +from executorch.backends.cadence.aot.pass_utils import CompileMode, get_arg from executorch.backends.cadence.aot.utils import get_shape, is_node_in_flattened_output from executorch.exir import memory from executorch.exir.pass_manager import PassManager @@ -627,11 +627,11 @@ def removable_slice_or_select_op( # A slice/select op is redundant only if (a) either the slicing/select # is along the outermost dimension, or (b) all dimensions previous to - # slicing/select dimension are 0 or 1. - node_spec = node.meta.get("spec") - tensor_shape = list(node_spec.shape) - dim = 0 if len(node.args) == 1 else node.args[1] - if dim and not set(tensor_shape[0:dim]).issubset({0, 1}): + # slicing/select dimension are 0 or 1. A select drops its dimension from + # the output, so use the input shape. + input_shape = input_node.meta["spec"].shape + dim = get_arg(node, "dim", int) % len(input_shape) + if not set(input_shape[0:dim]).issubset({0, 1}): return False # The slice step should be 1 for contiguity. diff --git a/backends/cadence/aot/ops_registrations.py b/backends/cadence/aot/ops_registrations.py index 8fe83f23314..57faeabdb78 100644 --- a/backends/cadence/aot/ops_registrations.py +++ b/backends/cadence/aot/ops_registrations.py @@ -2704,7 +2704,7 @@ def fully_connected_meta( torch._check( src.dtype in (torch.float32, torch.bfloat16), lambda: "expected float dtype" ) - torch._check(src.size(0) == 1, lambda: "expected batch size of 1") + torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1") # src comes in shape [leading_dims, in_dim] # weight comes in shape [out_dim, in_dim] # output comes in empty with shape [leading_dims, out_dim] @@ -2729,11 +2729,10 @@ def quantized_fully_connected_meta( ) -> torch.Tensor: torch._check(bias.dtype == torch.int32, lambda: "expected int32") torch._check(weight.dim() == 2, lambda: "expected 2D tensor") - torch._check(src.size(0) == 1, lambda: "expected batch size of 1") + torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1") # src comes in shape [leading_dims, in_dim] # weight comes in shape [out_dim, in_dim] # output comes in empty with shape [leading_dims, out_dim] - assert src.shape[0] == 1 out_size = list(src.size()) weight_size = list(weight.size()) assert len(weight_size) == 2 @@ -2755,11 +2754,10 @@ def quantized_fully_connected_per_tensor_meta( ) -> torch.Tensor: torch._check(bias.dtype == torch.int32, lambda: "expected int32") torch._check(weight.dim() == 2, lambda: "expected 2D tensor") - torch._check(src.size(0) == 1, lambda: "expected batch size of 1") + torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1") # src comes in shape [leading_dims, in_dim] # weight comes in shape [out_dim, in_dim] # output comes in empty with shape [leading_dims, out_dim] - assert src.shape[0] == 1 out_size = list(src.size()) weight_size = list(weight.size()) assert len(weight_size) == 2 @@ -2783,7 +2781,7 @@ def quantized_fully_connected_packed_meta( ) -> torch.Tensor: torch._check(bias.dtype == torch.int32, lambda: "expected int32") torch._check(weight.dim() == 2, lambda: "expected 2D tensor") - torch._check(src.size(0) == 1, lambda: "expected batch size of 1") + torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1") # src comes in shape [leading_dims, in_dim] # weight comes in shape [out_dim, packed_row_bytes], so out_dim is still # size(0) - that is what packing per row buys us - but in_dim is an @@ -2812,11 +2810,10 @@ def quantized_fully_connected_asym8sxasym8s_asym8s_per_tensor_meta( ) torch._check(bias.dtype == torch.int32, lambda: "expected int32") torch._check(weight.dim() == 2, lambda: "expected 2D tensor") - torch._check(src.size(0) == 1, lambda: "expected batch size of 1") + torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1") # src comes in shape [leading_dims, in_dim] # weight comes in shape [out_dim, in_dim] # output comes in empty with shape [leading_dims, out_dim] - assert src.shape[0] == 1 out_size = list(src.size()) weight_size = list(weight.size()) assert len(weight_size) == 2 @@ -2842,11 +2839,10 @@ def quantized_fully_connected_asym8uxasym8u_asym8u_per_tensor_meta( ) torch._check(bias.dtype == torch.int32, lambda: "expected int32") torch._check(weight.dim() == 2, lambda: "expected 2D tensor") - torch._check(src.size(0) == 1, lambda: "expected batch size of 1") + torch._check(prod(src.shape[:-1]) == 1, lambda: "expected batch size of 1") # src comes in shape [leading_dims, in_dim] # weight comes in shape [out_dim, in_dim] # output comes in empty with shape [leading_dims, out_dim] - assert src.shape[0] == 1 out_size = list(src.size()) weight_size = list(weight.size()) assert len(weight_size) == 2 diff --git a/backends/cadence/aot/quantizer/pattern_utils.py b/backends/cadence/aot/quantizer/pattern_utils.py index 7f48c7c374d..d9c330916f4 100644 --- a/backends/cadence/aot/quantizer/pattern_utils.py +++ b/backends/cadence/aot/quantizer/pattern_utils.py @@ -227,6 +227,46 @@ def get_weight_zero_point(gm: fx.GraphModule, dq_weight: fx.Node) -> int | torch return zps.to(torch.int32).flatten() +# The quantizer computes the bias scale in float32 and fusion in float64, so a +# bias at the accumulator scale gives a ratio within 6e-8 of 1. +_BIAS_SCALE_RATIO_ATOL = 1e-5 + + +def bias_at_scale( + gm: fx.GraphModule, + dq_bias: fx.Node, + bias_scale: float | torch.Tensor, + like_node: fx.Node, +) -> fx.Node: + """The int32 bias operand for an accumulator at ``bias_scale``. + + Quantized linear and conv ops add the int32 bias straight to the int32 + accumulator, whose scale is input_scale * weight_scale. The quantizer derives + the bias scale the same way, but quantizes a shared bias only once, so a + Linear that runs on inputs with different scales (QuantizableLSTM runs one per + time step) has a bias whose scale matches only one of them. For the others, + this returns the bias constant rescaled to ``bias_scale``. + """ + bias_q = get_arg(dq_bias, "input", fx.Node) + ratio = torch.as_tensor(get_weight_scale(gm, dq_bias), dtype=torch.float64) / ( + torch.as_tensor(bias_scale, dtype=torch.float64) + ) + if torch.allclose( + ratio, torch.ones_like(ratio), rtol=0, atol=_BIAS_SCALE_RATIO_ATOL + ): + return bias_q + values = resolve_constant(gm, bias_q) + assert ( + values is not None + ), f"cannot rescale {bias_q}: the bias is not a constant of the program" + rescaled = torch.round(values.to(torch.float64) * ratio) + int32 = torch.iinfo(torch.int32) + assert bool( + ((rescaled >= int32.min) & (rescaled <= int32.max)).all() + ), f"cannot rescale {bias_q}: the rescaled bias does not fit in int32" + return add_constant_placeholder(gm, rescaled.to(torch.int32), like_node, "bias") + + def insert_node_with_meta( gm: fx.GraphModule, op: OpOverload, @@ -296,7 +336,7 @@ def fuse_conv( input_scale = get_arg(dq_input, "scale", float) bias_scale = input_scale * weight_scale if dq_bias is not None: - bias_q = get_arg(dq_bias, "input", fx.Node) + bias_q = bias_at_scale(gm, dq_bias, bias_scale, conv_node) else: # Cadence quantized conv ops require a non-optional bias argument. weight_node = get_arg(dq_weight, "input", fx.Node) @@ -387,7 +427,7 @@ def fuse_linear( ) out_multiplier, out_shift = quantize_tensor_multiplier(requantize_scale_t) if dq_bias is not None: - bias_q = get_arg(dq_bias, "input", fx.Node) + bias_q = bias_at_scale(gm, dq_bias, bias_scale, op_node) else: # Cadence quantized linear ops require a non-optional bias argument. weight_node = get_arg(dq_weight, "input", fx.Node) diff --git a/backends/cadence/aot/tests/test_memory_passes.py b/backends/cadence/aot/tests/test_memory_passes.py index b7e2cce193b..3862400230c 100644 --- a/backends/cadence/aot/tests/test_memory_passes.py +++ b/backends/cadence/aot/tests/test_memory_passes.py @@ -1016,6 +1016,67 @@ def test_optimize_select_non_outermost(self) -> None: ) self.verify_nop_memory_alloc(graph_module) + def _plan_select_or_slice( + self, + input_shape: list[int], + op: torch._ops.OpOverload, + args: tuple[int, ...], + out_shape: list[int], + ) -> torch.fx.GraphModule: + """Memory-plans op(add(x, full), *args), whose input is planned.""" + builder = GraphBuilder() + x = builder.placeholder("x", torch.ones(*input_shape, dtype=torch.float32)) + to_add_to_x = builder.call_operator( + op=exir_ops.edge.aten.full.default, + args=(input_shape, 123.0), + kwargs={"dtype": torch.float32}, + ) + add_x = builder.call_operator( + op=exir_ops.edge.aten.add.Tensor, args=(x, to_add_to_x) + ) + out = builder.call_operator( + op=exir_ops.edge.aten.full.default, + args=(out_shape, 0.0), + kwargs={"dtype": torch.float32}, + ) + result = builder.call_operator(op=op, args=(add_x, *args), kwargs={"out": out}) + builder.output([result]) + graph_module = self.run_memory_planning_only( + builder.get_graph_module(), alloc_graph_input=False + ) + graph_module.graph.eliminate_dead_code() + return graph_module + + def test_does_not_optimize_select_on_a_negative_inner_dim(self) -> None: + # dim=-2 of a [3, 4, 5] input is dim 1, behind a dim of size 3, so the + # selected values are not contiguous in the input. + graph_module = self._plan_select_or_slice( + [3, 4, 5], torch.ops.aten.select_copy.int_out, (-2, 1), [3, 5] + ) + self.assertEqual( + count_node(graph_module, torch.ops.aten._select_copy_nop.int_out), 0 + ) + self.assertEqual( + count_node(graph_module, torch.ops.aten.select_copy.int_out), 1 + ) + + def test_optimize_select_on_a_negative_outermost_dim(self) -> None: + graph_module = self._plan_select_or_slice( + [3, 6], torch.ops.aten.select_copy.int_out, (-2, 1), [6] + ) + self.assertEqual( + count_node(graph_module, torch.ops.aten._select_copy_nop.int_out), 1 + ) + self.verify_nop_memory_alloc(graph_module) + + def test_does_not_optimize_slice_on_a_negative_inner_dim(self) -> None: + graph_module = self._plan_select_or_slice( + [3, 6], torch.ops.aten.slice_copy.Tensor_out, (-1, 0, 2, 1), [3, 2] + ) + self.assertEqual( + count_node(graph_module, torch.ops.aten._slice_copy_nop.Tensor_out), 0 + ) + def test_optimize_select_depending_on_mode(self) -> None: builder = GraphBuilder() x = builder.placeholder("x", torch.ones(2, 6, dtype=torch.float32)) diff --git a/backends/cadence/aot/tests/test_pattern_utils.py b/backends/cadence/aot/tests/test_pattern_utils.py index 1851a8fe0d1..b0af9fb97d9 100644 --- a/backends/cadence/aot/tests/test_pattern_utils.py +++ b/backends/cadence/aot/tests/test_pattern_utils.py @@ -917,3 +917,118 @@ def test_encoded_multiplier_shift_matches_reference(self) -> None: f"out_shift per channel: got {out_shift}, " f"expected {expected_shift.to(torch.int32)}", ) + + +class TestFusedBiasScale(unittest.TestCase): + """The fused int32 bias must be at the accumulator scale, input * weight. + + The quantizer quantizes a shared bias once, so a Linear that runs on inputs + with different scales (QuantizableLSTM runs one per time step) reaches fusion + with a bias whose scale matches only one of its calls. + """ + + INPUT_SCALE = 0.1 + WEIGHT_SCALE = 0.05 + BIAS = torch.tensor([100, -50, 25, 0], dtype=torch.int32) + + def _build_program( + self, op: torch._ops.OpOverload, bias_scale: float, bias: torch.Tensor + ) -> tuple[ExportedProgram, torch.fx.Node]: + """A dq -> op(input, weight, bias) -> q program, the bias at bias_scale.""" + out_channels = bias.numel() + is_conv = op == torch.ops.aten.conv1d.default + builder = ProgramBuilder() + x_q = builder.placeholder( + "x_q", + torch.randint(-8, 8, (1, 3, 5) if is_conv else (2, 3), dtype=torch.int8), + ) + w_q = builder.placeholder( + "w_q", + torch.randint( + -8, 8, (out_channels, 3, 1) if is_conv else (out_channels, 3) + ).to(torch.int8), + input_kind=InputKind.CONSTANT_TENSOR, + ) + b_q = builder.placeholder("b_q", bias, input_kind=InputKind.CONSTANT_TENSOR) + dq_input = builder.call_operator( + op=DQ_PER_TENSOR, args=(x_q, self.INPUT_SCALE, 0, -128, 127, torch.int8) + ) + dq_weight = builder.call_operator( + op=DQ_PER_TENSOR, args=(w_q, self.WEIGHT_SCALE, 0, -128, 127, torch.int8) + ) + dq_bias = builder.call_operator( + op=DQ_PER_TENSOR, + args=(b_q, bias_scale, 0, -(2**31), 2**31 - 1, torch.int32), + ) + anchor = builder.call_operator(op=op, args=(dq_input, dq_weight, dq_bias)) + q = builder.call_operator( + op=Q_PER_TENSOR, args=(anchor, 0.2, 0, -128, 127, torch.int8) + ) + builder.output([q]) + ep = builder.get_program() + ep.graph_module.meta[EXPORTED_PROGRAM_META_KEY] = ep + return ep, ep.graph.find_nodes(op="call_function", target=op)[0] + + def _fused_bias( + self, op: torch._ops.OpOverload, bias_scale: float, bias: torch.Tensor + ) -> tuple[ExportedProgram, torch.fx.Node]: + ep, anchor = self._build_program(op, bias_scale, bias) + pattern = ( + Conv1dPattern() if op == torch.ops.aten.conv1d.default else LinearPattern() + ) + fused = pattern.fuse(ep.graph_module, anchor) + self.assertIsNotNone(fused) + bias_node = cast(torch.fx.Node, fused).args[2] + self.assertIsInstance(bias_node, torch.fx.Node) + return ep, cast(torch.fx.Node, bias_node) + + def test_linear_rescales_a_bias_quantized_for_another_input_scale(self) -> None: + # The bias was quantized at 0.4 times the accumulator scale of this call. + bias_scale = 0.4 * self.INPUT_SCALE * self.WEIGHT_SCALE + ep, bias_node = self._fused_bias( + torch.ops.aten.linear.default, bias_scale, self.BIAS + ) + + rescaled = resolve_constant(ep.graph_module, bias_node) + + self.assertIsNotNone(rescaled) + self.assertTrue( + torch.equal( + cast(torch.Tensor, rescaled), + torch.tensor([40, -20, 10, 0], dtype=torch.int32), + ) + ) + + def test_conv_rescales_a_bias_quantized_for_another_input_scale(self) -> None: + bias_scale = 2.0 * self.INPUT_SCALE * self.WEIGHT_SCALE + ep, bias_node = self._fused_bias( + torch.ops.aten.conv1d.default, bias_scale, self.BIAS + ) + + rescaled = resolve_constant(ep.graph_module, bias_node) + + self.assertIsNotNone(rescaled) + self.assertTrue( + torch.equal( + cast(torch.Tensor, rescaled), + torch.tensor([200, -100, 50, 0], dtype=torch.int32), + ) + ) + + def test_bias_at_the_accumulator_scale_is_used_as_is(self) -> None: + _, bias_node = self._fused_bias( + torch.ops.aten.linear.default, + self.INPUT_SCALE * self.WEIGHT_SCALE, + self.BIAS, + ) + + self.assertEqual(bias_node.name, "b_q") + + def test_rescaling_past_int32_raises(self) -> None: + bias = torch.tensor([2**30, 0, 0, 0], dtype=torch.int32) + with self.assertRaisesRegex(AssertionError, "does not fit in int32"): + self._fused_bias( + torch.ops.aten.linear.default, + 4.0 * self.INPUT_SCALE * self.WEIGHT_SCALE, + bias, + ) diff --git a/backends/cadence/aot/tests/test_replace_ops_passes.py b/backends/cadence/aot/tests/test_replace_ops_passes.py index 0b6c07bddee..e560c8beb95 100644 --- a/backends/cadence/aot/tests/test_replace_ops_passes.py +++ b/backends/cadence/aot/tests/test_replace_ops_passes.py @@ -57,6 +57,7 @@ from executorch.backends.test.graph_builder import GraphBuilder, single_op_builder from executorch.exir.dialects._ops import ops as exir_ops from executorch.exir.pass_base import ExportPass, ProxyValue +from torch._subclasses.fake_tensor import FakeTensorMode from torch.fx.passes.infra.pass_base import PassResult from torch.utils import _pytree as pytree @@ -1206,6 +1207,84 @@ def test_replace_scalar_tensor_with_full( 0, ) + def test_linear_on_a_1d_input_becomes_fully_connected(self) -> None: + """A 1-D input is one row, so the pass replaces it and the meta accepts it.""" + out_features, in_features = 4, 6 + src = torch.randint(-8, 8, (in_features,), dtype=torch.int8) + weight = torch.randint(-8, 8, (out_features, in_features), dtype=torch.int8) + bias = torch.randint(-16, 16, (out_features,), dtype=torch.int32) + gm = single_op_builder( + placeholders=(src, weight, bias), + op=exir_ops.edge.cadence.quantized_linear.per_tensor, + args=(src, weight, bias, 0, 0, 1 << 30, 0, 0, None), + ) + + gm_after = cast( + PassResult, ReplaceLinearWithFullyConnectedOpPass()(gm) + ).graph_module + + fc = exir_ops.edge.cadence.quantized_fully_connected.per_tensor + self.assertEqual(count_node(gm_after, fc), 1) + node = gm_after.graph.find_nodes(op="call_function", target=fc)[0] + self.assertEqual(tuple(node.meta["val"].shape), (out_features,)) + + @expand( + [ + ("float", "fully_connected"), + ("quantized", "quantized_fully_connected"), + ("per_tensor", "quantized_fully_connected.per_tensor"), + ("packed", "quantized_fully_connected_packed"), + ("asym8s", "quantized_fully_connected_asym8sxasym8s_asym8s.per_tensor"), + ("asym8u", "quantized_fully_connected_asym8uxasym8u_asym8u.per_tensor"), + ] + ) + def test_fully_connected_meta_accepts_exactly_one_row( + self, _: str, op: str + ) -> None: + """Every fully_connected meta takes one row: a 1-D input, but not [2, in].""" + name, _, overload = op.partition(".") + target = getattr(getattr(torch.ops.cadence, name), overload or "default") + if name == "fully_connected": + dtype = torch.float32 + else: + dtype = torch.uint8 if "asym8u" in name else torch.int8 + out_features, in_features = 4, 6 + w = torch.zeros(out_features, in_features, dtype=dtype) + b = torch.zeros(out_features, dtype=torch.int32) + qparams = torch.zeros(1, dtype=torch.int32) + + def args(src: torch.Tensor) -> tuple[object, ...]: + if name == "fully_connected": + return (src, w, None) + if op == "quantized_fully_connected": + return (src, w, b, 0, None, qparams, qparams, 0, None) + if name == "quantized_fully_connected_packed": + packed = torch.zeros(out_features, in_features // 2, dtype=torch.int8) + return ( + src, + packed, + b, + in_features, + 4, + 0, + None, + qparams, + qparams, + 0, + None, + ) + return (src, w, b, 0, 0, 1 << 30, 0, 0, None) + + with FakeTensorMode(allow_non_fake_inputs=True): + out = target(*args(torch.zeros(in_features, dtype=dtype))) + self.assertEqual(tuple(out.shape), (out_features,)) + for shape in ((2, in_features), (1, 2, in_features)): + with self.subTest(shape=shape): + with self.assertRaisesRegex( + RuntimeError, "expected batch size of 1" + ): + target(*args(torch.zeros(shape, dtype=dtype))) + @torch.no_grad() def test_replace_linear_with_fully_connected(self) -> None: shape, in_channels, out_channels = (1, 14), 14, 128 diff --git a/backends/cadence/aot/tests/test_type_dispatch_passes.py b/backends/cadence/aot/tests/test_type_dispatch_passes.py index 595b79dd8c6..1fa24ed7e70 100644 --- a/backends/cadence/aot/tests/test_type_dispatch_passes.py +++ b/backends/cadence/aot/tests/test_type_dispatch_passes.py @@ -250,6 +250,33 @@ def test_dispatch_quantized_conv_2d( # Should be replaced with dtype-specific variant self.assertEqual(count_node(gm, expected_op), 1) + def _nhwc_conv_with_offset(self, offset: torch.Tensor | None) -> PassResult: + x = torch.randint(-128, 127, (1, 8, 8, 3), dtype=torch.int8) + w = torch.randint(-128, 127, (16, 3, 3, 3), dtype=torch.int8) + b = torch.randint(-2147483648, 2147483647, (16,), dtype=torch.int32) + placeholders = (x, w, b) if offset is None else (x, w, b, offset) + gm = single_op_builder( + placeholders=placeholders, + op=exir_ops.edge.cadence.quantized_conv2d_nhwc.per_tensor, + args=(x, w, b, [1, 1], [0, 0], [1, 1], 1, 0, 0, 1.0, 1.0, 0, 1, 1, offset), + ) + return cast(PassResult, CompileTimeTypeDispatchPass()(gm)) + + def test_dispatch_quantized_conv_2d_nhwc_with_bound_offset(self) -> None: + """BindOptionalArgsPass binds offset=None, which the typed variants lack.""" + gm = self._nhwc_conv_with_offset(None).graph_module + + typed = ( + exir_ops.edge.cadence.quantized_conv2d_nhwc_asym8sxsym8s_asym8s.per_tensor + ) + self.assertEqual(count_node(gm, typed), 1) + node = gm.graph.find_nodes(op="call_function", target=typed)[0] + self.assertEqual(len(node.args), 14) + + def test_dispatch_quantized_conv_2d_nhwc_rejects_an_offset(self) -> None: + with self.assertRaisesRegex(RuntimeError, "no operand for the extra args"): + self._nhwc_conv_with_offset(torch.zeros(16, dtype=torch.int32)) + @expand( [ ( diff --git a/backends/cadence/aot/type_dispatch.py b/backends/cadence/aot/type_dispatch.py index c2a2dcd9fc7..256f17b0b49 100644 --- a/backends/cadence/aot/type_dispatch.py +++ b/backends/cadence/aot/type_dispatch.py @@ -176,4 +176,17 @@ def call_operator( getattr(exir_ops.edge.cadence, typed_op_name), config.variant ) + # The generic op can have trailing optional args that its typed variants + # lack, such as quantized_conv2d_nhwc's offset. They have to be unset. + typed_arg_names = [arg.name for arg in typed_op._schema.arguments] + extra_args = list(args[len(typed_arg_names) :]) + [ + value for name, value in kwargs.items() if name not in typed_arg_names + ] + if any(arg is not None for arg in extra_args): + raise RuntimeError( + f"{typed_op_name} has no operand for the extra args of {op}: {extra_args}" + ) + args = args[: len(typed_arg_names)] + kwargs = {name: kwargs[name] for name in kwargs if name in typed_arg_names} + return super().call_operator(typed_op, args, kwargs, meta) From 6bca9f2a9950cee5959f8fa7ec764d43a4930521 Mon Sep 17 00:00:00 2001 From: Ali Afzal Date: Mon, 16 Nov 2026 14:20:02 -0800 Subject: [PATCH 4/4] Lint the yamls, test op registration, and register the CPU runner's kernels (#24935) Summary: Pull Request resolved: https://github.com/pytorch/executorch/pull/24935 The x86 `cadence_runner` couldn't load most programs the Cadence compiler produces for CPU, because `backends/cadence/aot/functions.yaml` didn't register their kernels, and nothing checked the yamls or the registry. This diff adds both checks and registers the missing kernels. The yaml lint, `aot/tests/test_functions_yaml.py`, checks every `functions*.yaml` for kernel names codegen can't resolve and for namespaces outside the libraries the backend builds. It found five bad entries, fixed here. `functions.yaml` registered `cadence::quantized_max_pool2d.out`, an op that no longer exists, instead of the `quantized_max_pool2d_nchw.out` the compiler emits. `functions_hifi.yaml` bound `quantize_per_tensor_asym16u` and `dequantize_per_tensor_asym32s` to the asym16s kernels, which clamp to int16 and read int32 as int16; on the simulator a round trip of 1.0 returned 0.65534 and alternating -0.31072 and 0.00001, and with the right kernels it returns 1.0, so this changes HiFi results for those two ops from wrong to correct. `functions_fusion_g3.yaml` had an extra `native::` in two names; Fusion G3 doesn't build against the pinned nnlib yet, so no CI result changes. The registry test, `cadence_op_registry_test`, links the ops library and checks with `registry_has_op_function` that every op codegen selected from the yaml is registered. It catches a dropped registration, an unlinked kernel library, or the kernel table filling up before every op is registered. It reads its expected ops from the same yaml, so it can't catch an op missing from the yaml altogether; the backend test suite catches that. It runs on the host for `functions.yaml`, where it shares the runner's codegen and yaml but not its link line, because the runner links `cadence_ops_lib` again in its second-stage build, and on the simulator for the HiFi cores. Vision isn't included because OSS has neither a Vision op-test job nor the `vision/operators/tests/CMakeLists.txt` that would supply gtest; with a stub CMakeLists the test passes on the Vision simulator, so adding it is a separate change with its own CI job. The diff registers the 7 Cadence ops the compiler emits for CPU (`conv1d`, `conv2d`, `avg_pool2d`, `fully_connected`, `transposed_im2row`, `transposed_convolution` and `_softmax_f32_f32`) against the existing generic kernels, and 38 ATen ops against their portable kernels. `conv3d` stays unregistered until a test covers it, and the 3-D pools have no portable kernel. `aten::linear.out` maps to the generic `fully_connected` kernel because the compiler keeps `aten.linear` on purpose and there is no portable linear kernel. `ReplaceLinearWithFullyConnectedOpPass` rewrites a linear to `fully_connected` only when it has one row, because the HiFi kernels compute one row, but the generic kernel computes every leading row with the same schema, and the kernel diff earlier in this stack added its dtype and shape checks. `cadence_ops_lib` now links `portable_kernels` instead of the hand-kept source list in `aten_ops_cadence`, which is removed, so `functions.yaml` is the only list. Registration still comes only from the yaml and the linker keeps only the kernels it references, so the runner grows from 3.1 MB to 4.4 MB. The HiFi, Vision and Fusion G3 builds don't change. Authored with Claude Code. Reviewed By: DrJessop Differential Revision: D128295395 --- .ci/scripts/test-cadence-generic.sh | 17 +- .ci/scripts/test-cadence-xtensa.sh | 62 +++-- .github/workflows/_xtensa_test.yml | 11 +- backends/cadence/CMakeLists.txt | 36 +++ backends/cadence/aot/BUCK | 18 ++ backends/cadence/aot/functions.yaml | 238 +++++++++++++++++- backends/cadence/aot/functions_fusion_g3.yaml | 4 +- backends/cadence/aot/functions_hifi.yaml | 4 +- .../cadence/aot/tests/test_functions_yaml.py | 79 ++++++ backends/cadence/cadence_op_registry_test.cpp | 37 +++ .../cadence/generic/operators/CMakeLists.txt | 66 +---- .../generic/operators/tests/CMakeLists.txt | 17 +- .../cadence/utils/gen_selected_ops_header.py | 38 +++ 13 files changed, 512 insertions(+), 115 deletions(-) create mode 100644 backends/cadence/aot/tests/test_functions_yaml.py create mode 100644 backends/cadence/cadence_op_registry_test.cpp create mode 100644 backends/cadence/utils/gen_selected_ops_header.py diff --git a/.ci/scripts/test-cadence-generic.sh b/.ci/scripts/test-cadence-generic.sh index 548901ab754..051d4701818 100755 --- a/.ci/scripts/test-cadence-generic.sh +++ b/.ci/scripts/test-cadence-generic.sh @@ -6,7 +6,8 @@ # LICENSE file in the root directory of this source tree. # # Build the Cadence generic (reference) op-level gtest tests for the host and -# run them. +# run them, then build and run cadence_op_registry_test, which checks that every +# op in backends/cadence/aot/functions.yaml is registered by cadence_ops_lib. # # Unlike backends/cadence/build_cadence_runner.sh (built -fno-exceptions # -fno-rtti), the gtest tests need exceptions + RTTI, so those flags are NOT set @@ -14,8 +15,11 @@ set -euo pipefail -TEST_TARGET=cadence_generic_op_tests -TEST_BIN="cmake-out/backends/cadence/generic/operators/tests/${TEST_TARGET}" +BUILD_TARGETS=(cadence_generic_op_tests cadence_op_registry_test) +TEST_BINS=( + cmake-out/backends/cadence/generic/operators/tests/cadence_generic_op_tests + cmake-out/backends/cadence/cadence_op_registry_test +) rm -rf cmake-out cmake \ @@ -28,6 +32,9 @@ cmake \ -DPYTHON_EXECUTABLE="$(which python3)" \ -Bcmake-out . -cmake --build cmake-out --target "${TEST_TARGET}" -j"$(nproc)" +cmake --build cmake-out --target "${BUILD_TARGETS[@]}" -j"$(nproc)" -"${TEST_BIN}" +for TEST_BIN in "${TEST_BINS[@]}"; do + echo "=== running $(basename "${TEST_BIN}") ===" + "${TEST_BIN}" +done diff --git a/.ci/scripts/test-cadence-xtensa.sh b/.ci/scripts/test-cadence-xtensa.sh index dc24eb61f19..63dd7987dd8 100755 --- a/.ci/scripts/test-cadence-xtensa.sh +++ b/.ci/scripts/test-cadence-xtensa.sh @@ -6,7 +6,9 @@ # LICENSE file in the root directory of this source tree. # # Build the Cadence Xtensa op-level gtest tests for the configured backend and -# run them on the Instruction Set Simulator (xt-run). +# run them on the Instruction Set Simulator (xt-run). On backends that opt in, +# also build and run cadence_op_registry_test, which checks that every op in the +# backend's functions yaml is registered by cadence_ops_lib. # # Requires the Xtensa toolchain env to already be set (run # .ci/scripts/setup-xtensa-tools.sh first): XTENSA_TOOLCHAIN, @@ -22,21 +24,27 @@ set -euo pipefail : "${XTENSA_CORE:?run setup-xtensa-tools.sh first}" : "${CADENCE_OPT_FLAG:?run setup-xtensa-tools.sh first}" -# Map the optimized-kernel flag to the backend dir + gtest target name. +# Map the optimized-kernel flag to the backend dir + gtest target name, and +# whether the backend runs cadence_op_registry_test. case "${CADENCE_OPT_FLAG}" in - EXECUTORCH_NNLIB_OPT) TARGET_DIR=hifi ;; - EXECUTORCH_VISION_OPT) TARGET_DIR=vision ;; - EXECUTORCH_FUSION_G3_OPT) TARGET_DIR=fusion_g3 ;; + EXECUTORCH_NNLIB_OPT) TARGET_DIR=hifi RUN_REGISTRY_TEST=1 ;; + EXECUTORCH_VISION_OPT) TARGET_DIR=vision RUN_REGISTRY_TEST=0 ;; + EXECUTORCH_FUSION_G3_OPT) TARGET_DIR=fusion_g3 RUN_REGISTRY_TEST=0 ;; *) echo "ERROR: unknown CADENCE_OPT_FLAG='${CADENCE_OPT_FLAG}'" >&2 exit 1 ;; esac TEST_TARGET="cadence_${TARGET_DIR}_op_tests" -TEST_ELF="cmake-out/backends/cadence/${TARGET_DIR}/operators/tests/${TEST_TARGET}" +TEST_ELFS=("cmake-out/backends/cadence/${TARGET_DIR}/operators/tests/${TEST_TARGET}") +BUILD_TARGETS=("${TEST_TARGET}") +if [[ "${RUN_REGISTRY_TEST}" == "1" ]]; then + BUILD_TARGETS+=(cadence_op_registry_test) + TEST_ELFS+=(cmake-out/backends/cadence/cadence_op_registry_test) +fi NPROC=$(nproc) -echo "=== building ${TEST_TARGET} for ${XTENSA_CORE} (${CADENCE_OPT_FLAG}) ===" +echo "=== building ${BUILD_TARGETS[*]} for ${XTENSA_CORE} (${CADENCE_OPT_FLAG}) ===" xt-clang --version | head -1 rm -rf cmake-out @@ -61,24 +69,26 @@ cmake \ -DPYTHON_EXECUTABLE="$(which python3)" \ -Bcmake-out . -cmake --build cmake-out --target "${TEST_TARGET}" -j"${NPROC}" - -if [[ ! -f "${TEST_ELF}" ]]; then - echo "ERROR: ${TEST_ELF} was not produced" >&2 - exit 1 -fi +cmake --build cmake-out --target "${BUILD_TARGETS[@]}" -j"${NPROC}" -echo "=== running ${TEST_TARGET} on xt-run ===" -LOG=$(mktemp) -# --exit_with_target_code propagates gtest_main's exit code, so a failing test -# fails this step; also assert on the gtest summary lines as a backstop. -xt-run --turbo --exit_with_target_code "${TEST_ELF}" 2>&1 | tee "${LOG}" -if grep -q "\[ FAILED \]" "${LOG}"; then - echo "ERROR: gtest reported failures for ${TEST_TARGET}" >&2 - exit 1 -fi -if ! grep -q "\[ PASSED \]" "${LOG}"; then - echo "ERROR: ${TEST_TARGET} did not report a gtest PASSED summary" >&2 - exit 1 -fi +for TEST_ELF in "${TEST_ELFS[@]}"; do + if [[ ! -f "${TEST_ELF}" ]]; then + echo "ERROR: ${TEST_ELF} was not produced" >&2 + exit 1 + fi + TEST_NAME=$(basename "${TEST_ELF}") + echo "=== running ${TEST_NAME} on xt-run ===" + LOG=$(mktemp) + # --exit_with_target_code propagates gtest_main's exit code, so a failing test + # fails this step; also assert on the gtest summary lines as a backstop. + xt-run --turbo --exit_with_target_code "${TEST_ELF}" 2>&1 | tee "${LOG}" + if grep -q "\[ FAILED \]" "${LOG}"; then + echo "ERROR: gtest reported failures for ${TEST_NAME}" >&2 + exit 1 + fi + if ! grep -q "\[ PASSED \]" "${LOG}"; then + echo "ERROR: ${TEST_NAME} did not report a gtest PASSED summary" >&2 + exit 1 + fi +done echo "Cadence ${TARGET_DIR} op tests passed on ${XTENSA_CORE}." diff --git a/.github/workflows/_xtensa_test.yml b/.github/workflows/_xtensa_test.yml index d2a7bd50519..9ed56eac5ac 100644 --- a/.github/workflows/_xtensa_test.yml +++ b/.github/workflows/_xtensa_test.yml @@ -1,10 +1,13 @@ # Reusable: build + run the Cadence Xtensa op-level gtest tests for one core on # the Instruction Set Simulator (xt-run). Mirrors _xtensa_build.yml's native # OIDC skeleton (running xt-run needs the same licensed toolchain), -# then builds the gtest op-test ELF and runs it on the simulator. The runner -# cross-compile and these op tests are separate build configs (the tests need -# exceptions/RTTI that the runner build disables), so this is a self-contained -# job rather than consuming the runner artifact. +# then builds the gtest op-test ELF and runs it on the simulator. On backends +# that opt in, test-cadence-xtensa.sh also builds and runs +# cadence_op_registry_test, which checks that cadence_ops_lib registers every +# op in the backend's functions yaml. The runner cross-compile and these op +# tests are separate build configs (the tests need exceptions/RTTI that the +# runner build disables), so this is a self-contained job rather than +# consuming the runner artifact. name: xtensa-test on: diff --git a/backends/cadence/CMakeLists.txt b/backends/cadence/CMakeLists.txt index 703813735db..148f58ba75e 100644 --- a/backends/cadence/CMakeLists.txt +++ b/backends/cadence/CMakeLists.txt @@ -155,4 +155,40 @@ if(EXECUTORCH_BUILD_CADENCE_OP_TESTS "${CMAKE_CURRENT_SOURCE_DIR}/${TARGET_DIR}/operators/tests/CMakeLists.txt" ) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/${TARGET_DIR}/operators/tests) + + # Op-registry gtest: links cadence_ops_lib the way cadence_executor_runner + # does and checks that every op codegen selected from the backend's functions + # yaml is in the kernel registry after runtime_init(). The op list is read at + # build time from cadence_ops_lib's selected_operators.yaml. gtest comes from + # the op-test dir above. + get_target_property(_cadence_ops_lib_dir cadence_ops_lib BINARY_DIR) + set(_selected_ops_yaml + ${_cadence_ops_lib_dir}/cadence_ops_lib/selected_operators.yaml + ) + set(_selected_ops_h + ${CMAKE_CURRENT_BINARY_DIR}/cadence_ops_lib_selected_ops.h + ) + add_custom_command( + OUTPUT ${_selected_ops_h} + COMMAND + ${PYTHON_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/utils/gen_selected_ops_header.py + --oplist-yaml=${_selected_ops_yaml} --output-path=${_selected_ops_h} + DEPENDS ${_selected_ops_yaml} + ${CMAKE_CURRENT_SOURCE_DIR}/utils/gen_selected_ops_header.py + ) + add_executable( + cadence_op_registry_test cadence_op_registry_test.cpp ${_selected_ops_h} + ) + target_compile_definitions( + cadence_op_registry_test PRIVATE GTEST_HAS_PTHREAD=0 + ) + target_include_directories( + cadence_op_registry_test PRIVATE ${_common_include_directories} + ${CMAKE_CURRENT_BINARY_DIR} + ) + target_link_libraries( + cadence_op_registry_test PRIVATE gtest gtest_main executorch + cadence_ops_lib + ) endif() diff --git a/backends/cadence/aot/BUCK b/backends/cadence/aot/BUCK index b9ab1c4a956..2fad03694d2 100644 --- a/backends/cadence/aot/BUCK +++ b/backends/cadence/aot/BUCK @@ -168,6 +168,13 @@ fbcode_target(_kind = executorch_generated_lib, "//executorch/backends/cadence/generic/operators:op_quantized_max_pool2d_nhwc", "//executorch/backends/cadence/generic/operators:op_quantized_mul", "//executorch/backends/cadence/generic/operators:op_quantized_relu", + "//executorch/backends/cadence/generic/operators:op_avg_pool2d", + "//executorch/backends/cadence/generic/operators:op_conv1d", + "//executorch/backends/cadence/generic/operators:op_conv2d", + "//executorch/backends/cadence/generic/operators:op_fully_connected", + "//executorch/backends/cadence/generic/operators:op_softmax", + "//executorch/backends/cadence/generic/operators:op_transposed_convolution", + "//executorch/backends/cadence/generic/operators:op_transposed_im2row", "//executorch/kernels/portable:executorch_all_ops", "//executorch/kernels/portable:operators", ], @@ -741,3 +748,14 @@ fbcode_target(_kind = python_unittest, "//later:lib", ], ) + +fbcode_target(_kind = python_unittest, + name = "test_functions_yaml", + srcs = [ + "tests/test_functions_yaml.py", + ], + resources = glob(["functions*.yaml"]), + deps = [ + "fbsource//third-party/pypi/pyyaml:pyyaml", + ], +) diff --git a/backends/cadence/aot/functions.yaml b/backends/cadence/aot/functions.yaml index 449b5794714..0e29967c432 100644 --- a/backends/cadence/aot/functions.yaml +++ b/backends/cadence/aot/functions.yaml @@ -192,6 +192,204 @@ - arg_meta: null kernel_name: torch::executor::select_copy_int_out +- op: abs.out + kernels: + - arg_meta: null + kernel_name: torch::executor::abs_out + +- op: amax.out + kernels: + - arg_meta: null + kernel_name: torch::executor::amax_out + +- op: amin.out + kernels: + - arg_meta: null + kernel_name: torch::executor::amin_out + +- op: arange.start_out + kernels: + - arg_meta: null + kernel_name: torch::executor::arange_start_out + +- op: argmax.out + kernels: + - arg_meta: null + kernel_name: torch::executor::argmax_out + +- op: argmin.out + kernels: + - arg_meta: null + kernel_name: torch::executor::argmin_out + +- op: ceil.out + kernels: + - arg_meta: null + kernel_name: torch::executor::ceil_out + +- op: clamp.out + cpp_no_default_args: ['min'] + kernels: + - arg_meta: null + kernel_name: torch::executor::clamp_out + +- op: constant_pad_nd.out + kernels: + - arg_meta: null + kernel_name: torch::executor::constant_pad_nd_out + +- op: copy.out + kernels: + - arg_meta: null + kernel_name: torch::executor::copy_out + +- op: elu.out + kernels: + - arg_meta: null + kernel_name: torch::executor::elu_out + +- op: flip.out + kernels: + - arg_meta: null + kernel_name: torch::executor::flip_out + +- op: floor.out + kernels: + - arg_meta: null + kernel_name: torch::executor::floor_out + +- op: fmod.Scalar_out + kernels: + - arg_meta: null + kernel_name: torch::executor::fmod_Scalar_out + +- op: gt.Scalar_out + kernels: + - arg_meta: null + kernel_name: torch::executor::gt_scalar_out + +- op: index.Tensor_out + kernels: + - arg_meta: null + kernel_name: torch::executor::index_Tensor_out + +- op: index_put.out + kernels: + - arg_meta: null + kernel_name: torch::executor::index_put_out + +- op: index_select.out + kernels: + - arg_meta: null + kernel_name: torch::executor::index_select_out + +- op: le.Scalar_out + kernels: + - arg_meta: null + kernel_name: torch::executor::le_scalar_out + +- op: leaky_relu.out + kernels: + - arg_meta: null + kernel_name: torch::executor::leaky_relu_out + +- op: log.out + kernels: + - arg_meta: null + kernel_name: torch::executor::log_out + +- op: log10.out + kernels: + - arg_meta: null + kernel_name: torch::executor::log10_out + +- op: log1p.out + kernels: + - arg_meta: null + kernel_name: torch::executor::log1p_out + +- op: log2.out + kernels: + - arg_meta: null + kernel_name: torch::executor::log2_out + +- op: _log_softmax.out + kernels: + - arg_meta: null + kernel_name: torch::executor::log_softmax_out + +- op: minimum.out + kernels: + - arg_meta: null + kernel_name: torch::executor::minimum_out + +- op: _native_batch_norm_legit_no_training.out + kernels: + - arg_meta: null + kernel_name: torch::executor::_native_batch_norm_legit_no_training_out + +- op: ne.Scalar_out + kernels: + - arg_meta: null + kernel_name: torch::executor::ne_scalar_out + +- op: pow.Tensor_Scalar_out + kernels: + - arg_meta: null + kernel_name: torch::executor::pow_Tensor_Scalar_out + +- op: relu.out + kernels: + - arg_meta: null + kernel_name: torch::executor::relu_out + +- op: round.out + kernels: + - arg_meta: null + kernel_name: torch::executor::round_out + +- op: slice_scatter.out + kernels: + - arg_meta: null + kernel_name: torch::executor::slice_scatter_out + +- op: sqrt.out + kernels: + - arg_meta: null + kernel_name: torch::executor::sqrt_out + +- op: squeeze_copy.dim_out + kernels: + - arg_meta: null + kernel_name: torch::executor::squeeze_copy_dim_out + +- op: tanh.out + kernels: + - arg_meta: null + kernel_name: torch::executor::tanh_out + +- op: trunc.out + kernels: + - arg_meta: null + kernel_name: torch::executor::trunc_out + +- op: upsample_bilinear2d.vec_out + kernels: + - arg_meta: null + kernel_name: torch::executor::upsample_bilinear2d_vec_out + +- op: upsample_nearest2d.vec_out + kernels: + - arg_meta: null + kernel_name: torch::executor::upsample_nearest2d_vec_out + +# aten::linear has no portable kernel. The generic fully_connected kernel has +# the same schema and takes any number of leading dimensions. +- op: linear.out + kernels: + - arg_meta: null + kernel_name: impl::generic::fully_connected_out + # custom ops - func: cadence::quantize_per_tensor.out(Tensor input, float scale, int zero_point, int quant_min, int quant_max, ScalarType dtype, *, Tensor(a!) out) -> Tensor(a!) variants: function @@ -324,7 +522,7 @@ - arg_meta: null kernel_name: impl::generic::quantized_relu_asym8u_asym8u_per_tensor_out -- func: cadence::quantized_max_pool2d.out(Tensor input, int[] kernel_size, int[] stride, int[] padding, int[] dilation, bool ceil_mode, *, Tensor(a!) out) -> Tensor(a!) +- func: cadence::quantized_max_pool2d_nchw.out(Tensor input, int[] kernel_size, int[] stride, int[] padding, int[] dilation, bool ceil_mode, *, Tensor(a!) out) -> Tensor(a!) kernels: - arg_meta: null kernel_name: impl::generic::quantized_max_pool2d_nchw_out @@ -379,6 +577,11 @@ - arg_meta: null kernel_name: impl::generic::im2row_per_tensor_out +- func: cadence::transposed_im2row.out(Tensor input, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, int[2] output_padding, Tensor in_zero_point, bool channel_last=False, *, Tensor(a!) out) -> Tensor(a!) + kernels: + - arg_meta: null + kernel_name: impl::generic::transposed_im2row_out + - func: cadence::quantized_conv2d_nchw.per_tensor_out(Tensor input, Tensor weight, Tensor bias, int[] stride, SymInt[] padding, int[] dilation, int groups, int input_zero_point, int weight_zero_point, float bias_scale, float out_scale, int out_zero_point, int out_multiplier, int out_shift, *, Tensor(a!) out) -> Tensor(a!) kernels: - arg_meta: null @@ -508,3 +711,36 @@ kernels: - arg_meta: null kernel_name: impl::generic::requantize_per_tensor_out + +- func: cadence::conv1d.out(Tensor input, Tensor weight, Tensor bias, int[1] stride, SymInt[1] padding, int[1] dilation, int groups, *, Tensor(a!) out) -> Tensor(a!) + kernels: + - arg_meta: null + kernel_name: impl::generic::conv1d_out + +- func: cadence::conv2d.out(Tensor input, Tensor weight, Tensor bias, int[2] stride, SymInt[2] padding, int[2] dilation, int groups, *, Tensor(a!) out) -> Tensor(a!) + kernels: + - arg_meta: null + kernel_name: impl::generic::conv2d_out + +# cadence::conv3d.out is intentionally not registered for CPU until a test +# covers it. + +- func: cadence::transposed_convolution.out(Tensor input, Tensor weight, Tensor bias, int[] stride, SymInt[] padding, int[] dilation, SymInt[] output_padding, int groups, bool channel_last=False, *, Tensor(a!) out) -> Tensor(a!) + kernels: + - arg_meta: null + kernel_name: impl::generic::transposed_convolution_out + +- func: cadence::avg_pool2d.out(Tensor input, int[2] kernel_size, int[2] stride=[], int[2] padding=[], bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, Tensor? in_zero_point=None, bool channel_last=False, *, Tensor(a!) out) -> Tensor(a!) + kernels: + - arg_meta: null + kernel_name: impl::generic::avg_pool2d_out + +- func: cadence::fully_connected.out(Tensor input, Tensor weight, Tensor? bias=None, *, Tensor(a!) out) -> Tensor(a!) + kernels: + - arg_meta: null + kernel_name: impl::generic::fully_connected_out + +- func: cadence::_softmax_f32_f32.out(Tensor self, int dim, bool? half_to_float=None, *, Tensor(a!) out) -> Tensor(a!) + kernels: + - arg_meta: null + kernel_name: impl::generic::_softmax_f32_f32_out diff --git a/backends/cadence/aot/functions_fusion_g3.yaml b/backends/cadence/aot/functions_fusion_g3.yaml index d41c19c0b01..32175f9572c 100644 --- a/backends/cadence/aot/functions_fusion_g3.yaml +++ b/backends/cadence/aot/functions_fusion_g3.yaml @@ -182,10 +182,10 @@ variants: function kernels: - arg_meta: null - kernel_name: impl::G3::native::quantize_per_tensor_out + kernel_name: impl::G3::quantize_per_tensor_out - func: cadence::dequantize_per_tensor.out(Tensor input, float scale, int zero_point, int quant_min, int quant_max, ScalarType dtype, *, Tensor(a!) out) -> Tensor(a!) variants: function kernels: - arg_meta: null - kernel_name: impl::G3::native::dequantize_per_tensor_out + kernel_name: impl::G3::dequantize_per_tensor_out diff --git a/backends/cadence/aot/functions_hifi.yaml b/backends/cadence/aot/functions_hifi.yaml index d1fd884f538..7aa8280d2eb 100644 --- a/backends/cadence/aot/functions_hifi.yaml +++ b/backends/cadence/aot/functions_hifi.yaml @@ -346,7 +346,7 @@ variants: function kernels: - arg_meta: null - kernel_name: impl::HiFi::quantize_per_tensor_asym16s_out + kernel_name: impl::HiFi::quantize_per_tensor_asym16u_out - func: cadence::quantize_per_tensor_asym32s.out(Tensor input, float scale, int zero_point, int quant_min, int quant_max, ScalarType dtype, *, Tensor(a!) out) -> Tensor(a!) variants: function @@ -388,7 +388,7 @@ variants: function kernels: - arg_meta: null - kernel_name: impl::HiFi::dequantize_per_tensor_asym16s_out + kernel_name: impl::HiFi::dequantize_per_tensor_asym32s_out - func: cadence::quantized_conv2d_nchw.out(Tensor input, Tensor weight, Tensor bias, int[] stride, SymInt[] padding, int[] dilation, int groups, int input_zero_point, Tensor? weight_zero_point, Tensor bias_scale, float out_scale, int out_zero_point, Tensor out_multiplier, Tensor out_shift, *, Tensor(a!) out) -> Tensor(a!) kernels: diff --git a/backends/cadence/aot/tests/test_functions_yaml.py b/backends/cadence/aot/tests/test_functions_yaml.py new file mode 100644 index 00000000000..7fd58ebd318 --- /dev/null +++ b/backends/cadence/aot/tests/test_functions_yaml.py @@ -0,0 +1,79 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-strict + +import glob +import os +import unittest + +import yaml + +# Kernel namespaces that each backend's operator library compiles. +BACKEND_NAMESPACES: dict[str, set[str]] = { + "functions.yaml": {"impl::generic", "torch::executor"}, + "functions_hifi.yaml": {"impl::HiFi", "impl::generic", "torch::executor"}, + "functions_vision.yaml": {"impl::vision", "torch::executor"}, + "functions_fusion_g3.yaml": {"impl::G3", "torch::executor"}, +} + + +def load_kernels() -> list[tuple[str, str, str]]: + """Returns (yaml name, op name, kernel name) for every functions*.yaml kernel.""" + aot_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + kernels = [] + for path in sorted(glob.glob(os.path.join(aot_dir, "functions*.yaml"))): + with open(path) as f: + for entry in yaml.safe_load(f): + op = entry["op"] if "op" in entry else entry["func"].partition("(")[0] + kernels.extend( + (os.path.basename(path), op, kernel["kernel_name"]) + for kernel in entry["kernels"] + ) + return kernels + + +class TestFunctionsYaml(unittest.TestCase): + def test_all_yamls_loaded(self) -> None: + self.assertEqual( + {yaml_name for yaml_name, _, _ in load_kernels()}, + set(BACKEND_NAMESPACES), + ) + + def test_kernel_names_omit_native(self) -> None: + # Codegen appends ::native to the kernel namespace itself. + self.assertEqual( + [ + (yaml_name, op, kernel_name) + for yaml_name, op, kernel_name in load_kernels() + if "::native::" in kernel_name + ], + [], + ) + + def test_kernel_namespace_belongs_to_backend(self) -> None: + self.assertEqual( + [ + (yaml_name, op, kernel_name) + for yaml_name, op, kernel_name in load_kernels() + if kernel_name.rpartition("::")[0] not in BACKEND_NAMESPACES[yaml_name] + ], + [], + ) + + def test_custom_op_kernel_name_matches_op(self) -> None: + mismatches = [] + for yaml_name, op, kernel_name in load_kernels(): + if not op.startswith("cadence::"): + continue + name, _, overload = op.removeprefix("cadence::").partition(".") + if kernel_name.rpartition("::")[2] not in { + f"{name}_out", + f"{name}_{overload}", + f"{name}_{overload}_out", + }: + mismatches.append((yaml_name, op, kernel_name)) + self.assertEqual(mismatches, []) diff --git a/backends/cadence/cadence_op_registry_test.cpp b/backends/cadence/cadence_op_registry_test.cpp new file mode 100644 index 00000000000..767855a776f --- /dev/null +++ b/backends/cadence/cadence_op_registry_test.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include + +#include +#include + +// Generated from cadence_ops_lib's selected_operators.yaml; see +// backends/cadence/CMakeLists.txt. +#include "cadence_ops_lib_selected_ops.h" + +namespace { + +using ::executorch::runtime::get_registered_kernels; +using ::executorch::runtime::registry_has_op_function; + +TEST(CadenceOpRegistryTest, EverySelectedOpIsRegistered) { + ::executorch::runtime::runtime_init(); + for (const char* op : kSelectedOps) { + EXPECT_TRUE(registry_has_op_function(op)) << op; + } + std::printf( + "Checked %d selected ops against %d registered kernels.\n", + static_cast(std::size(kSelectedOps)), + static_cast(get_registered_kernels().size())); +} + +} // namespace diff --git a/backends/cadence/generic/operators/CMakeLists.txt b/backends/cadence/generic/operators/CMakeLists.txt index dbf06e56bee..6e56581cef7 100644 --- a/backends/cadence/generic/operators/CMakeLists.txt +++ b/backends/cadence/generic/operators/CMakeLists.txt @@ -14,73 +14,11 @@ endif() include(${EXECUTORCH_ROOT}/tools/cmake/Utils.cmake) include(${EXECUTORCH_ROOT}/tools/cmake/Codegen.cmake) -# ATen compliant ops that are needed to run this model. -set(_aten_ops__srcs - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/activation_ops_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/copy_ops_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/broadcast_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/dtype_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/index_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/kernel_ops_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/matmul_ops_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/reduce_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/repeat_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/slice_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/pattern/unary_ufunc_realhbbf16_to_floathbf16.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_add.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_bmm.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_cat.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_clone.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_div.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_embedding.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_exp.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_full.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_hardtanh.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_max_pool2d_with_indices.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_mean.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_mul.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_native_layer_norm.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_neg.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_permute_copy.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_rsqrt.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_sigmoid.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_slice_copy.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_softmax.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_split_with_sizes_copy.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_sub.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_to_copy.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_where.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_expand_copy.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_gelu.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_empty.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_transpose_copy.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_eq.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_logical_not.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_any.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_native_group_norm.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_sum.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_select_copy.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_split_with_sizes_copy.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/op_view_copy.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/delinearize_index.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/dtype_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/normalization_ops_util.cpp" - "${EXECUTORCH_ROOT}/kernels/portable/cpu/util/select_copy_util.cpp" -) -add_library(aten_ops_cadence ${_aten_ops__srcs}) -target_link_libraries(aten_ops_cadence PUBLIC executorch) -target_link_libraries(aten_ops_cadence PRIVATE cadence_kernels) - # Let files say "include ". set(_common_include_directories ${EXECUTORCH_ROOT}/.. ${EXECUTORCH_ROOT}/runtime/core/portable_type/c10 ) -target_include_directories( - aten_ops_cadence PUBLIC ${ROOT_DIR}/.. ${CMAKE_BINARY_DIR} - ${_common_include_directories} -) - # Custom ops that are needed to run the test model. file(GLOB custom_ops_srcs "*.cpp") add_library(custom_ops ${custom_ops_srcs}) @@ -105,6 +43,8 @@ generate_bindings_for_kernels( ) message("Generated cadence x86 files ${gen_command_sources}") +# The ATen ops in functions.yaml use the portable kernels. Registration comes +# only from functions.yaml, so linking the whole library adds no other ops. gen_operators_lib( - LIB_NAME "cadence_ops_lib" KERNEL_LIBS custom_ops DEPS aten_ops_cadence + LIB_NAME "cadence_ops_lib" KERNEL_LIBS custom_ops portable_kernels ) diff --git a/backends/cadence/generic/operators/tests/CMakeLists.txt b/backends/cadence/generic/operators/tests/CMakeLists.txt index ea59f48a0f6..1b7a2cdc347 100644 --- a/backends/cadence/generic/operators/tests/CMakeLists.txt +++ b/backends/cadence/generic/operators/tests/CMakeLists.txt @@ -84,17 +84,10 @@ target_include_directories( ) # Direct-call: link the libs that define the kernels under test. custom_ops has -# the cadence-specific ops; aten_ops_cadence has the aten-compliant ones; -# cadence_kernels is the shared kernel layer; executorch provides the platform -# layer the tests' runtime_init() needs. No cadence_ops_lib registry is needed -# for direct-call tests. +# the cadence-specific ops; cadence_kernels is the shared kernel layer; +# executorch provides the platform layer the tests' runtime_init() needs. No +# cadence_ops_lib registry is needed for direct-call tests. target_link_libraries( - cadence_generic_op_tests - PRIVATE gtest - gtest_main - gmock - executorch - custom_ops - aten_ops_cadence - cadence_kernels + cadence_generic_op_tests PRIVATE gtest gtest_main gmock executorch custom_ops + cadence_kernels ) diff --git a/backends/cadence/utils/gen_selected_ops_header.py b/backends/cadence/utils/gen_selected_ops_header.py new file mode 100644 index 00000000000..9dd15c35c0a --- /dev/null +++ b/backends/cadence/utils/gen_selected_ops_header.py @@ -0,0 +1,38 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Write a C++ header that lists the operator names in a selected_operators.yaml +produced by codegen/tools/gen_oplist.py, as `kSelectedOps`.""" + +import argparse +import os + +import yaml + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--oplist-yaml", required=True) + parser.add_argument("--output-path", required=True) + args = parser.parse_args() + + with open(args.oplist_yaml) as f: + ops = sorted(yaml.safe_load(f)["operators"]) + assert ops, f"{args.oplist_yaml} selects no operators" + + entries = "".join(f' "{op}",\n' for op in ops) + with open(args.output_path, "w") as f: + f.write( + f"// Generated by {os.path.basename(__file__)} from " + f"{os.path.basename(args.oplist_yaml)}. Do not edit.\n" + "#pragma once\n" + "\n" + f"constexpr const char* kSelectedOps[] = {{\n{entries}}};\n" + ) + + +if __name__ == "__main__": + main()