CoolFace
Apppublic

tidalove/adain

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
Network.py74 linesDownload Raw Back to root
1import torch.nn as nn2 3vgg19_cfg = [3, 64, 64, "M", 128, 128, "M", 256, 256, 256, 256, "M", 512, 512, 512, 512, "M", 512, 512, 512, 512, "M"]4decoder_cfg = [512, 256, "U", 256, 256, 256, 128, "U", 128, 64, 'U', 64, 3]5 6def vgg19(weights=None):7    """8    Build vgg19 network. Load weights if weights are given.9 10    Args:11        weights (dict): vgg19 pretrained weights12 13    Return:14        layers (nn.Sequential): vgg19 layers15    """16 17    modules = make_block(vgg19_cfg)18    modules = [nn.Conv2d(3, 3, kernel_size=1)] + list(modules.children())19    layers = nn.Sequential(*modules)20 21    if weights:22        layers.load_state_dict(weights)23    24    return layers25 26 27def decoder(weights=None):28    """29    Build decoder network. Load weights if weights are given.30 31    Args:32        weights (dict): decoder pretrained weights33 34    Return:35        layers (nn.Sequential): decoder layers36    """37 38    modules = make_block(decoder_cfg)39    layers = nn.Sequential(*list(modules.children())[:-1]) # no relu at the last layer40 41    if weights:42        layers.load_state_dict(weights)43 44    return layers45 46 47def make_block(config):48    """49    Helper function for building blocks of convolutional layers.50 51    Args:52        config (list): List of layer configs. "M"53            "M" - Max pooling layer. 54            "U" - Upsampling layer. 55            i (int) - Convolutional layer (i filters) plus ReLU activation. 56    Return:57        layers (nn.Sequential): block layers58    """59    layers = []60    in_channels = config[0]61    62    for c in config[1:]:63        if c == "M":64            layers.append(nn.MaxPool2d(kernel_size=2, stride=2, padding=0))65        elif c == "U":66            layers.append(nn.Upsample(scale_factor=2, mode='nearest'))67        else:68            assert(isinstance(c, int))69            layers.append(nn.Conv2d(in_channels, c, kernel_size=3, padding=1))70            layers.append(nn.ReLU(inplace=True))71            in_channels = c72 73    return nn.Sequential(*layers)74