|
| 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 | +from typing import Iterator |
| 8 | + |
| 9 | +import torch |
| 10 | +import torchvision |
| 11 | + |
| 12 | +from executorch.examples.models.mobilenet_v2 import MV2Model |
| 13 | +from torch.utils.data import DataLoader |
| 14 | +from torchvision import transforms |
| 15 | + |
| 16 | + |
| 17 | +class MobilenetV2(MV2Model): |
| 18 | + |
| 19 | + def get_calibration_inputs( |
| 20 | + self, batch_size: int = 1 |
| 21 | + ) -> Iterator[tuple[torch.Tensor]]: |
| 22 | + """ |
| 23 | + Returns an iterator for the Imagenette validation dataset, downloading it if necessary. |
| 24 | +
|
| 25 | + Args: |
| 26 | + batch_size (int): The batch size for the iterator. |
| 27 | +
|
| 28 | + Returns: |
| 29 | + iterator: An iterator that yields batches of images from the Imagnetette validation dataset. |
| 30 | + """ |
| 31 | + dataloader = self.get_dataset(batch_size) |
| 32 | + |
| 33 | + # Return the iterator |
| 34 | + dataloader_iterable = itertools.starmap( |
| 35 | + lambda data, label: (data,), iter(dataloader) |
| 36 | + ) |
| 37 | + |
| 38 | + # We want approximately 500 samples |
| 39 | + batch_count = 500 // batch_size |
| 40 | + return itertools.islice(dataloader_iterable, batch_count) |
| 41 | + |
| 42 | + def get_dataset(self, batch_size): |
| 43 | + # Define data transformations |
| 44 | + data_transforms = transforms.Compose( |
| 45 | + [ |
| 46 | + transforms.Resize((224, 224)), |
| 47 | + transforms.ToTensor(), |
| 48 | + transforms.Normalize( |
| 49 | + mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] |
| 50 | + ), # ImageNet stats |
| 51 | + ] |
| 52 | + ) |
| 53 | + |
| 54 | + dataset = torchvision.datasets.Imagenette( |
| 55 | + root="./data", split="val", transform=data_transforms, download=True |
| 56 | + ) |
| 57 | + dataloader = torch.utils.data.DataLoader( |
| 58 | + dataset, |
| 59 | + batch_size=batch_size, |
| 60 | + shuffle=False, |
| 61 | + num_workers=1, |
| 62 | + ) |
| 63 | + return dataloader |
| 64 | + |
| 65 | + |
| 66 | +def gather_samples_per_class_from_dataloader( |
| 67 | + dataloader, num_samples_per_class=10 |
| 68 | +) -> list[tuple]: |
| 69 | + """ |
| 70 | + Gathers a specified number of samples for each class from a DataLoader. |
| 71 | +
|
| 72 | + Args: |
| 73 | + dataloader (DataLoader): The PyTorch DataLoader object. |
| 74 | + num_samples_per_class (int): The number of samples to gather for each class. Defaults to 10. |
| 75 | +
|
| 76 | + Returns: |
| 77 | + samples: A list of (sample, label) tuples. |
| 78 | + """ |
| 79 | + |
| 80 | + if not isinstance(dataloader, DataLoader): |
| 81 | + raise TypeError("dataloader must be a torch.utils.data.DataLoader object") |
| 82 | + if not isinstance(num_samples_per_class, int) or num_samples_per_class <= 0: |
| 83 | + raise ValueError("num_samples_per_class must be a positive integer") |
| 84 | + |
| 85 | + labels = sorted( |
| 86 | + set([label for _, label in dataloader.dataset]) |
| 87 | + ) # Get unique labels from the dataset |
| 88 | + samples_per_label = {label: [] for label in labels} # Initialize dictionary |
| 89 | + |
| 90 | + for sample, label in dataloader: |
| 91 | + label = label.item() |
| 92 | + if len(samples_per_label[label]) < num_samples_per_class: |
| 93 | + samples_per_label[label].append((sample, label)) |
| 94 | + |
| 95 | + samples = [] |
| 96 | + |
| 97 | + for label in labels: |
| 98 | + samples.extend(samples_per_label[label]) |
| 99 | + |
| 100 | + return samples |
| 101 | + |
| 102 | + |
| 103 | +def generate_input_samples_file(): |
| 104 | + model = MobilenetV2() |
| 105 | + dataloader = model.get_dataset(batch_size=1) |
| 106 | + samples = gather_samples_per_class_from_dataloader( |
| 107 | + dataloader, num_samples_per_class=2 |
| 108 | + ) |
| 109 | + |
| 110 | + torch.save(samples, "calibration_data.pt") |
| 111 | + |
| 112 | + |
| 113 | +if __name__ == "__main__": |
| 114 | + generate_input_samples_file() |
0 commit comments