Module flowcon.nn.nets.lipschitz_dense

https://github.com/yperugachidiaz/invertible_densenets/blob/master/lib/layers/dense_layer.py

MIT License

Copyright (c) 2019 Ricky Tian Qi Chen Copyright (c) 2021 Yura Perugachi-Diaz

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Classes

class LipschitzDenseLayer (network, learnable_concat=False, lip_coeff=0.98)

Base class for all neural network modules.

Your models should also subclass this class.

Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes::

import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

Submodules assigned in this way will be registered, and will have their parameters converted too when you call :meth:to, etc.

Note

As per the example above, an __init__() call to the parent class must be made before assignment on the child.

:ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool

Initialize internal Module state, shared by both nn.Module and ScriptModule.

Expand source code
class LipschitzDenseLayer(torch.nn.Module):
    def __init__(self, network, learnable_concat=False, lip_coeff=0.98):
        super(LipschitzDenseLayer, self).__init__()
        self.network = network
        self.lip_coeff = lip_coeff

        if learnable_concat:
            self.K1_unnormalized = torch.nn.Parameter(torch.tensor([1.]))
            self.K2_unnormalized = torch.nn.Parameter(torch.tensor([1.]))
        else:
            self.register_buffer("K1_unnormalized", torch.tensor([1.]))
            self.register_buffer("K2_unnormalized", torch.tensor([1.]))

    def get_eta1_eta2(self, beta=0.1):
        eta1 = F.softplus(self.K1_unnormalized) + beta
        eta2 = F.softplus(self.K2_unnormalized) + beta
        divider = torch.sqrt(eta1 ** 2 + eta2 ** 2)

        eta1_normalized = (eta1 / divider) * self.lip_coeff
        eta2_normalized = (eta2 / divider) * self.lip_coeff
        return eta1_normalized, eta2_normalized

    def forward(self, x):
        out = self.network(x)
        eta1_normalized, eta2_normalized = self.get_eta1_eta2()
        return torch.cat([x * eta1_normalized, out * eta2_normalized], dim=1)

    def build_clone(self):
        class LipschitzDenseLayerClone(torch.nn.Module):
            def __init__(self, network, eta1, eta2):
                super(LipschitzDenseLayerClone, self).__init__()
                self.network = network
                self.eta1_normalized = eta1_normalized
                self.eta2_normalized = eta2_normalized

            def forward(self, x, concat=True):
                out = self.network(x)
                if concat:
                    return torch.cat([x * self.eta1_normalized, out * self.eta2_normalized], dim=1)
                else:
                    return x * self.eta1_normalized, out * self.eta2_normalized

        with torch.no_grad():
            eta1_normalized, eta2_normalized = self.get_eta1_eta2()
            return LipschitzDenseLayerClone(self.network.build_clone(), eta1_normalized, eta2_normalized)

    def build_jvp_net(self, x, concat=True):
        class LipschitzDenseLayerJVP(torch.nn.Module):
            def __init__(self, network, eta1_normalized, eta2_normalized):
                super(LipschitzDenseLayerJVP, self).__init__()
                self.network = network
                self.eta1_normalized = eta1_normalized
                self.eta2_normalized = eta2_normalized

            def forward(self, v):
                out = self.network(v)
                return torch.cat([v * self.eta1_normalized, out * self.eta2_normalized], dim=1)

        with torch.no_grad():
            eta1_normalized, eta2_normalized = self.get_eta1_eta2()
            network, out = self.network.build_jvp_net(x)
            if concat:
                y = torch.cat([x * eta1_normalized, out * eta2_normalized], dim=1)
                return LipschitzDenseLayerJVP(network, eta1_normalized, eta2_normalized), y
            else:
                return LipschitzDenseLayerJVP(network, eta1_normalized,
                                              eta2_normalized), x * eta1_normalized, out * eta2_normalized

Ancestors

  • torch.nn.modules.module.Module

Class variables

var call_super_init : bool
var dump_patches : bool
var training : bool

Methods

def build_clone(self)
def build_jvp_net(self, x, concat=True)
def forward(self, x) ‑> Callable[..., Any]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the :class:Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

def get_eta1_eta2(self, beta=0.1)