# from https://github.com/akamaster/pytorch_resnet_cifar10
"""
Properly implemented ResNet-s for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the implementations on the web is copy-paste from
torchvision's resnet and has wrong number of params.
Proper ResNet-s for CIFAR10 (for fair comparision and etc.) has following
number of layers and parameters:
name      | layers | params
ResNet20  |    20  | 0.27M
ResNet32  |    32  | 0.46M
ResNet44  |    44  | 0.66M
ResNet56  |    56  | 0.85M
ResNet110 |   110  |  1.7M
ResNet1202|  1202  | 19.4m
which this implementation indeed has.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
    Deep Residual Learning for Image Recognition. arXiv:1512.03385
[2] https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
If you use this implementation in you work, please don't forget to mention the
author, Yerlan Idelbayev.
"""
from functools import partial

import torch
import torch.nn as nn
import torch.nn.functional as F
from quantized_modules import TernaryConv2d, TernaryLinear, weights_init

__all__ = ['ResNet', 'resnet20', 'resnet32', 'resnet44', 'resnet56', 'resnet110', 'resnet1202']


class Shortcut(nn.Module):
    def __init__(self, planes):
        super(Shortcut, self).__init__()
        self.planes = planes

    def forward(self, x):
        return F.pad(x[:, :, ::2, ::2], (0, 0, 0, 0, self.planes // 4, self.planes // 4), "constant", 0)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_planes, planes, stride=1, num_branches=2, option='A'):
        super(BasicBlock, self).__init__()
        self.conv1 = TernaryConv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False,
                                   num_branches=num_branches)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = TernaryConv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False,
                                   num_branches=num_branches)
        self.bn2 = nn.BatchNorm2d(planes)

        self.shortcut = nn.Sequential()
        if stride != 1 or in_planes != planes:
            if option == 'A':
                """
                For CIFAR10 ResNet paper uses option A.
                """
                self.shortcut = Shortcut(planes)
            elif option == 'B':
                self.shortcut = nn.Sequential(
                     TernaryConv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False,
                                   num_branches=num_branches),
                     nn.BatchNorm2d(self.expansion * planes)
                )

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += self.shortcut(x)
        out = F.relu(out)
        return out


class ResNet(nn.Module):
    def __init__(self, block, num_blocks, num_classes=10, num_branches=2, num_branches_first=2, num_branches_last=2,
                 quantize_first_layer=False, quantize_last_layer=False, decompose=None):
        super(ResNet, self).__init__()
        self.in_planes = 16
        self.num_branches = num_branches

        first_layer_type = partial(TernaryConv2d, num_branches=num_branches_first)\
            if quantize_first_layer else nn.Conv2d
        self.conv1 = first_layer_type(3, 16, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(16)
        self.layer1 = self._make_layer(block, 16, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 32, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, 64, num_blocks[2], stride=2)
        last_layer_type = partial(TernaryLinear, num_branches=num_branches_last)\
            if quantize_last_layer else nn.Linear
        if decompose is None:
            self.linear = last_layer_type(64 + 1, num_classes, bias=False)
        else:
            self.linear = nn.Sequential(
                last_layer_type(64 + 1, decompose, bias=False),
                last_layer_type(decompose, num_classes, bias=False)
            )
        self.apply(partial(weights_init))

    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride, num_branches=self.num_branches))
            self.in_planes = planes * block.expansion

        return nn.Sequential(*layers)

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = F.avg_pool2d(out, out.size(3))
        out = out.view(out.size(0), -1)
        out = torch.cat([out, out.new_ones((out.size(0), 1))], dim=1)
        out = self.linear(out)
        return out


def resnet20(*args, **kwargs):
    return ResNet(BasicBlock, [3, 3, 3], *args, **kwargs)


def resnet32(*args, **kwargs):
    return ResNet(BasicBlock, [5, 5, 5], *args, **kwargs)


def resnet44(*args, **kwargs):
    return ResNet(BasicBlock, [7, 7, 7], *args, **kwargs)


def resnet56(*args, **kwargs):
    return ResNet(BasicBlock, [9, 9, 9], *args, **kwargs)


def resnet110(*args, **kwargs):
    return ResNet(BasicBlock, [18, 18, 18], *args, **kwargs)


def resnet1202(*args, **kwargs):
    return ResNet(BasicBlock, [200, 200, 200], *args, **kwargs)
