-
Notifications
You must be signed in to change notification settings - Fork 1.2k
NXP backend: handle tests of mlperf tiny visual wake words #22844
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
novak-vaclav
wants to merge
1
commit into
pytorch:main
Choose a base branch
from
nxp-upstream:feature/EIEX-1031-refactor-mlperf-tiny-vww
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
119 changes: 119 additions & 0 deletions
119
backends/nxp/tests/models/test_mlperf_tiny_visual_wake_words.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| # Copyright 2026 NXP | ||
| # | ||
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| from functools import partial | ||
|
|
||
| import numpy as np | ||
|
|
||
| # noinspection PyUnusedImports | ||
| import pytest | ||
| import torch | ||
|
|
||
| from executorch.backends.nxp.tests.dataset_creator import ( | ||
| FromCalibrationDataDatasetCreator, | ||
| ) | ||
| from executorch.backends.nxp.tests.executorch_pipeline import ModelInputSpec | ||
| from executorch.backends.nxp.tests.graph_verifier import BaseGraphVerifier | ||
| from executorch.backends.nxp.tests.model_output_comparator import ( | ||
| ClassificationAccuracyOutputComparator, | ||
| NumericalStatsOutputComparator, | ||
| ) | ||
| from executorch.backends.nxp.tests.nsys_testing import ( | ||
| lower_run_compare, | ||
| lower_run_compare_ptq_qat, | ||
| ) | ||
| from executorch.backends.nxp.tests.use_qat import * # noqa F403 | ||
| from executorch.examples.nxp.models.mlperf_tiny.visual_wake_words.mlperf_tiny_visual_wake_words import ( | ||
| MLPerfTinyVisualWakeWords, | ||
| ) | ||
|
|
||
| BOUNDS_MSE = { | ||
| "PTQ": {"channels-last": 4.6e-8, "channels-first": 5.0e-8}, | ||
| "QAT": {"channels-last": 3.0e-6, "channels-first": 3.7e-6}, | ||
| } | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def reseed_model_per_test_run(): | ||
| torch.manual_seed(23) | ||
| np.random.seed(23) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("channels_last", [False, True]) | ||
| def test_mlperf_tiny_vww_mse_cpu_vs_npu(mocker, request, channels_last, use_qat): | ||
| # 20 samples per class | ||
| num_samples = 40 | ||
|
|
||
| visual_wake_words = MLPerfTinyVisualWakeWords( | ||
| num_samples=num_samples, use_random_dataset=True | ||
| ) | ||
| model = visual_wake_words.get_eager_model() | ||
| dataset = visual_wake_words.dataset | ||
| labels = visual_wake_words.labels | ||
|
|
||
| dataset_creator = FromCalibrationDataDatasetCreator( | ||
| dataset, num_examples=num_samples, idx_to_label=labels | ||
| ) | ||
|
|
||
| input_spec = ModelInputSpec(visual_wake_words.input_shape) | ||
| if channels_last: | ||
| model.to(memory_format=torch.channels_last) | ||
| input_spec.dim_order = torch.channels_last | ||
|
|
||
| quant_type_key = "QAT" if use_qat else "PTQ" | ||
| format_key = "channels-last" if channels_last else "channels-first" | ||
| mse = BOUNDS_MSE[quant_type_key][format_key] | ||
| comparator = NumericalStatsOutputComparator( | ||
| max_mse_error=mse, use_softmax=True, is_classification_task=True | ||
| ) | ||
| model_verifier = BaseGraphVerifier(1, []) | ||
| train_fn = ( | ||
| partial(visual_wake_words.train_model_fn, channels_last=channels_last) | ||
| if use_qat | ||
| else None | ||
| ) | ||
|
|
||
| lower_run_compare( | ||
| model, | ||
| [input_spec], | ||
| model_verifier, | ||
| request, | ||
| dataset_creator=dataset_creator, | ||
| output_comparator=comparator, | ||
| mocker=mocker, | ||
| use_qat=use_qat, | ||
| train_fn=train_fn, | ||
| ) | ||
|
|
||
|
|
||
| def test_mlperf_tiny_vww_ptq_qat_equivalence(request): | ||
| # 20 samples per class | ||
| num_samples = 40 | ||
|
|
||
| visual_wake_words = MLPerfTinyVisualWakeWords( | ||
| num_samples=num_samples, use_random_dataset=True | ||
| ) | ||
|
|
||
| model = visual_wake_words.get_eager_model() | ||
| dataset = visual_wake_words.dataset | ||
| labels = visual_wake_words.labels | ||
|
|
||
| dataset_creator = FromCalibrationDataDatasetCreator( | ||
| dataset, num_examples=num_samples, idx_to_label=labels | ||
| ) | ||
| comparator = ClassificationAccuracyOutputComparator(class_dict=labels) | ||
|
|
||
| input_spec = ModelInputSpec(visual_wake_words.input_shape) | ||
| model_verifier = BaseGraphVerifier(1, []) | ||
|
|
||
| lower_run_compare_ptq_qat( | ||
| model, | ||
| [input_spec], | ||
| model_verifier, | ||
| request, | ||
| train_fn=visual_wake_words.train_model_fn, | ||
| dataset_creator=dataset_creator, | ||
| output_comparator=comparator, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 4 additions & 0 deletions
4
examples/nxp/models/mlperf_tiny/visual_wake_words/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| # Copyright 2026 NXP | ||
| # | ||
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. |
64 changes: 64 additions & 0 deletions
64
examples/nxp/models/mlperf_tiny/visual_wake_words/mlperf_tiny_visual_wake_words.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| # Copyright 2026 NXP | ||
| # | ||
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| import logging | ||
|
|
||
| import torch | ||
|
|
||
| from executorch.examples.models.mlperf_tiny import MobileNetV1025 | ||
| from executorch.examples.nxp.models.mlperf_tiny.mlperf_tiny_model import MLPerfTinyModel | ||
|
|
||
| log = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class MLPerfTinyVisualWakeWords(MLPerfTinyModel): | ||
| """MLPerf Tiny visual wake words model (MobileNetV1 width 0.25).""" | ||
|
|
||
| # MobileNetV1 specific QAT training hyperparameters. | ||
| TRAIN_HYPERPARAMETERS = { | ||
| "num_epochs": 15, | ||
| "batch_size": 20, | ||
| "lr": 2.5e-7, | ||
| "eps": 1e-7, | ||
| "weight_decay": 0.0, | ||
| } | ||
|
|
||
| INPUT_SHAPE = (1, 3, 96, 96) | ||
| IDX_TO_LABEL = {0: "person", 1: "non_person"} | ||
|
|
||
| # MobileNetV1 stacks 13 depthwise-separable blocks, each with a BatchNorm. | ||
| # Randomly initialized MobileNetV1 has the BatchNorm nodes with default parameters | ||
| # (running_mean=0, running_var=1), causing each depthwise-separable block to behave as identity. | ||
| # In other MLPerf Tiny models, this could be fixed by multiplying the random weights | ||
| # by constant, however in this case the model is too deep and that solution | ||
| # is no longer viable. | ||
| # Instead calibration of BatchNorm by running few forward passes in train mode fixes it. | ||
| BN_CALIBRATION_ITERS = 10 | ||
| BN_CALIBRATION_BATCH_SIZE = 16 | ||
|
|
||
| def _calibrate_batch_norm(self, model: torch.nn.Module) -> None: | ||
| model.train() | ||
| with torch.no_grad(): | ||
| for _ in range(self.BN_CALIBRATION_ITERS): | ||
| inputs = torch.rand( | ||
| (self.BN_CALIBRATION_BATCH_SIZE, *self.input_shape[1:]), | ||
| dtype=torch.float32, | ||
| ) | ||
| model(inputs) | ||
| model.eval() | ||
|
|
||
| @property | ||
| def input_shape(self): | ||
| return self.INPUT_SHAPE | ||
|
|
||
| @property | ||
| def labels(self): | ||
| return self.IDX_TO_LABEL | ||
|
|
||
| def _init_eager_model(self) -> torch.nn.Module: | ||
| model = MobileNetV1025() | ||
| self._calibrate_batch_norm(model) | ||
|
|
||
| return model.eval() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: I would keep the same order of parameters in all tests (and previous one).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I checked params in
lower_run_compareandlower_run_compare_ptq_qatin all executorch MLPerf Tiny tests to make them correspond to the order in your Anomaly Detection PR. The only issue was in image classification.