Module flowcon.nn.nets.invertible_densenet
Classes
class DenseNet (dimension, densenet_depth: int = 2, densenet_growth: int = 16, activation_function: Union[str, Callable] = 'CLipSwish', lip_coeff: float = 0.98, n_lipschitz_iters: int = 5, **kwargs)
-
Provides a Lipschitz contiuous network g(x) with a fixed lipschitz constant.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Expand source code
class DenseNet(_DenseNet): """ Provides a Lipschitz contiuous network g(x) with a fixed lipschitz constant. """ def __init__(self, dimension, densenet_depth: int = 2, densenet_growth: int = 16, activation_function: Union[str, Callable] = "CLipSwish", lip_coeff: float = 0.98, n_lipschitz_iters: int = 5, **kwargs): super().__init__(dimension=dimension, densenet_depth=densenet_depth, densenet_growth=densenet_growth, activation_function=activation_function, lip_coeff=lip_coeff, n_lipschitz_iters=n_lipschitz_iters) if len(kwargs) > 0: logger.warning("Unused kwargs for {}: {}".format(self.__class__.__name__, pformat(kwargs))) self.dense_net, self.densenet_final_layer_dim = self.build_densenet(self.dimension, self.densenet_depth, self.densenet_growth) def forward(self, x, context=None): assert context is None, "Context not supported for this Class." return self.dense_net(x)
Ancestors
- flowcon.nn.nets.invertible_densenet._DenseNet
- torch.nn.modules.module.Module
Class variables
var call_super_init : bool
var dump_patches : bool
var training : bool
Methods
def forward(self, x, context=None) ‑> 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.
class InputConditionalDenseNet (dimension, context_features, densenet_depth, densenet_growth=16, c_embed_hidden_sizes=(128, 128, 10), activation_function=flowcon.nn.nets.activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs)
-
Provides a Lipschitz contiuous network g(x;t) = h(concat[x, f(c)]) with a fixed lipschitz constant. The network h(x;t) is a DenseNet and Lipschitz Continuous w.r.t. x. the network f provides an embedding of the context.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Expand source code
class InputConditionalDenseNet(_DenseNet): """ Provides a Lipschitz contiuous network g(x;t) = h(concat[x, f(c)]) with a fixed lipschitz constant. The network h(x;t) is a DenseNet and Lipschitz Continuous w.r.t. x. the network f provides an embedding of the context. """ def __init__(self, dimension, context_features, densenet_depth, densenet_growth=16, c_embed_hidden_sizes=(128, 128, 10), activation_function=activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs ): super().__init__(dimension=dimension, densenet_depth=densenet_depth, densenet_growth=densenet_growth, activation_function=activation_function, lip_coeff=lip_coeff, n_lipschitz_iters=n_lipschitz_iters) if len(kwargs) > 0: logger.warning("Unused kwargs for class '{}': \n {}".format(self.__class__.__name__, pformat(kwargs))) self.context_features = context_features self.c_embed_hidden_sizes = c_embed_hidden_sizes self.bn = torch.nn.BatchNorm1d(self.context_features) self.dense_net, self.densenet_final_layer_dim = self.build_densenet( total_in_channels=self.dimension + self.c_embed_hidden_sizes[-1], densenet_growth=densenet_growth, densenet_depth=densenet_depth, include_last_layer=True) self.context_embedding_net = MLP((self.context_features,), (self.c_embed_hidden_sizes[-1],), hidden_sizes=self.c_embed_hidden_sizes, activation=torch.nn.SiLU()) def forward(self, inputs, context=None): context = self.bn(context) context_embedding = self.context_embedding_net(context) concat_inputs = torch.cat([inputs, context_embedding], -1) outputs = self.dense_net(concat_inputs) return outputs
Ancestors
- flowcon.nn.nets.invertible_densenet._DenseNet
- torch.nn.modules.module.Module
Class variables
var call_super_init : bool
var dump_patches : bool
var training : bool
Methods
def forward(self, inputs, context=None) ‑> 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.
class LastLayerAttention (dimension, context_features, value_dim, hidden_sizes=(64, 64), activation=Swish())
-
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 LastLayerAttention(torch.nn.Module): def __init__(self, dimension, context_features, value_dim, hidden_sizes=(64, 64), activation=activations.Swish()): super().__init__() self.dimension = dimension self.context_features = context_features self.hidden_sizes = hidden_sizes self.value_dim = value_dim self.activation = activation self.bias_net = MLP((self.context_features,), (self.dimension,), hidden_sizes=self.hidden_sizes, activation=self.activation) self.weight_network = MLP((self.context_features,), (self.dimension, self.value_dim), hidden_sizes=self.hidden_sizes, activation=self.activation) def attention(self, context, values): presoftmax = self.weight_network(context) # .view(-1, self.dimension, self.num_heads) post_softmax = torch.nn.functional.softmax(presoftmax, dim=-1) weights = torch.bmm(post_softmax, values).squeeze() return weights + self.bias_net(context)
Ancestors
- torch.nn.modules.module.Module
Class variables
var call_super_init : bool
var dump_patches : bool
var training : bool
Methods
def attention(self, context, values)
def forward(self, *input: Any) ‑> None
-
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.
class LastLayerConditionalDenseNet (dimension, context_features, densenet_depth, densenet_growth=16, last_layer_hidden_sizes=(64, 64), activation_function=flowcon.nn.nets.activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs)
-
Provides a Lipschitz contiuous network g(x;c) = h(x;t) with a fixed lipschitz constant. The network h(x;c) is a DenseNet. Let xϵR^d. For a unconditional DenseNet the last layer is given by Az, where zϵR^k with k>d is a higher dimensional embedding and AϵR^(d imes k) is a matrix with spectral norm <1. For making this last layer conditional, we instead parameterize A(c) with a hypernetwork. We further pass each row through a softmax (making A row stochastic), such that the Lipschitz constant of remains unchanged.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Expand source code
class LastLayerConditionalDenseNet(_DenseNet): """ Provides a Lipschitz contiuous network g(x;c) = h(x;t) with a fixed lipschitz constant. The network h(x;c) is a DenseNet. Let xϵR^d. For a unconditional DenseNet the last layer is given by Az, where zϵR^k with k>d is a higher dimensional embedding and AϵR^(d\times k) is a matrix with spectral norm <1. For making this last layer conditional, we instead parameterize A(c) with a hypernetwork. We further pass each row through a softmax (making A row stochastic), such that the Lipschitz constant of remains unchanged. """ def __init__(self, dimension, context_features, densenet_depth, densenet_growth=16, last_layer_hidden_sizes=(64, 64), activation_function=activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs ): super().__init__(dimension=dimension, densenet_depth=densenet_depth, densenet_growth=densenet_growth, activation_function=activation_function, lip_coeff=lip_coeff, n_lipschitz_iters=n_lipschitz_iters) if len(kwargs) > 0: logger.warning("Unused kwargs for class '{}': \n {}".format(self.__class__.__name__, pformat(kwargs))) self.context_features = context_features self.last_layer_hidden_sizes = last_layer_hidden_sizes self.bn = torch.nn.BatchNorm1d(self.context_features) self.dense_net, self.densenet_final_layer_dim = self.build_densenet(total_in_channels=self.dimension, densenet_growth=densenet_growth, densenet_depth=densenet_depth, include_last_layer=False) self.custom_attention = LastLayerAttention(dimension=self.dimension, context_features=self.context_features, value_dim=self.densenet_final_layer_dim, hidden_sizes=self.last_layer_hidden_sizes) def forward(self, inputs, context=None): context = self.bn(context) values_weights = self.dense_net(inputs).unsqueeze(-1) weights = self.custom_attention.attention(context, values_weights) return weights
Ancestors
- flowcon.nn.nets.invertible_densenet._DenseNet
- torch.nn.modules.module.Module
Class variables
var call_super_init : bool
var dump_patches : bool
var training : bool
Methods
def forward(self, inputs, context=None) ‑> 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.
class MixedConditionalDenseNet (dimension, context_features, densenet_depth, densenet_growth=16, last_layer_hidden_sizes=(64, 64), c_embed_hidden_sizes=(32, 32, 10), activation_function=flowcon.nn.nets.activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs)
-
Combination of LastLayerConditionalDenseNet and InputConditionalDenseNet, i.e. both the first and last layer of the densenet are conditional.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Expand source code
class MixedConditionalDenseNet(_DenseNet): """ Combination of LastLayerConditionalDenseNet and InputConditionalDenseNet, i.e. both the first and last layer of the densenet are conditional. """ def __init__(self, dimension, context_features, densenet_depth, densenet_growth=16, last_layer_hidden_sizes=(64, 64), c_embed_hidden_sizes=(32, 32, 10), activation_function=activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs ): super().__init__(dimension=dimension, densenet_depth=densenet_depth, densenet_growth=densenet_growth, activation_function=activation_function, lip_coeff=lip_coeff, n_lipschitz_iters=n_lipschitz_iters) if len(kwargs) > 0: logger.warning("Unused kwargs for class '{}': \n {}".format(self.__class__.__name__, pformat(kwargs))) self.context_features = context_features self.c_embed_hidden_sizes = c_embed_hidden_sizes self.last_layer_hidden_sizes = last_layer_hidden_sizes self.output_channels = self.calc_output_channels(self.activation, self.densenet_growth) self.bn = torch.nn.BatchNorm1d(self.context_features) self.dense_net, self.densenet_final_layer_dim = self.build_densenet( total_in_channels=self.dimension + self.c_embed_hidden_sizes[-1], densenet_growth=densenet_growth, densenet_depth=densenet_depth, include_last_layer=False) self.custom_attention = LastLayerAttention(dimension=self.dimension, context_features=self.context_features, value_dim=self.densenet_final_layer_dim, hidden_sizes=self.last_layer_hidden_sizes) self.context_embedding_net = MLP((self.context_features,), (self.c_embed_hidden_sizes[-1],), hidden_sizes=self.c_embed_hidden_sizes, activation=torch.nn.SiLU()) def forward(self, inputs, context=None): context = self.bn(context) context_embedding = self.context_embedding_net(context) concat_inputs = torch.cat([inputs, context_embedding], -1) values_weights = self.dense_net(concat_inputs).unsqueeze(-1) weights = self.custom_attention.attention(context, values_weights) return weights
Ancestors
- flowcon.nn.nets.invertible_densenet._DenseNet
- torch.nn.modules.module.Module
Class variables
var call_super_init : bool
var dump_patches : bool
var training : bool
Methods
def forward(self, inputs, context=None) ‑> 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.
class MultiplicativeAndInputConditionalDenseNet (dimension, context_features, densenet_depth, densenet_growth=16, c_embed_hidden_sizes=(128, 128, 10), m_embed_hidden_sizes=(128, 128), activation_function=flowcon.nn.nets.activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs)
-
Provides a Lipschitz contiuous network g(x;c) = φ(c) h(x;t) with a fixed lipschitz constant. The network h(x;c) is an InputConditionalDenseNet and Lipschitz Continuous w.r.t. x, and φ(c) \in (0,1), making g Lipschitz Continuous w.r.t. x.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Expand source code
class MultiplicativeAndInputConditionalDenseNet(_DenseNet): """ Provides a Lipschitz contiuous network g(x;c) = φ(c) h(x;t) with a fixed lipschitz constant. The network h(x;c) is an InputConditionalDenseNet and Lipschitz Continuous w.r.t. x, and φ(c) \in (0,1), making g Lipschitz Continuous w.r.t. x. """ def __init__(self, dimension, context_features, densenet_depth, densenet_growth=16, c_embed_hidden_sizes=(128, 128, 10), m_embed_hidden_sizes=(128, 128), activation_function=activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs ): super().__init__(dimension=dimension, densenet_depth=densenet_depth, densenet_growth=densenet_growth, activation_function=activation_function, lip_coeff=lip_coeff, n_lipschitz_iters=n_lipschitz_iters) if len(kwargs) > 0: logger.warning("Unused kwargs for class '{}': \n {}".format(self.__class__.__name__, pformat(kwargs))) self.context_features = context_features self.c_embed_hidden_sizes = c_embed_hidden_sizes self.m_embed_hidden_sizes = m_embed_hidden_sizes self.bn = torch.nn.BatchNorm1d(self.context_features) self.dense_net, self.densenet_final_layer_dim = self.build_densenet( total_in_channels=self.dimension + self.c_embed_hidden_sizes[-1], densenet_growth=densenet_growth, densenet_depth=densenet_depth, include_last_layer=True) self.factor_net = MLP((self.context_features,), (1,), hidden_sizes=self.m_embed_hidden_sizes, activation=torch.nn.SiLU()) self.embedding = MLP((self.context_features,), (self.c_embed_hidden_sizes[-1],), hidden_sizes=self.c_embed_hidden_sizes, activation=torch.nn.SiLU()) def forward(self, inputs, context=None): context = self.bn(context) factor = self.factor_net(context) context_embedding = self.embedding(context) concat_inputs = torch.cat([inputs, context_embedding], -1) outputs = torch.nn.functional.tanh(factor) * self.dense_net(concat_inputs) return outputs
Ancestors
- flowcon.nn.nets.invertible_densenet._DenseNet
- torch.nn.modules.module.Module
Class variables
var call_super_init : bool
var dump_patches : bool
var training : bool
Methods
def forward(self, inputs, context=None) ‑> 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.
class MultiplicativeConditionalDenseNet (dimension, context_features, densenet_depth, densenet_growth=16, c_embed_hidden_sizes=(128, 128, 10), m_embed_hidden_sizes=(128, 128), activation_function=flowcon.nn.nets.activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs)
-
Provides a Lipschitz contiuous network g(x;c) = φ(c) h(x;t) with a fixed lipschitz constant. The network h(x;c) is an InputConditionalDenseNet and Lipschitz Continuous w.r.t. x, and φ(c) \in (0,1), making g Lipschitz Continuous w.r.t. x.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
Expand source code
class MultiplicativeConditionalDenseNet(_DenseNet): """ Provides a Lipschitz contiuous network g(x;c) = φ(c) h(x;t) with a fixed lipschitz constant. The network h(x;c) is an InputConditionalDenseNet and Lipschitz Continuous w.r.t. x, and φ(c) \in (0,1), making g Lipschitz Continuous w.r.t. x. """ def __init__(self, dimension, context_features, densenet_depth, densenet_growth=16, c_embed_hidden_sizes=(128, 128, 10), m_embed_hidden_sizes=(128, 128), activation_function=activations.Swish, lip_coeff=0.98, n_lipschitz_iters=5, **kwargs ): super().__init__(dimension=dimension, densenet_depth=densenet_depth, densenet_growth=densenet_growth, activation_function=activation_function, lip_coeff=lip_coeff, n_lipschitz_iters=n_lipschitz_iters) if len(kwargs) > 0: logger.warning("Unused kwargs for class '{}': \n {}".format(self.__class__.__name__, pformat(kwargs))) self.context_features = context_features self.c_embed_hidden_sizes = c_embed_hidden_sizes self.m_embed_hidden_sizes = m_embed_hidden_sizes self.bn = torch.nn.BatchNorm1d(self.context_features) self.dense_net, self.densenet_final_layer_dim = self.build_densenet( total_in_channels=self.dimension + self.c_embed_hidden_sizes[-1], densenet_growth=densenet_growth, densenet_depth=densenet_depth, include_last_layer=True) self.factor_net = MLP((self.context_features,), (1,), hidden_sizes=self.m_embed_hidden_sizes, activation=torch.nn.SiLU()) def forward(self, inputs, context=None): context = self.bn(context) factor = self.factor_net(context) outputs = torch.nn.functional.tanh(factor) * self.dense_net(inputs) return outputs
Ancestors
- flowcon.nn.nets.invertible_densenet._DenseNet
- torch.nn.modules.module.Module
Class variables
var call_super_init : bool
var dump_patches : bool
var training : bool
Methods
def forward(self, inputs, context=None) ‑> 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.