|
| 1 | +# Copyright 2023 Nod Labs, Inc |
| 2 | +# |
| 3 | +# Licensed under the Apache License v2.0 with LLVM Exceptions. |
| 4 | +# See https://llvm.org/LICENSE.txt for license information. |
| 5 | +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | + |
| 7 | +import logging |
| 8 | + |
| 9 | +import math |
| 10 | +import unittest |
| 11 | +from dataclasses import dataclass |
| 12 | +from typing import Any, Optional, Tuple |
| 13 | + |
| 14 | +import torch |
| 15 | +import torch.nn.functional as F |
| 16 | +from torch import nn |
| 17 | +import torch.optim as optim |
| 18 | + |
| 19 | +import torchvision.transforms as transforms |
| 20 | +import torchvision.datasets as datasets |
| 21 | +from torch.utils.data import DataLoader |
| 22 | + |
| 23 | + |
| 24 | +# MNIST Data Loader |
| 25 | +class MNISTDataLoader: |
| 26 | + def __init__(self, batch_size, shuffle=True): |
| 27 | + self.batch_size = batch_size |
| 28 | + self.shuffle = shuffle |
| 29 | + |
| 30 | + # Data Transformations |
| 31 | + transform = transforms.Compose([ |
| 32 | + transforms.ToTensor(), |
| 33 | + transforms.Normalize((0.5,), (0.5,)) |
| 34 | + ]) |
| 35 | + |
| 36 | + # Download MNIST dataset |
| 37 | + self.mnist_trainset = datasets.MNIST(root='../data', train=True, download=True, transform=transform) |
| 38 | + self.mnist_testset = datasets.MNIST(root='../data', train=False, download=True, transform=transform) |
| 39 | + |
| 40 | + def get_train_loader(self): |
| 41 | + return DataLoader( |
| 42 | + dataset=self.mnist_trainset, |
| 43 | + batch_size=self.batch_size, |
| 44 | + shuffle=self.shuffle |
| 45 | + ) |
| 46 | + |
| 47 | + def get_test_loader(self): |
| 48 | + return DataLoader( |
| 49 | + dataset=self.mnist_testset, |
| 50 | + batch_size=self.batch_size, |
| 51 | + shuffle=False |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +# Simple CNN Model |
| 56 | +class CNN(nn.Module): |
| 57 | + def __init__(self): |
| 58 | + super(CNN, self).__init__() |
| 59 | + self.conv1 = nn.Conv2d(1, 32, kernel_size=5) |
| 60 | + self.relu = nn.ReLU() |
| 61 | + self.maxpool = nn.MaxPool2d(kernel_size=2) |
| 62 | + self.fc1 = nn.Linear(32 * 12 * 12, 10) |
| 63 | + |
| 64 | + def forward(self, x): |
| 65 | + x = self.conv1(x) |
| 66 | + x = self.relu(x) |
| 67 | + x = self.maxpool(x) |
| 68 | + x = x.view(x.size(0), -1) |
| 69 | + x = self.fc1(x) |
| 70 | + return x |
| 71 | + |
| 72 | +# Training |
| 73 | +def train(model, images, labels, optimizer, criterion): |
| 74 | + model.train() |
| 75 | + |
| 76 | + total_loss = 0.0 |
| 77 | + num_correct = 0.0 |
| 78 | + |
| 79 | + optimizer.zero_grad() |
| 80 | + # images, labels = images.to(device), labels.to(device) |
| 81 | + outputs = model(images) |
| 82 | + loss = criterion(outputs, labels) |
| 83 | + |
| 84 | + num_correct += int((torch.argmax(outputs, dim=1) == labels).sum()) |
| 85 | + total_loss += float(loss.item()) |
| 86 | + |
| 87 | + loss.backward() |
| 88 | + optimizer.step() |
| 89 | + total_loss += loss.item() |
| 90 | + |
| 91 | +# TODO Implement inference func |
| 92 | +""" |
| 93 | +def test(model, images, labels, criterion): |
| 94 | + model.eval() |
| 95 | + num_correct = 0.0 |
| 96 | + total_loss = 0.0 |
| 97 | + with torch.no_grad(): |
| 98 | +
|
| 99 | + # images, labels = images.to(device), labels.to(device) |
| 100 | + with torch.inference_mode(): |
| 101 | + outputs = model(images) |
| 102 | + loss = criterion(outputs, labels) |
| 103 | +
|
| 104 | + num_correct += int((torch.argmax(outputs, dim=1) == labels).sum()) |
| 105 | + total_loss += float(loss.item()) |
| 106 | +
|
| 107 | + # acc = 100 * num_correct / (config['batch_size'] * len(test_loader)) |
| 108 | + # total_loss = float(total_loss / len(test_loader)) |
| 109 | + # return acc, total_loss |
| 110 | +""" |
| 111 | + |
| 112 | +def main(): |
| 113 | + # Example Hyperparameters |
| 114 | + config = { |
| 115 | + 'batch_size': 64, |
| 116 | + 'learning_rate': 0.001, |
| 117 | + # 'threshold' : 0.001, |
| 118 | + # 'factor' : 0.1, |
| 119 | + 'num_epochs': 10, |
| 120 | + } |
| 121 | + |
| 122 | + # Data Loader |
| 123 | + custom_data_loader = MNISTDataLoader(config['batch_size']) |
| 124 | + train_loader = custom_data_loader.get_train_loader() |
| 125 | + # test_loader = MNISTDataLoader.get_test_loader() |
| 126 | + |
| 127 | + # Model, optimizer, loss |
| 128 | + model = CNN() |
| 129 | + optimizer = optim.Adam(model.parameters(), lr=config['learning_rate']) |
| 130 | + criterion = nn.CrossEntropyLoss() |
| 131 | + |
| 132 | + # Training |
| 133 | + train_opt = torch.compile(train, backend="turbine_cpu") |
| 134 | + for i, (images, labels) in enumerate(train_loader): |
| 135 | + train_opt(model, images, labels, optimizer, criterion) |
| 136 | + |
| 137 | + |
| 138 | + # TODO: Inference |
| 139 | + """ |
| 140 | + test_opt = torch.compile(test, backend="turbine_cpu", mode="reduce-overhead") |
| 141 | + for i, (images, labels) in enumerate(test_loader): |
| 142 | + test(model, images, labels, criterion) |
| 143 | + """ |
| 144 | + |
| 145 | + |
| 146 | + |
| 147 | +class ModelTests(unittest.TestCase): |
| 148 | + @unittest.expectedFailure |
| 149 | + def testMNIST(self): |
| 150 | + # TODO: Fix the below error |
| 151 | + """ |
| 152 | + failed to legalize operation 'arith.sitofp' that was explicitly marked illegal |
| 153 | + """ |
| 154 | + main() |
| 155 | + |
| 156 | + |
| 157 | +if __name__ == "__main__": |
| 158 | + logging.basicConfig(level=logging.DEBUG) |
| 159 | + unittest.main() |
0 commit comments