# AUTOGENERATED! DO NOT EDIT! File to edit: 00_resnet.ipynb (unless otherwise specified).

__all__ = ['model_urls', 'conv3x3', 'conv1x1', 'BasicBlock', 'Bottleneck', 'ResNet', 'resnet18', 'resnet34', 'resnet50',
           'resnet101', 'resnet152']


# Cell
import os
import shutil
import time
import torch.nn as nn
import torch.utils.model_zoo as model_zoo

model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}


# Cell
def conv3x3(in_planes, out_planes, stride=1):
    """Return a 3x3 convolution taking in `in_planes` filters and outputting
       `out_planes` filters with padding and stride `stride`."""
    return nn.Conv2d(
        in_planes, out_planes, kernel_size=3, stride=stride,
        padding=1, bias=False
    )


# Cell
def conv1x1(in_planes, out_planes, stride=1):
    """Return a 1x1 convolution taking in `in_planes` filters and outputting
       `out_planes` filters with padding and stride `stride`."""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)


# Cell
class BasicBlock(nn.Module):
    """The basic building block for ResNets, encompassing the residual connection. Takes in
       `inplanes` number of input filters, outputs `planes` number of output filters, with
       stride `stride` on the first 3x3 conv, and an optional downsampling (`nn.Module`)
       on the residual output via the `downsample` parameter."""
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


# Cell
class Bottleneck(nn.Module):
    """The bottleneck building block for ResNets, encompassing the residual connection. Takes in
       `inplanes` number of input filters, outputs `planes` number of output filters, with
       stride `stride` on the first 3x3 conv, and an optional downsampling (`nn.Module`)
       on the residual output via the `downsample` parameter."""
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = conv1x1(inplanes, planes)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = conv3x3(planes, planes, stride)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = conv1x1(planes, planes * self.expansion)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


# Cell
class ResNet(nn.Module):
    """Constructs a ResNet using a block specification and number of layers. Also specifies where to
       output training logs and model/system state."""
    def __init__(
        self, block, layers, num_classes=1000,
        log_dir = '/share/nikola/export/dt372/breakhis_gradcam/logs',
        save_dir = '/share/nikola/export/dt372/breakhis_gradcam/models',
        create_log_and_save_dirs=True
    ):
        super(ResNet, self).__init__()
        self.inplanes = 64
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.out_fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        if create_log_and_save_dirs:
            self.setup_logging_and_output_dirs(log_dir, save_dir)

    def setup_logging_and_output_dirs(self, log_dir, save_dir):
        timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())
        self.log_dir = os.path.join(log_dir, timestamp)
        os.mkdir(self.log_dir)
        self.save_dir = os.path.join(save_dir, timestamp)
        os.mkdir(self.save_dir)

    def clear_logging_and_output_dirs(self):
        assert self.log_dir and self.save_dir, "The logging and output directories were never created."
        print("Removing directory %s and all contents." % self.log_dir)
        shutil.rmtree(self.log_dir, ignore_errors=False, onerror=None)
        print("Removing directory %s and all contents." % self.save_dir)
        shutil.rmtree(self.save_dir, ignore_errors=False, onerror=None)

        print("Resetting %s and %s." % (self.log_dir, self.save_dir))
        os.mkdir(self.log_dir)
        os.mkdir(self.save_dir)

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.out_fc(x)

        return x


# Cell
def resnet18(pretrained=False, **kwargs):
    """Constructs a ResNet-18 model."""
    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet18']), strict=False)
    return model


def resnet34(pretrained=False, **kwargs):
    """Constructs a ResNet-34 model."""
    model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet34']), strict=False)
    return model


def resnet50(pretrained=False, **kwargs):
    """Constructs a ResNet-50 model."""
    model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet50']), strict=False)
    return model


def resnet101(pretrained=False, **kwargs):
    """Constructs a ResNet-101 model."""
    model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet101']), strict=False)
    return model


def resnet152(pretrained=False, **kwargs):
    """Constructs a ResNet-152 model."""
    model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet152']), strict=False)
    return model
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_resnet.ipynb (unless otherwise specified).

__all__ = ['model_urls', 'conv3x3', 'conv1x1', 'BasicBlock', 'Bottleneck', 'ResNet', 'resnet18', 'resnet34', 'resnet50',
           'resnet101', 'resnet152']


# Cell
import os
import shutil
import time
import torch.nn as nn
import torch.utils.model_zoo as model_zoo

model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}


# Cell
def conv3x3(in_planes, out_planes, stride=1):
    """Return a 3x3 convolution taking in `in_planes` filters and outputting
       `out_planes` filters with padding and stride `stride`."""
    return nn.Conv2d(
        in_planes, out_planes, kernel_size=3, stride=stride,
        padding=1, bias=False
    )


# Cell
def conv1x1(in_planes, out_planes, stride=1):
    """Return a 1x1 convolution taking in `in_planes` filters and outputting
       `out_planes` filters with padding and stride `stride`."""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)


# Cell
class BasicBlock(nn.Module):
    """The basic building block for ResNets, encompassing the residual connection. Takes in
       `inplanes` number of input filters, outputs `planes` number of output filters, with
       stride `stride` on the first 3x3 conv, and an optional downsampling (`nn.Module`)
       on the residual output via the `downsample` parameter."""
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


# Cell
class Bottleneck(nn.Module):
    """The bottleneck building block for ResNets, encompassing the residual connection. Takes in
       `inplanes` number of input filters, outputs `planes` number of output filters, with
       stride `stride` on the first 3x3 conv, and an optional downsampling (`nn.Module`)
       on the residual output via the `downsample` parameter."""
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = conv1x1(inplanes, planes)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = conv3x3(planes, planes, stride)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = conv1x1(planes, planes * self.expansion)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out


# Cell
class ResNet(nn.Module):
    """Constructs a ResNet using a block specification and number of layers. Also specifies where to
       output training logs and model/system state."""
    def __init__(
        self, block, layers, num_classes=1000,
        log_dir = '/share/nikola/export/dt372/breakhis_gradcam/logs',
        save_dir = '/share/nikola/export/dt372/breakhis_gradcam/models',
        create_log_and_save_dirs=True
    ):
        super(ResNet, self).__init__()
        self.inplanes = 64
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.out_fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        if create_log_and_save_dirs:
            self.setup_logging_and_output_dirs(log_dir, save_dir)

    def setup_logging_and_output_dirs(self, log_dir, save_dir):
        timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())
        self.log_dir = os.path.join(log_dir, timestamp)
        os.mkdir(self.log_dir)
        self.save_dir = os.path.join(save_dir, timestamp)
        os.mkdir(self.save_dir)

    def clear_logging_and_output_dirs(self):
        assert self.log_dir and self.save_dir, "The logging and output directories were never created."
        print("Removing directory %s and all contents." % self.log_dir)
        shutil.rmtree(self.log_dir, ignore_errors=False, onerror=None)
        print("Removing directory %s and all contents." % self.save_dir)
        shutil.rmtree(self.save_dir, ignore_errors=False, onerror=None)

        print("Resetting %s and %s." % (self.log_dir, self.save_dir))
        os.mkdir(self.log_dir)
        os.mkdir(self.save_dir)

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.out_fc(x)

        return x


# Cell
def resnet18(pretrained=False, **kwargs):
    """Constructs a ResNet-18 model."""
    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet18']), strict=False)
    return model


def resnet34(pretrained=False, **kwargs):
    """Constructs a ResNet-34 model."""
    model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet34']), strict=False)
    return model


def resnet50(pretrained=False, **kwargs):
    """Constructs a ResNet-50 model."""
    model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet50']), strict=False)
    return model


def resnet101(pretrained=False, **kwargs):
    """Constructs a ResNet-101 model."""
    model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet101']), strict=False)
    return model


def resnet152(pretrained=False, **kwargs):
    """Constructs a ResNet-152 model."""
    model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet152']), strict=False)
    return model
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_resnet.ipynb (unless otherwise specified). # Cell # Cell Return a 3x3 convolution taking in `in_planes` filters and outputting        `out_planes` filters with padding and stride `stride`. # Cell Return a 1x1 convolution taking in `in_planes` filters and outputting        `out_planes` filters with padding and stride `stride`. # Cell The basic building block for ResNets, encompassing the residual connection. Takes in        `inplanes` number of input filters, outputs `planes` number of output filters, with        stride `stride` on the first 3x3 conv, and an optional downsampling (`nn.Module`)        on the residual output via the `downsample` parameter. # Cell The bottleneck building block for ResNets, encompassing the residual connection. Takes in        `inplanes` number of input filters, outputs `planes` number of output filters, with        stride `stride` on the first 3x3 conv, and an optional downsampling (`nn.Module`)        on the residual output via the `downsample` parameter. # Cell Constructs a ResNet using a block specification and number of layers. Also specifies where to        output training logs and model/system state. # Cell Constructs a ResNet-18 model. Constructs a ResNet-34 model. Constructs a ResNet-50 model. Constructs a ResNet-101 model. Constructs a ResNet-152 model.