diff --git a/backends/nxp/tests/dataset_creators/base_dataset_creator.py b/backends/nxp/tests/dataset_creators/base_dataset_creator.py index 4255b0be3f7..0d276a7f2e6 100644 --- a/backends/nxp/tests/dataset_creators/base_dataset_creator.py +++ b/backends/nxp/tests/dataset_creators/base_dataset_creator.py @@ -85,7 +85,7 @@ def _copy(src: str, dst: str, spec: ModelInputSpec) -> None: mkdir(dst_example_dir_path) for spec_idx, spec in enumerate(input_spec): - file_name = f"{str(spec_idx).zfill(2)}.bin" + file_name = f"{str(spec_idx).zfill(4)}.bin" src = os.path.join(src_example_dir_path, file_name) dst = os.path.join(dst_example_dir_path, file_name) diff --git a/backends/nxp/tests/dataset_creators/real_dataset_creators.py b/backends/nxp/tests/dataset_creators/real_dataset_creators.py index 60ccd57178d..2814c5248a4 100644 --- a/backends/nxp/tests/dataset_creators/real_dataset_creators.py +++ b/backends/nxp/tests/dataset_creators/real_dataset_creators.py @@ -90,5 +90,5 @@ def _write_examples( example_tensors = example if isinstance(example, list) else [example] for spec_idx, tensor in enumerate(example_tensors): - bin_file_name = f"{dataset_dir_path}/example_{label}_{cl}_{i}_i{str(spec_idx).zfill(2)}.bin" + bin_file_name = f"{dataset_dir_path}/example_{label}_{cl}_{i}_i{str(spec_idx).zfill(4)}.bin" tensor.numpy().tofile(bin_file_name) diff --git a/backends/nxp/tests/dataset_creators/synthetic_creators.py b/backends/nxp/tests/dataset_creators/synthetic_creators.py index 95eb83a7817..e2901827517 100644 --- a/backends/nxp/tests/dataset_creators/synthetic_creators.py +++ b/backends/nxp/tests/dataset_creators/synthetic_creators.py @@ -56,7 +56,7 @@ def create_calibration_dataset( torch_type_to_numpy_type(spec.dtype) ) file_name = ( - f"{str(spec_idx).zfill(2)}.bin" + f"{str(spec_idx).zfill(4)}.bin" if len(input_spec) > 1 else f"{str(idx).zfill(4)}.bin" ) diff --git a/backends/nxp/tests/generic_tests/test_debug_results.py b/backends/nxp/tests/generic_tests/test_debug_results.py index 4d4c1e13f53..8d86c751c8f 100644 --- a/backends/nxp/tests/generic_tests/test_debug_results.py +++ b/backends/nxp/tests/generic_tests/test_debug_results.py @@ -3,23 +3,50 @@ # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. +import datetime +import hashlib import logging import os +import pathlib import numpy as np # noinspection PyUnusedImports import pytest import torch +import yaml +from executorch.backends.nxp.tests.comparators.all_close_comparator import ( + AllCloseOutputComparator, +) +from executorch.backends.nxp.tests.dataset_creators.synthetic_creators import ( + RandomDatasetCreator, +) from executorch.backends.nxp.tests.executorch_pipeline import ModelInputSpec from executorch.backends.nxp.tests.graph_verifier import BaseGraphVerifier from executorch.backends.nxp.tests.nsys_testing import ( - get_test_name, + get_test_dir, lower_run_compare, OUTPUTS_DIR, ) -from executorch.backends.nxp.tests.simple_models import AddTensorModule, AvgPool2dModule +from executorch.backends.nxp.tests.simple_models import ( + AddSubTensorModule, + AddTensorModule, + AvgPool2dModule, + SplitWithSections, +) + +SUMMARY_YAML_KEYS = { + "date_time", + "eiq_neutron_sdk_version", + "eiq_nsys_version", + "git_branch", + "git_commit", + "test_node_id", +} +RESULTS_CPU_DIR_NAME = "results_cpu" +RESULTS_NPU_DIR_NAME = "results_npu" +DIFF_CPU_NPU_DIR_NAME = "diff_cpu_npu_results" @pytest.fixture(autouse=True) @@ -28,139 +55,350 @@ def reseed_model_per_test_run(): np.random.seed(23) -def test_nsys_test_debug_results__single_input(caplog, request): - # Set log level to DEBUG to create debug results - caplog.set_level(logging.DEBUG) +class TestNsysDebugResults: + @staticmethod + def _assert_artifacts_presence( + test_dir: pathlib.Path, + num_examples: int, + num_inputs: int = 1, + num_outputs: int = 1, + ref_dataset: bool = False, + quant_dataset: bool = False, + ): + """Assert that exactly the expected debug artifacts created by `lower_run_compare` are present. - input_shape = (2, 4, 6, 7) - model = AvgPool2dModule(False, 0) + Fails if any expected artifact is missing or if any unexpected file is present in `test_dir`. - graph_verifier = BaseGraphVerifier(1, []) + :param test_dir: Test artifacts directory, as returned by `get_test_dir`. + :param num_examples: Number of examples generated by the dataset creator passed to `lower_run_compare`. + :param num_inputs: Number of model inputs. Multi-input examples are stored in per-example subdirectories. + :param num_outputs: Number of model outputs. + :param ref_dataset: True if a custom `reference_input_spec` was used, so `ref_dataset` is created. + :param quant_dataset: True if run with `remove_quant_io_ops`, so quantized datasets are created. + """ - # use different reference model dim order so transposed dataset is created - ref_input_spec = ModelInputSpec(input_shape, dim_order=torch.channels_last) - lower_run_compare( - model, - input_shape, - graph_verifier, - request, - remove_quant_io_ops=True, - reference_input_spec=[ref_input_spec], - ) + # Return the given files plus their .txt variants, e.g. [0000.bin] -> [0000.bin, 0000.txt]. + def _with_txt(files: list[str]) -> list[str]: + return files + [f"{os.path.splitext(f)[0]}.txt" for f in files] - test_name = get_test_name(request) - # Running by CI scripts adds prefix to the name - assert "test_nsys_test_debug_results__single_input" in test_name - assert os.path.isdir(os.path.join(OUTPUTS_DIR, test_name, "diff_cpu_npu_results")) - assert os.path.isfile(os.path.join(OUTPUTS_DIR, test_name, "summary.yaml")) - - # Check file contains key symbols - with open(os.path.join(OUTPUTS_DIR, test_name, "summary.yaml")) as f: - content = f.read() - keys = [ - "date_time", - "eiq_neutron_sdk_version", - "eiq_nsys_version", - "git_branch", - "git_commit", - "test_name", - ] - assert all(key in content for key in keys) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "tag1_neutron.et.tflite") - ) - assert os.path.isfile(os.path.join(OUTPUTS_DIR, test_name, "tag1_pure.et.tflite")) + # Handle artifacts based on number of inputs + if num_inputs == 1: + samples_input = [f"{idx:04d}.bin" for idx in range(num_examples)] + input_files = samples_input + else: + samples_input = [f"{idx:04d}" for idx in range(num_examples)] + input_files = [ + os.path.join(sample, f"{input_idx:04d}.bin") + for sample in samples_input + for input_idx in range(num_inputs) + ] - # Check text tensor variants - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "model_dataset", "calibration", "0000.txt") - ) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "model_dataset_quant", "0000.txt") - ) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "ref_dataset", "calibration", "0000.bin") - ) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "ref_dataset_quant", "0000.bin") - ) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "results_cpu", "0000.bin", "0000.txt") - ) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "results_npu", "0000.bin", "0000.txt") - ) - assert os.path.isfile( - os.path.join( - OUTPUTS_DIR, test_name, "diff_cpu_npu_results", "0000.bin", "0000.txt" + output_files = [f"{output_idx:04d}.bin" for output_idx in range(num_outputs)] + + expected_files = [ + "summary.yaml", + "tag1_neutron.et.tflite", + "tag1_pure.et.tflite", + ] + # model_delegated.pte, model_delegated.json, model_non_quantized.pte, ... + expected_files += [ + f"{program}.{ext}" + for program in [ + "model_delegated", + "model_non_delegated", + "model_non_quantized", + ] + for ext in ["pte", "json"] + ] + # results_cpu/results.txt, results_npu/trace.etdump, ... + # The runner writes results.txt (top-1 class) only for single output models run in + # `--dataset` mode, which is used for single input models only. + result_summary_files = ["trace.etdump"] + if num_inputs == 1 and num_outputs == 1: + result_summary_files.append("results.txt") + expected_files += [ + os.path.join(results_dir_name, file) + for results_dir_name in [RESULTS_CPU_DIR_NAME, RESULTS_NPU_DIR_NAME] + for file in result_summary_files + ] + # results_cpu/0000.bin/0000.bin, results_npu/0000.bin/0000.txt, ... + expected_files += [ + os.path.join(results_dir_name, sample, file) + for results_dir_name in [ + RESULTS_CPU_DIR_NAME, + RESULTS_NPU_DIR_NAME, + DIFF_CPU_NPU_DIR_NAME, + ] + for sample in samples_input + for file in _with_txt(output_files) + ] + # Datasets as (dir, files). The .txt variants are created only for the datasets used to run + # the models. Quantized runs are tested on the `_quant` datasets instead of the `test` ones. + test_files = input_files if quant_dataset else _with_txt(input_files) + datasets = [ + (os.path.join("model_dataset", "calibration"), _with_txt(input_files)), + (os.path.join("model_dataset", "test"), test_files), + ] + if ref_dataset: + datasets += [ + (os.path.join("ref_dataset", "calibration"), _with_txt(input_files)), + (os.path.join("ref_dataset", "test"), test_files), + ] + if quant_dataset: + datasets += [ + ("model_dataset_quant", _with_txt(input_files)), + ("ref_dataset_quant", _with_txt(input_files)), + ] + # model_dataset/calibration/0000.bin, model_dataset/calibration/0000.txt, ... + expected_files += [ + os.path.join(dataset_dir, file) + for dataset_dir, files in datasets + for file in files + ] + + expected_files += ["all_close_stats.csv"] + + expected_files = set(expected_files) + actual_files = { + os.path.relpath(os.path.join(root, file), test_dir) + for root, _, files in os.walk(test_dir) + for file in files + } + + missing_files = sorted(expected_files - actual_files) + extra_files = sorted(actual_files - expected_files) + assert not missing_files, f"Missing artifacts in '{test_dir}': {missing_files}" + assert not extra_files, f"Unexpected artifacts in '{test_dir}': {extra_files}" + + assert os.path.isfile(f"{test_dir}.zip") + + @staticmethod + def _assert_test_dir_name(test_dir: pathlib.Path, request: pytest.FixtureRequest): + """Assert that the test dir is named "__<8-char-hash of the pytest node ID>". + + :param test_dir: Test artifacts directory, as returned by `get_test_dir`. + :param request: PyTest fixture request of the current test. + """ + assert test_dir.parent == OUTPUTS_DIR + # Test file names may contain "__" as well, the hash is the last part. + test_file_name, digest = test_dir.name.rsplit("__", 1) + assert test_file_name == pathlib.Path(__file__).stem + assert digest == hashlib.sha256(request.node.nodeid.encode()).hexdigest()[:8] + + @staticmethod + def _assert_debug_summary_content( + test_dir: pathlib.Path, request: pytest.FixtureRequest + ): + """Assert that `summary.yaml` has the expected content and `test_name_mapping.yaml` maps the test dir. + + :param test_dir: Test artifacts directory. + :param request: PyTest fixture request of the test which produced the artifacts. + """ + with open(os.path.join(test_dir, "summary.yaml")) as f: + summary = yaml.safe_load(f) + + # Exactly the expected keys, nothing missing or extra + assert set(summary.keys()) == SUMMARY_YAML_KEYS + + # Check information about the test is stored correctly. + assert summary["test_node_id"] == request.node.nodeid + + # Check date is set and in correct format + date_time = summary["date_time"] + if isinstance(date_time, str): + date_time = datetime.datetime.fromisoformat(date_time) + assert isinstance(date_time, datetime.datetime) + + # Commit is always set, branch might not because of possible DETACHED state. + assert isinstance(summary["git_branch"], str) + assert isinstance(summary["git_commit"], str) and summary["git_commit"] + assert ( + isinstance(summary["eiq_neutron_sdk_version"], str) + and summary["eiq_neutron_sdk_version"] + ) + assert ( + isinstance(summary["eiq_nsys_version"], str) and summary["eiq_nsys_version"] ) + + # Check correctness of dir name mapping + mapping_path = os.path.join(OUTPUTS_DIR, "test_name_mapping.yaml") + assert os.path.isfile(mapping_path) + with open(mapping_path) as f: + test_name_mapping = yaml.safe_load(f) + + assert test_name_mapping[test_dir.name] == request.node.nodeid + + @pytest.mark.parametrize( + "ref_dim_order, remove_quant_io_ops", + [ + pytest.param( + torch.contiguous_format, + False, + id="same dim order, quant io ops kept", + ), + pytest.param( + torch.contiguous_format, + True, + id="same dim order, quant io ops removed", + ), + pytest.param( + torch.channels_last, + False, + id="channels last ref, quant io ops kept", + ), + pytest.param( + torch.channels_last, + True, + id="channels last ref, quant io ops removed", + ), + ], ) - assert os.path.isfile(os.path.join(OUTPUTS_DIR, f"{test_name}.zip")) + def test_debug_results__one_input_output( + self, caplog, request, ref_dim_order, remove_quant_io_ops + ): + # Set log level to DEBUG to create debug results + caplog.set_level(logging.DEBUG) + input_shape = (2, 4, 6, 7) + model = AvgPool2dModule(False) -class TestNsysDebugResults: - def test_nsys_test_debug_results__multiple_input(self, caplog, request): + graph_verifier = BaseGraphVerifier(1, []) + + num_examples = 3 + dataset_creator = RandomDatasetCreator(num_examples=num_examples) + + ref_dataset = ref_dim_order != torch.contiguous_format + reference_input_spec = None + if ref_dataset: + reference_input_spec = [ + ModelInputSpec(input_shape, dim_order=ref_dim_order) + ] + + lower_run_compare( + model, + input_shape, + graph_verifier, + request, + dataset_creator=dataset_creator, + remove_quant_io_ops=remove_quant_io_ops, + reference_input_spec=reference_input_spec, + ) + + # Assert test dir name correctness + test_dir = get_test_dir(request) + self._assert_test_dir_name(test_dir, request) + + # Assert artifacts correctness + self._assert_artifacts_presence( + test_dir, + num_examples, + ref_dataset=ref_dataset, + quant_dataset=remove_quant_io_ops, + ) + + # Assert debug summary dumps correctness + self._assert_debug_summary_content(test_dir, request) + + def test_debug_results__multiple_input_one_output(self, caplog, request): # Set log level to DEBUG to create debug results caplog.set_level(logging.DEBUG) input_shape = (1, 4, 7) x_input_spec = ModelInputSpec(input_shape) model = AddTensorModule() + num_inputs = 2 graph_verifier = BaseGraphVerifier(1, []) + num_examples = 3 + dataset_creator = RandomDatasetCreator(num_examples=num_examples) + lower_run_compare( model, - [x_input_spec, x_input_spec], + [x_input_spec] * num_inputs, graph_verifier, request, + dataset_creator=dataset_creator, ) - test_name = get_test_name(request) - # Running by CI scripts adds prefix to the name - assert ( - "TestNsysDebugResults__test_nsys_test_debug_results__multiple_input" - in test_name - ) - assert os.path.isdir( - os.path.join(OUTPUTS_DIR, test_name, "diff_cpu_npu_results") - ) - assert os.path.isfile(os.path.join(OUTPUTS_DIR, test_name, "summary.yaml")) - - # Check file contains key symbols - with open(os.path.join(OUTPUTS_DIR, test_name, "summary.yaml")) as f: - content = f.read() - keys = [ - "date_time", - "eiq_neutron_sdk_version", - "eiq_nsys_version", - "git_branch", - "git_commit", - "test_name", - ] - assert all(key in content for key in keys) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "tag1_neutron.et.tflite") - ) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "tag1_pure.et.tflite") - ) + # Assert test dir name correctness + test_dir = get_test_dir(request) + self._assert_test_dir_name(test_dir, request) - # Check text tensor variants - assert os.path.isfile( - os.path.join( - OUTPUTS_DIR, test_name, "model_dataset", "calibration", "0000", "00.txt" - ) - ) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "results_cpu", "0000", "0000.txt") + # Assert artifacts correctness + self._assert_artifacts_presence(test_dir, num_examples, num_inputs=num_inputs) + + # Assert debug summary dumps correctness + self._assert_debug_summary_content(test_dir, request) + + def test_debug_results__one_input_multiple_output(self, caplog, request): + # Set log level to DEBUG to create debug results + caplog.set_level(logging.DEBUG) + + input_shape = (8, 24) + sections = [16, 8] + model = SplitWithSections(sections, dim=1) + num_outputs = len(sections) + + graph_verifier = BaseGraphVerifier(1, []) + + num_examples = 3 + dataset_creator = RandomDatasetCreator(num_examples=num_examples) + + lower_run_compare( + model, + input_shape, + graph_verifier, + request, + dataset_creator=dataset_creator, ) - assert os.path.isfile( - os.path.join(OUTPUTS_DIR, test_name, "results_npu", "0000", "0000.txt") + + # Assert test dir name correctness + test_dir = get_test_dir(request) + self._assert_test_dir_name(test_dir, request) + + # Assert artifacts correctness + self._assert_artifacts_presence(test_dir, num_examples, num_outputs=num_outputs) + + # Assert debug summary dumps correctness + self._assert_debug_summary_content(test_dir, request) + + def test_debug_results__multiple_input_multiple_output(self, caplog, request): + # Set log level to DEBUG to create debug results + caplog.set_level(logging.DEBUG) + + input_shape = (1, 4, 7) + x_input_spec = ModelInputSpec(input_shape) + model = AddSubTensorModule() + num_inputs = 2 + num_outputs = 2 + + graph_verifier = BaseGraphVerifier(1, []) + + num_examples = 3 + dataset_creator = RandomDatasetCreator(num_examples=num_examples) + + # For some reason, the `atol` is a bit higher, however that is not what + # the test should check. + comparator = AllCloseOutputComparator(atol=0.01) + + lower_run_compare( + model, + [x_input_spec] * num_inputs, + graph_verifier, + request, + dataset_creator=dataset_creator, + output_comparator=comparator, ) - assert os.path.isfile( - os.path.join( - OUTPUTS_DIR, test_name, "diff_cpu_npu_results", "0000", "0000.txt" - ) + + # Assert test dir name correctness + test_dir = get_test_dir(request) + self._assert_test_dir_name(test_dir, request) + + # Assert artifacts correctness + self._assert_artifacts_presence( + test_dir, num_examples, num_inputs=num_inputs, num_outputs=num_outputs ) - assert os.path.isfile(os.path.join(OUTPUTS_DIR, f"{test_name}.zip")) + + # Assert debug summary dumps correctness + self._assert_debug_summary_content(test_dir, request) diff --git a/backends/nxp/tests/generic_tests/test_profiling.py b/backends/nxp/tests/generic_tests/test_profiling.py index 99ae74135d1..53082e8fbfd 100644 --- a/backends/nxp/tests/generic_tests/test_profiling.py +++ b/backends/nxp/tests/generic_tests/test_profiling.py @@ -18,11 +18,7 @@ NumericalStatsOutputComparator, ) from executorch.backends.nxp.tests.graph_verifier import BaseGraphVerifier -from executorch.backends.nxp.tests.nsys_testing import ( - get_test_name, - lower_run_compare, - OUTPUTS_DIR, -) +from executorch.backends.nxp.tests.nsys_testing import get_test_dir, lower_run_compare from executorch.backends.nxp.tests.profiling_utils import ( get_neutron_compiler_version, @@ -67,7 +63,7 @@ def extract_map_from_logs(caplog): return None -def inspector_check(test_name: str) -> None: +def inspector_check(test_dir: str) -> None: """ Validate ExecuTorch Inspector profiling output. @@ -111,7 +107,7 @@ def parse_delegate_metadata( metadata_list.append("Invalid metadata size") return metadata_list - npu_results_path = os.path.join(OUTPUTS_DIR, test_name, "results_npu") + npu_results_path = os.path.join(test_dir, "results_npu") etrecord_path = os.path.join(npu_results_path, "etrecord.bin") etdump_path = os.path.join(npu_results_path, "trace.etdump") @@ -293,7 +289,7 @@ def test__cifar(self, caplog, request): 10: (21,), # Slice 11: (), # Neutron Dump } - inspector_check(get_test_name(request)) + inspector_check(get_test_dir(request)) def test__cifar_batch_2(self, caplog, request): caplog.set_level(logging.INFO) @@ -464,7 +460,7 @@ def test__resnet8_batch_2(self, caplog, request): 27: (45,), # Slice (FullyConnected) 28: (), # Neutron Dump } - inspector_check(get_test_name(request)) + inspector_check(get_test_dir(request)) def test__ds_cnn(self, caplog, request): # Depthwise Separable CNN used for keyword spotting in MLCommons Tiny. diff --git a/backends/nxp/tests/generic_tests/test_quantized_input_data.py b/backends/nxp/tests/generic_tests/test_quantized_input_data.py index 7c5dbc7c3f7..335cad162de 100644 --- a/backends/nxp/tests/generic_tests/test_quantized_input_data.py +++ b/backends/nxp/tests/generic_tests/test_quantized_input_data.py @@ -11,7 +11,6 @@ from executorch.backends.nxp.tests.graph_verifier import DetailedGraphVerifier from executorch.backends.nxp.tests.nsys_testing import ( lower_run_compare, - OUTPUTS_DIR, ReferenceRunner, ) from executorch.backends.nxp.tests.simple_models import AvgPool2dModule, MulTensorModule @@ -33,8 +32,8 @@ def test__single_quantized_inputs(mocker, request): remove_quant_io_ops=True, ) - test_name = nsys_testing.get_test_name(request) - assert (OUTPUTS_DIR / test_name / "model_dataset_quant" / "0000.bin").exists() + test_dir = nsys_testing.get_test_dir(request) + assert (test_dir / "model_dataset_quant" / "0000.bin").exists() # Check outputs are in quantized int8 format output_tensor_spec = output_tensor_spec_spy.spy_return @@ -58,8 +57,8 @@ def test__single_quantized_inputs_edge_python_reference(mocker, request): remove_quant_io_ops=True, ) - test_name = nsys_testing.get_test_name(request) - assert (OUTPUTS_DIR / test_name / "model_dataset_quant" / "0000.bin").exists() + test_dir = nsys_testing.get_test_dir(request) + assert (test_dir / "model_dataset_quant" / "0000.bin").exists() # Check outputs are in quantized int8 format output_tensor_spec = output_tensor_spec_spy.spy_return @@ -82,10 +81,8 @@ def test__multiple_quantized_inputs(mocker, request): remove_quant_io_ops=True, ) - test_name = nsys_testing.get_test_name(request) - assert ( - OUTPUTS_DIR / test_name / "model_dataset_quant" / "0000" / "00.bin" - ).exists() + test_dir = nsys_testing.get_test_dir(request) + assert (test_dir / "model_dataset_quant" / "0000" / "0000.bin").exists() # Check outputs are in quantized int8 format output_tensor_spec = output_tensor_spec_spy.spy_return @@ -109,10 +106,8 @@ def test__multiple_quantized_inputs_edge_python_reference(mocker, request): remove_quant_io_ops=True, ) - test_name = nsys_testing.get_test_name(request) - assert ( - OUTPUTS_DIR / test_name / "model_dataset_quant" / "0000" / "00.bin" - ).exists() + test_dir = nsys_testing.get_test_dir(request) + assert (test_dir / "model_dataset_quant" / "0000" / "0000.bin").exists() # Check outputs are in quantized int8 format output_tensor_spec = output_tensor_spec_spy.spy_return diff --git a/backends/nxp/tests/nsys_testing.py b/backends/nxp/tests/nsys_testing.py index 99d0dc1a5df..a08048d191a 100644 --- a/backends/nxp/tests/nsys_testing.py +++ b/backends/nxp/tests/nsys_testing.py @@ -5,9 +5,10 @@ import datetime import functools +import hashlib import logging import os.path -import re +import pathlib import shutil import subprocess from copy import deepcopy @@ -60,6 +61,7 @@ from executorch.devtools.visualization.visualization_utils import ( visualize_with_clusters, ) +from filelock import FileLock from pytest import FixtureRequest from pytest_mock import MockerFixture from torch.export import ExportedProgram @@ -108,7 +110,6 @@ def _get_dataset_cli_args(input_spec: list[ModelInputSpec], testing_dataset_dir) def _run_delegated_executorch_program( model, test_dir, - test_name, calibration_dataset_dir, testing_dataset_dir, input_spec, @@ -134,7 +135,7 @@ def wrapper(*args, **kwargs): result = method(*args, **kwargs) visualize_with_clusters( result.tagged_exported_program, - os.path.join(test_dir, test_name + "_partitioned.json"), + os.path.join(test_dir, "model_partitioned.json"), False, ) return result @@ -173,7 +174,7 @@ def wrapper(*args, **kwargs): ), "No delegated parts found in program delegated to NPU!" dlg_model_verifier.verify_graph(exported_program.graph) - save_pte_program(delegated_program, test_name + "_delegated", test_dir) + save_pte_program(delegated_program, "model_delegated", test_dir) # Generate ETRecord if profiling flag is set. if use_profiling: @@ -199,7 +200,7 @@ def wrapper(*args, **kwargs): # Run nxp_executor_runner with program delegated to NPU delegated_model_path = os.path.abspath( - os.path.join(test_dir, f"{test_name}_delegated.pte") + os.path.join(test_dir, "model_delegated.pte") ) delegated_cmd = f"{NEUTRON_TEST_PATH} --model {delegated_model_path} {dataset_cli} {dataset_or_inputs} \ @@ -212,7 +213,6 @@ def wrapper(*args, **kwargs): def _run_non_delegated_executorch_program( model, test_dir, - test_name, calibration_dataset_dir, testing_dataset_dir, input_spec, @@ -241,11 +241,11 @@ def _run_non_delegated_executorch_program( non_delegated_program.exported_program().graph, [ExecutorchDelegateCall] ), "Delegated parts found in program executed on CPU!" - save_pte_program(non_delegated_program, test_name + "_non_delegated", test_dir) + save_pte_program(non_delegated_program, "model_non_delegated", test_dir) # Run program via nxp_executor_runner on CPU non_delegated_model_path = os.path.abspath( - os.path.join(test_dir, f"{test_name}_non_delegated.pte") + os.path.join(test_dir, "model_non_delegated.pte") ) non_delegated_cmd = f"{NEUTRON_TEST_PATH} --model {non_delegated_model_path} {dataset_cli} {dataset_or_inputs} \ @@ -258,7 +258,6 @@ def _run_non_delegated_executorch_program( def _save_non_quantized_fp32_executorch_program( model, test_dir, - test_name, input_spec, ) -> ExportedProgram: non_quantized_program = to_edge_program(model, input_spec).to_executorch() @@ -267,7 +266,7 @@ def _save_non_quantized_fp32_executorch_program( non_quantized_program.exported_program().graph, [ExecutorchDelegateCall] ), "Delegated parts found in non-quantized FP32 program!" - save_pte_program(non_quantized_program, test_name + "_non_quantized", test_dir) + save_pte_program(non_quantized_program, "model_non_quantized", test_dir) return non_quantized_program.exported_program() @@ -310,7 +309,6 @@ def _run_python_program( def _run_cortex_m_program( model: torch.nn.Module | GraphModule, test_dir, - test_name, calibration_dataset_dir, testing_dataset_dir, input_spec: list[ModelInputSpec], @@ -359,9 +357,7 @@ def _run_cortex_m_program( cpu_results_dir, npu_results_dir, ) - save_pte_program( - cortex_m_delegated_program, test_name + "_cortex_m_delegated", test_dir - ) + save_pte_program(cortex_m_delegated_program, "model_cortex_m_delegated", test_dir) def assert_cortex_m(): @@ -470,11 +466,7 @@ def lower_run_compare( reference_model = deepcopy(model) model_to_export_fp32 = deepcopy(model) - test_name = get_test_name(request) - test_dir = os.path.join(OUTPUTS_DIR, test_name) - - shutil.rmtree(test_dir, ignore_errors=True) - mkdir(test_dir) + test_dir = make_test_dir(request) model_input_spec = to_model_input_spec(model_input_spec) model_dataset_dir = os.path.join(test_dir, "model_dataset") @@ -513,7 +505,6 @@ def lower_run_compare( _save_non_quantized_fp32_executorch_program( model_to_export_fp32, test_dir, - test_name, model_input_spec, ) @@ -521,7 +512,6 @@ def lower_run_compare( _run_delegated_executorch_program( model_to_delegate, test_dir, - test_name, model_calibration_dataset_dir, model_testing_dataset_dir, model_input_spec, @@ -557,7 +547,6 @@ def lower_run_compare( reference_runner, reference_model, test_dir, - test_name, ref_calibration_dataset_dir, ref_testing_dataset_dir, reference_input_spec, @@ -580,7 +569,7 @@ def lower_run_compare( (ref_testing_dataset_dir, ref_spec, remove_quant_io_ops), ] ) - dump_debug_test_summary(test_name, test_dir) + dump_debug_test_summary(request, test_dir) npu_results_dir = os.path.join(test_dir, "results_npu") cpu_results_dir = os.path.join(test_dir, "results_cpu") output_comparator.compare_results(cpu_results_dir, npu_results_dir, output_spec) @@ -590,7 +579,6 @@ def _run_reference_model( reference_runner: ReferenceRunner, reference_model: torch.nn.Module, test_dir, - test_name, calibration_dataset_dir, testing_dataset_dir, reference_input_spec: list[ModelInputSpec], @@ -629,7 +617,6 @@ def _run_reference_model( non_delegated_program = _run_non_delegated_executorch_program( reference_model, test_dir, - test_name, calibration_dataset_dir, testing_dataset_dir, reference_input_spec, @@ -728,7 +715,6 @@ def _run_reference_model( _run_cortex_m_program( model_to_delegate_cortex_m, test_dir, - test_name, calibration_dataset_dir, testing_dataset_dir, reference_input_spec, @@ -782,11 +768,7 @@ def lower_run_compare_ptq_qat( model_ptq = model model_qat = deepcopy(model) - test_name = get_test_name(request) - test_dir = os.path.join(OUTPUTS_DIR, test_name) - - shutil.rmtree(test_dir, ignore_errors=True) - mkdir(test_dir) + test_dir = make_test_dir(request) dataset_dir = os.path.join(test_dir, "model_dataset") mkdir(dataset_dir) @@ -803,7 +785,6 @@ def lower_run_compare_ptq_qat( delegated_program_ptq, _, _ = _run_delegated_executorch_program( model_ptq, test_dir, - test_name, calibration_dataset_dir, testing_dataset_dir, input_spec, @@ -819,7 +800,6 @@ def lower_run_compare_ptq_qat( _ = _run_delegated_executorch_program( model_qat, test_dir, - test_name, calibration_dataset_dir, testing_dataset_dir, input_spec, @@ -836,7 +816,7 @@ def lower_run_compare_ptq_qat( output_tensor_spec = _get_program_output_spec(delegated_program_ptq) if logging.root.isEnabledFor(logging.DEBUG): - dump_debug_test_summary(test_name, test_dir) + dump_debug_test_summary(request, test_dir) shutil.make_archive(test_dir, "zip", test_dir) ptq_results_dir = os.path.join(test_dir, "results_ptq") qat_results_dir = os.path.join(test_dir, "results_qat") @@ -871,13 +851,43 @@ def _parse_input_quant_params( return q_params -def get_test_name(request): - # PyTest request is available, extract correct name including test class and params - test_name = request.node.nodeid.lstrip(":") - # Escape unacceptable characters from test name to make sure it is a valid filesystem directory name - test_name = re.sub(r'[<>:"/\\|?* ,()`]', "_", test_name) - test_name = test_name.strip(" .") - return test_name +def get_test_dir_name(request: FixtureRequest) -> str: + """Return the per-test output directory name "__". + + The test name is the sanitized test file name and the hash is + a truncated SHA-256 of the complete pytest node ID. + + :param request: PyTest fixture request. + """ + nodeid = request.node.nodeid + test_file_name = request.node.path.stem + + digest = hashlib.sha256(nodeid.encode()).hexdigest()[:8] + + return f"{test_file_name}__{digest}" + + +def get_test_dir(request: FixtureRequest) -> pathlib.Path: + """Return the per-test output directory path under OUTPUTS_DIR. + + :param request: PyTest fixture request. + """ + return OUTPUTS_DIR / get_test_dir_name(request) + + +def make_test_dir(request: FixtureRequest) -> str: + """Create and return a fresh per-test output directory under OUTPUTS_DIR. + + The mapping of the directory name to the full test ID is recorded as well. + + :param request: PyTest fixture request. + """ + test_dir = get_test_dir(request) + shutil.rmtree(test_dir, ignore_errors=True) + test_dir.mkdir(parents=True) + dump_test_name_mapping(request, str(test_dir)) + + return str(test_dir) def execute_cmd(cmd, cwd="."): @@ -949,7 +959,7 @@ def get_executorch_git_info() -> dict[str, str]: return {"git_branch": git_branch, "git_commit": git_commit} -def dump_debug_test_summary(test_name: str, test_dir: str): +def dump_debug_test_summary(request: FixtureRequest, test_dir: str): git_info = get_executorch_git_info() # During development, the NSYS in virtual env is not used. @@ -959,7 +969,7 @@ def dump_debug_test_summary(test_name: str, test_dir: str): else version("eiq_nsys") ) summary = { - "test_name": test_name, + "test_node_id": request.node.nodeid, "date_time": datetime.datetime.now().isoformat(), "git_branch": git_info["git_branch"], "git_commit": git_info["git_commit"], @@ -967,7 +977,20 @@ def dump_debug_test_summary(test_name: str, test_dir: str): "eiq_nsys_version": nsys_version, } with open(os.path.join(test_dir, "summary.yaml"), "w") as f: - yaml.dump(summary, f) + # Infinite width to prevent insertion of line breaks, which might prevent look-ups via grep etc. + yaml.dump(summary, f, width=float("inf")) + + +def dump_test_name_mapping(request: FixtureRequest, test_dir: str): + """Append the mapping of test directory name (with hash) to the full pytest node ID. + FileLock is used, so the file writes are thread-safe. + """ + test_name_with_hash = pathlib.Path(test_dir).name + mapping_file = OUTPUTS_DIR / "test_name_mapping.yaml" + with FileLock(f"{mapping_file}.lock"): + with open(mapping_file, "a") as f: + # Infinite width to prevent insertion of line breaks, which might prevent look-ups via grep etc. + yaml.dump({test_name_with_hash: request.node.nodeid}, f, width=float("inf")) def _generate_txt_test_data( diff --git a/backends/nxp/tests/simple_models.py b/backends/nxp/tests/simple_models.py index 85158b77625..c096c379d43 100644 --- a/backends/nxp/tests/simple_models.py +++ b/backends/nxp/tests/simple_models.py @@ -744,6 +744,15 @@ def forward(x, y): return x - y +class AddSubTensorModule(torch.nn.Module): + def __init__(self): + super().__init__() + + @staticmethod + def forward(x, y): + return x + y, x - y + + class MaxPoolSubTensorModule(torch.nn.Module): def __init__(self): super().__init__() diff --git a/backends/nxp/tests/utils.py b/backends/nxp/tests/utils.py index db1985f1831..573e1a2dee1 100644 --- a/backends/nxp/tests/utils.py +++ b/backends/nxp/tests/utils.py @@ -100,7 +100,7 @@ def read_prepared_samples( for spec_idx, spec in enumerate(input_spec): bin_file_path = os.path.join( - sample_dir, f"{str(spec_idx).zfill(2)}.bin" + sample_dir, f"{str(spec_idx).zfill(4)}.bin" ) sample_vector = np.fromfile( bin_file_path, dtype=torch_type_to_numpy_type(spec.dtype) diff --git a/requirements-dev.txt b/requirements-dev.txt index 6348af50ff4..c6996e68e63 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -20,6 +20,7 @@ pytest>=7.3.0,<9.0 pytest-xdist pytest-rerunfailures==14.0 pytest-json-report +filelock # For file writes during parallelized PyTest runs. gguf # For extension/llm/export/test/test_gguf.py (GGUF Q4_K/Q6_K dequant tests). # Needed only by tests and development tools, so the executorch package does not depend on them. expecttest