|
| 1 | +# Copyright 2025 NXP |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import pytest |
| 10 | +import torch |
| 11 | + |
| 12 | +from executorch.backends.nxp.backend.edge_program_converter import ( |
| 13 | + EdgeProgramToIRConverter, |
| 14 | +) |
| 15 | +from executorch.backends.nxp.tests.executorch_pipeline import to_quantized_edge_program |
| 16 | +from executorch.backends.nxp.tests.executors import ( |
| 17 | + convert_run_compare, |
| 18 | + ToNCHWPreprocess, |
| 19 | + ToNHWCPreprocess, |
| 20 | +) |
| 21 | +from executorch.backends.nxp.tests.models import ConvWithSigmoid |
| 22 | +from torch import nn |
| 23 | +from torch.export import ExportedProgram |
| 24 | + |
| 25 | + |
| 26 | +@pytest.fixture(autouse=True) |
| 27 | +def reseed_model_per_test_run(): |
| 28 | + torch.manual_seed(23) |
| 29 | + np.random.seed(23) |
| 30 | + |
| 31 | + |
| 32 | +def test_conv_sigmoid(mocker, input_shape: tuple[int] = (1, 3, 112, 112)): |
| 33 | + model = ConvWithSigmoid(conv_in_channels=input_shape[1]) |
| 34 | + |
| 35 | + converter_spy = mocker.spy(EdgeProgramToIRConverter, "convert_program") |
| 36 | + |
| 37 | + to_quantized_edge_program(model, input_shape).exported_program() |
| 38 | + |
| 39 | + tflite_flatbuffers_model, io_formats = converter_spy.spy_return |
| 40 | + exported_program: ExportedProgram = converter_spy.call_args.args[1] |
| 41 | + |
| 42 | + input_data = (np.random.random(input_shape) * 50).astype(np.int8) |
| 43 | + convert_run_compare( |
| 44 | + exported_program, |
| 45 | + tfl_model=tflite_flatbuffers_model, |
| 46 | + tflite_input_preprocess=ToNHWCPreprocess(), |
| 47 | + tflite_output_preprocess=ToNCHWPreprocess(), |
| 48 | + input_data=input_data, |
| 49 | + atol=1.0, |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +@pytest.mark.parametrize( |
| 54 | + "input_shape", |
| 55 | + [ |
| 56 | + pytest.param((10,), id="Scalar"), |
| 57 | + pytest.param((10, 25), id="1D"), |
| 58 | + pytest.param((10, 25, 25), id="2D"), |
| 59 | + pytest.param((10, 3, 25, 25), id="3D"), |
| 60 | + pytest.param((10, 3, 25, 25, 25), id="4D"), |
| 61 | + ], |
| 62 | +) |
| 63 | +def test_sigmoid_only(mocker, input_shape): |
| 64 | + model = nn.Sigmoid() |
| 65 | + |
| 66 | + converter_spy = mocker.spy(EdgeProgramToIRConverter, "convert_program") |
| 67 | + |
| 68 | + to_quantized_edge_program(model, input_shape).exported_program() |
| 69 | + |
| 70 | + tflite_flatbuffers_model, io_formats = converter_spy.spy_return |
| 71 | + exported_program: ExportedProgram = converter_spy.call_args.args[1] |
| 72 | + |
| 73 | + input_data = (np.random.random(input_shape) * 50).astype(np.int8) |
| 74 | + convert_run_compare( |
| 75 | + exported_program, tfl_model=tflite_flatbuffers_model, input_data=input_data |
| 76 | + ) |
0 commit comments