|
| 1 | +# Copyright 2025 NXP |
| 2 | +# |
| 3 | +# This source code is licensed under the BSD-style license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | + |
| 6 | +import itertools |
| 7 | +import os |
| 8 | +from typing import Iterator |
| 9 | + |
| 10 | +import torch |
| 11 | +from torch import nn |
| 12 | +from torch.utils.data import DataLoader |
| 13 | + |
| 14 | +from executorch.examples.models import model_base |
| 15 | + |
| 16 | + |
| 17 | +class MicroSpeechLSTM(model_base.EagerModelBase): |
| 18 | + |
| 19 | + def __init__(self): |
| 20 | + self._weights_file = os.path.join(os.path.dirname(__file__), 'microspeech_lstm_best.pth') |
| 21 | + calibration_dataset_path = os.path.join(os.path.dirname(__file__), 'calibration_data.pt') |
| 22 | + self._calibration_dataset = torch.load(calibration_dataset_path, map_location=torch.device('cpu')) |
| 23 | + |
| 24 | + @staticmethod |
| 25 | + def _collate_fn(data: list[tuple]): |
| 26 | + data, labels = zip(*data) |
| 27 | + return torch.stack(list(data)), torch.tensor(list(labels)) |
| 28 | + |
| 29 | + def get_eager_model(self) -> torch.nn.Module: |
| 30 | + lstm_module = MicroSpeechLSTMModule() |
| 31 | + lstm_module.load_state_dict(torch.load(self._weights_file, weights_only=True, map_location=torch.device('cpu'))) |
| 32 | + |
| 33 | + return lstm_module |
| 34 | + |
| 35 | + def get_example_inputs(self) -> tuple[torch.Tensor]: |
| 36 | + sample = self._calibration_dataset[0] |
| 37 | + |
| 38 | + return (sample[0].unsqueeze(0),) # use only sample data, not label |
| 39 | + |
| 40 | + def get_calibration_inputs(self, batch_size: int = 1) -> Iterator[tuple[torch.Tensor]]: |
| 41 | + """ |
| 42 | + Get LSTM's calibration input. Batch size is ignored and set to 1 because hidden state |
| 43 | + has to be initialized to the size of batch. |
| 44 | +
|
| 45 | + :param batch_size: Ignored. |
| 46 | + :return: Iterator with input calibration dataset samples. |
| 47 | + """ |
| 48 | + data_loader = DataLoader(self._calibration_dataset, batch_size=1) |
| 49 | + return itertools.starmap(lambda data, label: (data,), iter(data_loader)) |
| 50 | + |
| 51 | + |
| 52 | +class MicroSpeechLSTMModule(nn.Module): |
| 53 | + |
| 54 | + def __init__(self, input_size=80, output_size=3, features_size=128): |
| 55 | + super(MicroSpeechLSTMModule, self).__init__() |
| 56 | + self.lstm = nn.LSTM(input_size, features_size, batch_first=True) |
| 57 | + self.linear = nn.Linear(features_size, output_size) |
| 58 | + |
| 59 | + def forward(self, x): |
| 60 | + _, (x, _) = self.lstm(x) |
| 61 | + x = x.squeeze(0) |
| 62 | + x = self.linear(x) |
| 63 | + x = nn.functional.softmax(x, dim=1) |
| 64 | + return x |
0 commit comments