"""Data pipeline for the Oxford-IIIT Pet dataset. Handles loading the raw Oxford-IIIT Pet images, transforming them into PyTorch tensors, creating balanced data splits, and packaging them into batches ready for model training and evaluation. """ # region # __future__ annotations: ## Tells python to not evaluate type annotation when the file is being imported and treat them as text strings ## This avoids circular import errors and speeds up module initialization. ## I found that this is a defensive best practice # endregion from __future__ import annotations import numpy as np # region # used to split training vs validation data; keeps testing data separate # train is for learning model weights; Validations is for monitoring loss early (deterministic); # Test is the final benchmark (deterministic) # endregion from torch.utils.data import DataLoader, Subset # region # transforms allows for image processing, transformation, and data augmentation # endregion from torchvision import transforms from torchvision.datasets import OxfordIIITPet # region # resiize images to be the same so the tensor shapes are the same. 224x224 is industry standard # endregion IMAGE_SIZE = 224 # region # later will be using the model ResNet18 which was trained on these numbers # endregion IMAGENET_MEAN = [0.485, 0.456, 0.406] IMAGENET_STD = [0.229, 0.224, 0.225] # region # random generator - guarantees that your train/validation split, weight initializations, # and baseline results are identical no matter where the code is ran # endregion SEED = 42 def build_train_transform(image_size: int = IMAGE_SIZE) -> transforms.Compose: """Training transform: resize, light augmentation, tensor conversion, normalization for TRAINING images.""" return transforms.Compose( [ # region ## In tis function I am augmenting the picture so the model can learn from different angles. ## Resize: scales photo to 124x124 px ## RandomHorizontalFlip: mirroring image so model knows it's the same pet, no matter the dirction ## RandomRotation:eaches model it's the same pet, even if there is a 10degress angle ## ToTensor: converts the PIL image (image in memory), to a floading-point tensor. shape = (3, 244, 244) 3 is rgb color channels ## Normalize: centers and scales rgb so gradients - this is for the ResNet18 model #endregion transforms.Resize((image_size, image_size)), transforms.RandomHorizontalFlip(), transforms.RandomRotation(10), transforms.ToTensor(), transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD), ] ) def build_eval_transform(image_size: int = IMAGE_SIZE) -> transforms.Compose: """Deterministic transform for validation, testing, and inference for VALIDATION and TESTING images.""" return transforms.Compose( [ # region ## Resize: scale images to 224 x 224 for uniform tensor shapes ## ToTensor: converts images to (3,224, 224) shape. 3 is rgb ## Normalize: matches what is expected for the ResNet18 model # endregion transforms.Resize((image_size, image_size)), transforms.ToTensor(), transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD), ] ) def stratified_split_indices( # region # stratified - means to split the data # labels: tells the function what breed each photo belongs to. Images are assined a number already (catagory id) # labels: breed IDs (0-36) for every image in the dataset. # Used here to group photos by breed so each class gets split 80/20. # Note: Returns photo position indices (not label IDs), which build_datasets # passes into torch.utils.data.Subset to carve out train and val splits. # endregion labels: list[int], validation_fraction: float = 0.2, # 20% of data goes to the validation set seed: int = SEED, # seed = 42 # region # the arrow will return a type hint of what the data will send back. # a tuple with 2 items that are integers. The 1st will be training data, the 2nd will be validation. # endregion ) -> tuple[list[int], list[int]]: """Split sample indices into train and validation sets, preserving class balance. Each class contributes ``validation_fraction`` of its samples to the validation set, so every breed is represented in both partitions. """ # region ## label_array: converts the python list to a numpy array because lists do not suport vectorized boolean comparisons ## random_state: pass a fixed seed (42) for reproducibility because will yeild the same permutation every time. ## train_indices: creating an empty list that will accumulate. We have 37 breeds and the row will append to the list. list[int] is jsut a type hint ## validation_indices: creating an empty list, just like train_indicies, but for the validation (20% portion of data) # endregion label_array = np.asarray(labels) random_state = np.random.default_rng(seed) train_indices: list[int] = [] validation_indices: list[int] = [] # region ## for loop: takes the values in label_array and loops through them, 37 times, once for every pet breed # class_indices: where label array and class_id are equal (true), retruns indicies of true values ## random_state.shuffle: shuffles the class_indicies, above it was set to use 42. Helps to eliminate bias. ## validation_count: calculates how many images from the specific breed should go into the validation set. validation_fraction as set to 20% earlier ## validation_indices.extend: Takes the first validation_count elements from the shuffled array converts numpy array to a list ## train_indices.extend: same as validation_indices.extend, but for train ## return sorted: orders the indicies and returns two elements in the tuple (the function returns two int tuples). # endregion for class_id in np.unique(label_array): class_indices = np.flatnonzero(label_array == class_id) random_state.shuffle(class_indices) validation_count = max(1, int(round(len(class_indices) * validation_fraction))) validation_indices.extend(class_indices[:validation_count].tolist()) train_indices.extend(class_indices[validation_count:].tolist()) return sorted(train_indices), sorted(validation_indices) def build_datasets( # region ## This function will download the Oxford-IIIT data, apply the transform pipelines, spliting the dataset, and return object for pytorch DataLoader ## data_root: the data folder is where images and annotations are stored ## image_size: defaults to 224 (previously declared variable) ## validation_fraction: defaults to 20%, (previously declared variable) ## seed: defaulted to 42. Forwards to random seed to stratified_split_indices() ## download: Boolean flag of True passed to torchvision constructor because pytorch will check if th dataset exists in the data folder. Only will extract if missing. # endregion data_root: str = "data", image_size: int = IMAGE_SIZE, validation_fraction: float = 0.2, seed: int = SEED, download: bool = True, # region ## the union '|' indicated that either the function will return a Pytorch Subset ### instance or data from OxfordIIITPet. Subset is for 'train' and 'val' datasets. ### OxfordIIITPet is used for the test set because test data is loaded directly without index slicing. ### note test data in OxfordIIITPet already comes partitioned as its own self-contained dataset. # endregion ) -> dict[str, Subset | OxfordIIITPet]: """Create the train, validation, and test datasets. The ``trainval`` partition is instantiated twice: once with augmentation (for the training subset) and once with the deterministic transform (for the validation subset), so validation images are never augmented. """ # region ## trainval_augmented = OxfordIIITPet(: Instanciates the PyTorch dataset object from torchvision’s ### built-in OxfordIIITPet class and assigns it to the variable trainval_augmented ## root: The data is in the data_root folder for the OxfordIIITPet dataset ## split: gets the combined training and validation partition in the OxfordIIITPet dataset ## target_types: Passing "category" ensures the dataset returns an integer class ID (0 through 36) representing the pet breed for each photo. ## transform: calls the helper function to assign the image transformation to this dataset ## download: passes in the True or False vale to see if dataset exists locally. (variable declared as True above) # endregion trainval_augmented = OxfordIIITPet( root=data_root, split="trainval", target_types="category", transform=build_train_transform(image_size), download=download, ) # region ## Performs the same as the trainval_augmented, but for plain images # endregion trainval_plain = OxfordIIITPet( root=data_root, split="trainval", target_types="category", transform=build_eval_transform(image_size), download=download, ) # region ## Performs the same as the trainval_augmented, but for test images. Note that Oxford has test data reserved already # endregion test_dataset = OxfordIIITPet( root=data_root, split="test", target_types="category", transform=build_eval_transform(image_size), download=download, ) # region ## unpack the tuple from stratified_split_indices and assign them variables: train_indices, validation_indices ### these will be passed into aonother torch.util.data.Subset to partition the dataset into two distict sets ### calls stratified_split_indices() to perform class-by-class grouping, deterministic shuffling, and proportional slicing ## trainval_plain._labels: trainval_plain was defined above, ._labels is torchvision's list containing breed ID for ever image in trainval ## validation_fraction=validation_fraction: defauted to 20% in previous variable. Tells the splitter that 20% of photos ### should be allocated to validation, leaving 80% for training. ### seed = seed: 42...random shuffle produces the exact same split index list everytime the function funs. # endregion train_indices, validation_indices = stratified_split_indices( trainval_plain._labels, validation_fraction=validation_fraction, seed=seed ) # region ## Returns a python dictionary with three values, train. validation, and test as the Keys. Makes reading easier later ## train subset: the training data will have the randomized augmetations, train_indicies is 80% portion of row indices ### Later the DataLoader will request item 0 from this train split, Subset looks up the catalog position in train_indices to get ### the image through trainval_agmented. ## vadisation subset: is deterministic evaluation with 20% row indicies for validation ## test dataset: assigns the benchmark test dataset directly to 'test' key. THis data is already isolated, so didn't need subset. # endregion return { "train": Subset(trainval_augmented, train_indices), "validation": Subset(trainval_plain, validation_indices), "test": test_dataset, } def build_dataloaders( # region ## This function is responsible for creating the PyTorch DataLoader objects ## datasets: variable expects a dictionary of either 'train', 'validation', ### or 'test' and the values are either from Subset or OxfordIIITPet objects. expects data from build_datasets() ## batch_size: Dictates how many images are groupd together into a single tensor during each training, or evaluation loop ## If batch size is 32, the output tensor fed into ResNet-18 will have 4D Shape ### (Batch, Channels(rbg), 224(height), 224(width)). This fits with the GPU Memory of NVIDIA T4 ## num_workers: Specifies how many subprocesses CPU threads use to preload and preprocess images async while GPU trains ## pin_memory: When set to True, the DataLoader allocates the loaded batch tensors into 'pinned' host memor. ### This enables faster dirct memory trainsfers. Ture when training on NVIDIA GPU ## dict[str, DataLoader]: ## Note, DataLoader is a function in the pytorch utils.py file # endregion datasets: dict[str, Subset | OxfordIIITPet], batch_size: int = 32, num_workers: int = 2, pin_memory: bool = False, ) -> dict[str, DataLoader]: """Wrap each dataset in a ``DataLoader``; only the training loader shuffles.""" # region ## loaders: Initialze an empty python dict (includes type hints) and the values are from the Pytorch DataLoader instances ## loop: itterates through each each key value in datasets() dictionary (these come from build_datasets()) ## loaders[split_name] : Instanciates a new PyTorch DataLoader for the current split and maps to split_name inside loaders ## split_dataset: passes in the value of split_dataset into the loader (variable in the for loop - train, validate, test) ## batch_size: already set to 32, dictates how many samples are stacked into each batch tensor. ### The model will look at a set of 32 and then calculate its error and update. ## shuffle: if the data is 'train' this will be True, else False. Training data must be shuffed every epock so the ### model doesn't memorize image order and gradient updates remain stochastic. (Gradient update is the step a model ### takes to correct its internal settings - weights abd biases, so it can be more accurate. In this case, every batch_size=32) ## num_workers: set for processing. Forwards the worker thread count (default 2) so multiple ### subprocesses read and transform image files in parallel. ## pin_memory: When using CUDA setup, it locks RAM to speed up the PCIe data transfer dirctly to GPU VRAM. This is more to do ### with the hardware for the GPU and how it allocated memory. ## persistent_workers: Checks if num_workers is > 0. If > 0, then persistent_workers = True, else False. ### PyTorch kills and respons worker subprocesses at the end of each epoch. If Ture, then keeps the backgroud ### worker processes in memory between epochs. This helps speed up the training loops. ## the function will return a dict of rtrain, validation, test . # endregion loaders: dict[str, DataLoader] = {} for split_name, split_dataset in datasets.items(): loaders[split_name] = DataLoader( split_dataset, batch_size=batch_size, shuffle=(split_name == "train"), num_workers=num_workers, pin_memory=pin_memory, persistent_workers=num_workers > 0, ) return loaders