|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: LicenseRef-Apache2 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +import logging |
| 17 | + |
| 18 | +import torch |
| 19 | +from datasets import load_dataset |
| 20 | +from torch.utils.data import Dataset |
| 21 | +from torchvision.transforms.functional import to_tensor |
| 22 | + |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +def infinite_dataloader(dataloader, sampler): |
| 28 | + """Create an infinite iterator that automatically restarts at the end of each epoch.""" |
| 29 | + epoch = 0 |
| 30 | + while True: |
| 31 | + sampler.set_epoch(epoch) # Update epoch for proper shuffling |
| 32 | + for batch in dataloader: |
| 33 | + yield batch |
| 34 | + epoch += 1 # Increment epoch counter after completing one full pass |
| 35 | + |
| 36 | + |
| 37 | +class BeansDataset(Dataset): |
| 38 | + """ |
| 39 | + Simple wrapper Dataset for AI-Lab-Makerere/beans that converts PIL images to Tensors. |
| 40 | + """ |
| 41 | + |
| 42 | + def __init__(self, image_size: tuple[int, int], split: str = "train"): |
| 43 | + """ |
| 44 | + Args: |
| 45 | + image_size (tuple[int, int]): Resize 2-D image data to this size. |
| 46 | + split (str): Dataset split to load. Options: ["train", "validation", "test"] |
| 47 | + """ |
| 48 | + self.resize_dimensions = image_size |
| 49 | + # Download Beans Dataset. |
| 50 | + self.dataset = load_dataset("AI-Lab-Makerere/beans", split=split) |
| 51 | + self.class_list = self.dataset.features["labels"].names |
| 52 | + if not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0: |
| 53 | + logger.info( |
| 54 | + f"[AI-Lab-Makerere/beans (Split={split})]\nDataset Size: {len(self.dataset)}\nClasses (Count={len(self.class_list)}): {self.class_list}" |
| 55 | + ) |
| 56 | + |
| 57 | + def __len__(self): |
| 58 | + return len(self.dataset) |
| 59 | + |
| 60 | + def __getitem__(self, idx): |
| 61 | + # Preprocess sample. |
| 62 | + sample = self.dataset[idx] |
| 63 | + image_tensor = to_tensor(sample["image"].resize(self.resize_dimensions).convert("RGB")) |
| 64 | + label_idx = sample["labels"] |
| 65 | + return image_tensor, label_idx |
0 commit comments