from model import *

import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
from torchvision import datasets, transforms
from torchvision.transforms.functional import InterpolationMode
import os
import os.path as osp


def train(model, device, train_loader, optimizer, epoch):
    model.train()
    lossLayer = torch.nn.CrossEntropyLoss()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = lossLayer(output, target)
        loss.backward()
        optimizer.step()

        if batch_idx % 50 == 0:
            print('Train Epoch: {} [{}/{}]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset), loss.item()
            ))

def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    lossLayer = torch.nn.CrossEntropyLoss(reduction='sum')
    for data, target in test_loader:
        data, target = data.to(device), target.to(device)
        output = model(data)
        test_loss += lossLayer(output, target).item()
        pred = output.argmax(dim=1, keepdim=True)
        correct += pred.eq(target.view_as(pred)).sum().item()
    
    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.4f}, Accuracy: {:.2f}%\n'.format(
        test_loss, 100. * correct / len(test_loader.dataset)
    ))


if __name__ == "__main__":
    batch_size = 32
    test_batch_size = 32
    seed = 1
    # epoch = 35
    # lr = 0.01
    epochs1 = 15
    epochs2 = epochs1+10
    epochs3 = epochs2+10
    lr1 = 0.01
    lr2 = 0.001
    lr3 = 0.0001
    momentum = 0.5
    save_model = True

    torch.manual_seed(seed)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    train_loader = torch.utils.data.DataLoader(
        datasets.CIFAR10('../data', train=True, download=True,
                       transform=transforms.Compose([
                           transforms.Resize((32, 32), interpolation=InterpolationMode.BICUBIC),
                           transforms.RandomHorizontalFlip(),
                           transforms.ToTensor(),
                           transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
                       ])),
        batch_size=batch_size, shuffle=True, num_workers=1, pin_memory=True
    )

    test_loader = torch.utils.data.DataLoader(
        datasets.CIFAR10('../data', train=False, transform=transforms.Compose([
            transforms.Resize((32, 32), interpolation=InterpolationMode.BICUBIC),
            transforms.ToTensor(),
            transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
        ])),
        batch_size=test_batch_size, shuffle=True, num_workers=1, pin_memory=True
    )

    model = VGG_19().to(device)

    # optimizer = optim.Adam(model.parameters(), lr=lr)
    # lr_scheduler = CosineAnnealingLR(optimizer, T_max=epoch)
    # for epoch in range(1, epoch + 1):
    #     train(model, device, train_loader, optimizer, epoch)
    #     # lr_scheduler.step()
    #     test(model, device, test_loader)

    optimizer1 = optim.SGD(model.parameters(), lr=lr1, momentum=momentum)
    optimizer2 = optim.SGD(model.parameters(), lr=lr2, momentum=momentum)
    optimizer3 = optim.SGD(model.parameters(), lr=lr3, momentum=momentum)
    
    for epoch in range(1, epochs1 + 1):
        train(model, device, train_loader, optimizer1, epoch)
        test(model, device, test_loader)
    
    for epoch in range(epochs1 + 1, epochs2 + 1):
        train(model, device, train_loader, optimizer2, epoch)
        test(model, device, test_loader)
        
    for epoch in range(epochs2 + 1, epochs3 + 1):
        train(model, device, train_loader, optimizer3, epoch)
        test(model, device, test_loader)
    
    if save_model:
        if not osp.exists('ckpt'):
            os.makedirs('ckpt')
        torch.save(model.state_dict(), 'ckpt/cifar10_VGG_19.pt')