'''Train CIFAR10 with PyTorch.'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.optim.lr_scheduler import StepLR

import torchvision
import torchvision.transforms as transforms
import numpy as np

import os
import argparse
import pdb

from models.vgg_7_cyc import VGG_7_cyc
from models.vgg_7_mod import VGG_7_mod

parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
parser.add_argument('--lr', default=0.001, type=float, help='learning rate')
parser.add_argument('--wd', default=0, type=float, help='weight decay')
parser.add_argument('--reg', default=0., type=float, help='overflow reg')
parser.add_argument('--clip', default=0, type=float, help='grad clip')
parser.add_argument('--c-bits', default=0, type=int, help='num bits, 0: bin, 1: tern, 2: 2 bits and so on')
parser.add_argument('--steps', default=60, type=int, help='num lr steps')
parser.add_argument('--epochs', default=200, type=int, help='num epochs')
parser.add_argument('--net', default='res18', type=str, help='network structure')
parser.add_argument('--save', type=str, default="test", help='save name for checkpoiny')
parser.add_argument('--resume', type=str, default=None, help='resume from checkpoint')
parser.add_argument('--gpu', type=str, default="0")


args = parser.parse_args()

os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu

device = 'cuda' if torch.cuda.is_available() else 'cpu'
best_acc = 0  # best test accuracy
start_epoch = 0  # start from epoch 0 or last checkpoint epoch

cudnn.benchmark = True

# Data
print('==> Preparing data..')
mean = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
transform_train = transforms.Compose([
    transforms.RandomCrop(32, padding=4),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize(mean, std),
])

transform_test = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean, std),
])

trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)

testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=512, shuffle=False, num_workers=2)

classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

# Model
print('==> Building model %s..' % args.net)
if args.net == "vggcyc":
    net = VGG_7_cyc('VGG7', args.c_bits)
elif args.net == "vgg":
    net = VGG_7_mod('VGG7', args.c_bits)

net = net.to(device)
print(net)

if device == 'cuda':
    net = torch.nn.DataParallel(net)
    cudnn.benchmark = True

if args.resume:
    # Load checkpoint.
    print('==> Resuming from checkpoint..')
    checkpoint = torch.load(args.resume)
    pretrain_dict = checkpoint['net']
    model_dict = net.state_dict()
    model_dict.update(pretrain_dict)
    net.load_state_dict(model_dict)
    best_acc = 0
    start_epoch = 0

criterion = nn.CrossEntropyLoss()

optimizer = optim.Adam([{'params': net.parameters()}], 
                       lr=args.lr, weight_decay=args.wd)

scheduler = StepLR(optimizer, step_size=args.steps, gamma=0.1)
ofrate = 0

# Training
def train(epoch, reg):
    print('\nEpoch: %d, LR: %.5f' % (epoch, scheduler.get_lr()[0]))
    net.train()
    train_loss = 0
    correct = 0
    total = 0
    qrange_loss = 0
    scale = 0
    oflinear = 0

    for batch_idx, (inputs, targets) in enumerate(trainloader):
        inputs, targets = inputs.to(device), targets.to(device)
        optimizer.zero_grad()
        outputs, qrange, ofrate, oflinear = net(inputs)
        loss = criterion(outputs, targets) + reg * qrange 
        loss.backward()

        optimizer.step()

        train_loss += loss.item()
        qrange_loss += qrange.item()
        _, predicted = outputs.max(1)
        total += targets.size(0)
        correct += predicted.eq(targets).sum().item()

        if batch_idx % 50 == 0 or batch_idx == len(trainloader) - 1:
            print('Batch: [{}/{}]\tLoss: {:.4f}\tQrange Loss: {:.4f}\tAccuracy: {:.2f} %\tRate: {:.4f} %\tLinear Rate: {:.4f} %'.format(
                   batch_idx, len(trainloader), train_loss/(batch_idx+1), qrange_loss/(batch_idx+1), 100.*correct/total, ofrate*100., oflinear*100.))

def test(epoch):
    global best_acc
    net.eval()
    test_loss = 0
    correct = 0
    total = 0
    qrange_loss = 0
    scale = 0
    oflinear = 0
    with torch.no_grad():
        print("evaluating:...")
        for batch_idx, (inputs, targets) in enumerate(testloader):
            inputs, targets = inputs.to(device), targets.to(device)
            outputs, qrange, ofrate, oflinear = net(inputs)
            loss = criterion(outputs, targets)

            test_loss += loss.item()
            qrange_loss += qrange.item()
            _, predicted = outputs.max(1)
            total += targets.size(0)
            correct += predicted.eq(targets).sum().item()

            if batch_idx % 50 == 0 or batch_idx == len(testloader) - 1:
                print('Batch: [{}/{}]\tLoss: {:.4f}\tQrange Loss: {:.4f}\tAccuracy: {:.2f} %\tScale: {:.4f}\tRate: {:.4f} %\tLinear Rate: {:.4f} %'.format(
                       batch_idx, len(testloader), test_loss/(batch_idx+1), qrange_loss/(batch_idx+1), 100.*correct/total, scale, ofrate*100., oflinear*100.))

    # Save checkpoint.
    acc = 100.*correct/total
    if acc > best_acc:
        print('Saving..')
        state = {
            'net': net.state_dict(),
            'acc': acc,
            'epoch': epoch,
        }
        if not os.path.isdir('checkpoint/'):
            os.mkdir('checkpoint/')
        torch.save(state, args.save)
        best_acc = acc

for epoch in range(start_epoch, start_epoch+args.epochs):
    train(epoch, args.reg) 
    scheduler.step()
    test(epoch)
