|
| 1 | +# ------------------------------------------------------------------------- |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# Licensed under the MIT License. |
| 4 | +# -------------------------------------------------------------------------- |
| 5 | +from logging import getLogger |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import torchvision.transforms as transforms |
| 10 | +import transformers |
| 11 | +from torch import from_numpy |
| 12 | +from torch.utils.data import Dataset |
| 13 | + |
| 14 | +from olive.data.registry import Registry |
| 15 | + |
| 16 | +logger = getLogger(__name__) |
| 17 | + |
| 18 | +def get_imagenet_label_map(): |
| 19 | + import json |
| 20 | + cache_file = Path(f"./cache/data/imagenet_class_index.json") |
| 21 | + if not cache_file.exists(): |
| 22 | + import requests |
| 23 | + imagenet_class_index_url = ( |
| 24 | + "https://raw.githubusercontent.com/pytorch/vision/main/gallery/assets/imagenet_class_index.json" |
| 25 | + ) |
| 26 | + response = requests.get(imagenet_class_index_url) |
| 27 | + response.raise_for_status() # Ensure the request was successful |
| 28 | + content = response.json() |
| 29 | + cache_file.parent.resolve().mkdir(parents=True, exist_ok=True) |
| 30 | + with open(cache_file, "w") as f: |
| 31 | + json.dump(content, f) |
| 32 | + else: |
| 33 | + with open(cache_file) as f: |
| 34 | + content = json.loads(f.read()) |
| 35 | + |
| 36 | + return {v[0]: int(k) for k, v in content.items()} |
| 37 | + |
| 38 | +def adapt_label_for_mini_imagenet(labels: list, label_names: list): |
| 39 | + label_map = get_imagenet_label_map() |
| 40 | + return [label_map[label_names[x]] for x in labels] |
| 41 | + |
| 42 | +class ImagenetDataset(Dataset): |
| 43 | + def __init__(self, data): |
| 44 | + self.images = from_numpy(data["images"]) |
| 45 | + self.labels = from_numpy(data["labels"]) |
| 46 | + |
| 47 | + def __len__(self): |
| 48 | + return min(len(self.images), len(self.labels)) |
| 49 | + |
| 50 | + def __getitem__(self, idx): |
| 51 | + return {"pixel_values": self.images[idx]}, self.labels[idx] |
| 52 | + |
| 53 | + |
| 54 | +@Registry.register_post_process() |
| 55 | +def dataset_post_process(output): |
| 56 | + return ( |
| 57 | + output.logits.argmax(axis=1) |
| 58 | + if isinstance(output, transformers.modeling_outputs.ModelOutput) |
| 59 | + else output.argmax(axis=1) |
| 60 | + ) |
| 61 | + |
| 62 | +from transformers import AutoImageProcessor |
| 63 | +processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224", use_fast=True) |
| 64 | + |
| 65 | +@Registry.register_pre_process() |
| 66 | +def dataset_pre_process(output_data, **kwargs): |
| 67 | + shuffle = kwargs.get("shuffle", True) |
| 68 | + if shuffle: |
| 69 | + seed = kwargs.get("seed", 42) |
| 70 | + output_data = output_data.shuffle(seed=seed) |
| 71 | + cache_key = kwargs.get("cache_key") |
| 72 | + size = kwargs.get("size", 256) |
| 73 | + cache_file = None |
| 74 | + if cache_key: |
| 75 | + cache_file = Path(f"./cache/data/{cache_key}_{output_data.info.dataset_name}_{size}.npz") |
| 76 | + if cache_file.exists(): |
| 77 | + with np.load(Path(cache_file)) as data: |
| 78 | + return ImagenetDataset(data) |
| 79 | + |
| 80 | + labels = [] |
| 81 | + images = [] |
| 82 | + for i, sample in enumerate(output_data): |
| 83 | + if i >= size: |
| 84 | + break |
| 85 | + image = sample["image"] |
| 86 | + label = sample["label"] |
| 87 | + image = image.convert("RGB") |
| 88 | + image = processor(image)["pixel_values"][0] |
| 89 | + images.append(image) |
| 90 | + labels.append(label) |
| 91 | + |
| 92 | + if(output_data.info.dataset_name == "mini-imagenet"): |
| 93 | + labels = adapt_label_for_mini_imagenet(labels, output_data.features["label"].names) |
| 94 | + result_data = ImagenetDataset({"images": np.array(images), "labels": np.array(labels)}) |
| 95 | + |
| 96 | + if cache_file: |
| 97 | + cache_file.parent.resolve().mkdir(parents=True, exist_ok=True) |
| 98 | + np.savez(cache_file, images=np.array(images), labels=np.array(labels)) |
| 99 | + |
| 100 | + return result_data |
0 commit comments