tfep.nn.transformers.spline.NeuralSplineTransformer
- class tfep.nn.transformers.spline.NeuralSplineTransformer(x0: Tensor, xf: Tensor, n_bins: int, y0: Tensor | None = None, yf: Tensor | None = None, circular: bool = False, identity_boundary_slopes: bool = False, learn_lower_bound: bool = False, learn_upper_bound: bool = False, min_bin_size: float = 0.0001, min_slope: float = 0.0001)[source]
Bases:
MAFTransformerNeural spline transformer module for autoregressive normalizing flows.
This is an implementation of the neural spline transformer proposed in [1]. Using the therminology in [1], the spline function is defined from K+1 knots (x, y) that give rise to K bins. The domain of the spline for feature
iis in the intervalx0[i] <= x[i] <= x0[i] + cumsum(widths). All values outside this interval are transformed linearly following the slopes of the first and last knot.Optionally, the spline domain can be learned. If only one boundary is learned, this is done through a parameter (made positive through an exponential) provided by the conditioner that scales the domain interval. The same scaling parameter is applied to the input and output domains. If both boundaries are learned, another parameter shifting the domain interval is required from the conditioner, which is also applied identically to both the input and output domains.
This class can also implement circular splines [2] for periodic degrees of freedom. The periodic DOFs do not take slopes for the last knot (which is set to be equal to that of the first), but take instead a shift parameter so that the final transformation is
:math:`y = mathrm{spline}((x - x_0 + phi) % p + x_0)
where \(x_0\) correspond to the
x0parameter for that DOF, \(p\) is the period, and \(\phi\) is the shift. With circular splines, learning the spline domain is not supported.See also
nets.functions.transformer.neural_spline_transformerReferences
- [1] Durkan C, Bekasov A, Murray I, Papamakarios G. Neural spline flows.
arXiv preprint arXiv:1906.04032. 2019 Dec 12.
- [2] Rezende DJ, et al. Normalizing flows on tori and spheres. arXiv preprint
arXiv:2002.02428. 2020 Feb 6.
- __init__(x0: Tensor, xf: Tensor, n_bins: int, y0: Tensor | None = None, yf: Tensor | None = None, circular: bool = False, identity_boundary_slopes: bool = False, learn_lower_bound: bool = False, learn_upper_bound: bool = False, min_bin_size: float = 0.0001, min_slope: float = 0.0001)[source]
Constructor.
- Parameters:
x0 (torch.Tensor) – Shape
(n_features,). Position of the first of the K+1 knots determining the positions of the K bins for the input. Iflearn_lower_boundisTrue, this is the starting value.xf (torch.Tensor) – Shape
(n_features,). Position of the last of the K+1 knots determining the positions of the K bins for the input. Iflearn_upper_boundisTrue, this is the starting value.n_bins (int) – Total number of bins (i.e., K).
y0 (torch.Tensor, optional) – Shape
(n_features,). Position of the first of the K+1 knots determining the positions of the K bins for the output. If not passed,x0is taken. Iflearn_lower_boundisTrue, this is the starting value.yf (torch.Tensor, optional) – Shape
(n_features,). Position of the last of the K+1 knots determining the positions of the K bins for the output. If not passed,xfis taken. Iflearn_upper_boundisTrue, this is the starting value.circular (bool, optional) – If
True, the features are treated as periodic. In this case,y0andyfmust correspond tox0andxf.identity_boundary_slopes (bool, optional) – If
True, the slopes at the boundaries of the domain are forced to 1 so that the spline can implement the identity function outside its domain. Note that this will be true only ifx0 == y0andxf == yf.learn_lower_bound (bool, optional) – If
True, the lower limit of the spline domain (both input and output) is learned. Default isFalse.learn_upper_bound (bool, optional) – If
True, the upper limit of the spline domain (both input and output) is learned. Default isFalse.min_bin_size (float, optional) – The minimum possible bin size (i.e., width and height) for numerical stability.
min_slope (float, optional) – The minimum possible slope for numerical stability.
Methods
__init__(x0, xf, n_bins[, y0, yf, circular, ...])Constructor.
add_module(name, module)Add a child module to the current module.
apply(fn)Apply
fnrecursively to every submodule (as returned by.children()) as well as self.bfloat16()Casts all floating point parameters and buffers to
bfloat16datatype.buffers([recurse])Return an iterator over module buffers.
children()Return an iterator over immediate children modules.
compile(*args, **kwargs)Compile this Module's forward using
torch.compile().cpu()Move all model parameters and buffers to the CPU.
cuda([device])Move all model parameters and buffers to the GPU.
double()Casts all floating point parameters and buffers to
doubledatatype.eval()Set the module in evaluation mode.
extra_repr()Set the extra representation of the module.
float()Casts all floating point parameters and buffers to
floatdatatype.forward(x, parameters)Apply the transformation to the input.
get_buffer(target)Return the buffer given by
targetif it exists, otherwise throw an error.get_degrees_out(degrees_in)Returns the degrees associated to the conditioner's output.
get_extra_state()Return any extra state to include in the module's state_dict.
get_identity_parameters(n_features)Return the value of the parameters that makes this the identity function.
get_parameter(target)Return the parameter given by
targetif it exists, otherwise throw an error.get_submodule(target)Return the submodule given by
targetif it exists, otherwise throw an error.half()Casts all floating point parameters and buffers to
halfdatatype.inverse(y, parameters)Inverse function.
ipu([device])Move all model parameters and buffers to the IPU.
load_state_dict(state_dict[, strict, assign])Copy parameters and buffers from
state_dictinto this module and its descendants.modules()Return an iterator over all modules in the network.
mtia([device])Move all model parameters and buffers to the MTIA.
named_buffers([prefix, recurse, ...])Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
named_children()Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
named_modules([memo, prefix, remove_duplicate])Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
named_parameters([prefix, recurse, ...])Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
parameters([recurse])Return an iterator over module parameters.
register_backward_hook(hook)Register a backward hook on the module.
register_buffer(name, tensor[, persistent])Add a buffer to the module.
register_forward_hook(hook, *[, prepend, ...])Register a forward hook on the module.
register_forward_pre_hook(hook, *[, ...])Register a forward pre-hook on the module.
register_full_backward_hook(hook[, prepend])Register a backward hook on the module.
register_full_backward_pre_hook(hook[, prepend])Register a backward pre-hook on the module.
register_load_state_dict_post_hook(hook)Register a post-hook to be run after module's
load_state_dict()is called.register_load_state_dict_pre_hook(hook)Register a pre-hook to be run before module's
load_state_dict()is called.register_module(name, module)Alias for
add_module().register_parameter(name, param)Add a parameter to the module.
register_state_dict_post_hook(hook)Register a post-hook for the
state_dict()method.register_state_dict_pre_hook(hook)Register a pre-hook for the
state_dict()method.requires_grad_([requires_grad])Change if autograd should record operations on parameters in this module.
set_extra_state(state)Set extra state contained in the loaded state_dict.
set_submodule(target, module)Set the submodule given by
targetif it exists, otherwise throw an error.share_memory()See
torch.Tensor.share_memory_().state_dict(*args[, destination, prefix, ...])Return a dictionary containing references to the whole state of the module.
to(*args, **kwargs)Move and/or cast the parameters and buffers.
to_empty(*, device[, recurse])Move the parameters and buffers to the specified device without copying storage.
train([mode])Set the module in training mode.
type(dst_type)Casts all parameters and buffers to
dst_type.xpu([device])Move all model parameters and buffers to the XPU.
zero_grad([set_to_none])Reset gradients of all model parameters.
Attributes
T_destinationcall_super_initdump_patchesNumber of parameters needed by the transformer for each feature.
training- forward(x: Tensor, parameters: Tensor) tuple[Tensor][source]
Apply the transformation to the input.
- Parameters:
x (torch.Tensor) – Shape
(batch_size, n_features). Input features. Periodic features will be mapped within their domain before being transformed. Non-periodic features outside their domain will be transformed linearly.parameters (torch.Tensor) – Shape:
(batch_size, n_parameters_per_feat*n_features). For standard splines,n_parameters_per_featis3*n_bins + 1. Ifidentity_boundary_slopes=True, the spline requires 1 less parameter per feature in circular splines and 2 less for standard splines since the slopes of the boundary knots are fixed. If the lower and upper bound of the spline domain are learnable, they each require 1 extra parameter per feature.The order of the parameters should allow reshaping the array to
(batch_size, n_parameters_per_feat, n_features), whereparameters[b, :n_bins, i]andparameters[b, n_bins:2*n_bins, i]are the widths and heights of the bins for featurex[b, i].parameters[b, 2*n_bins:3*n_bins +- 1, i]are the slopes (the+- 1is due to the values ofidentity_boundary_slopesandcircular). For circular splinesparameters[b, -1, i]is the shift parameter. When the spline domain is learnable,parameters[b, -1, i]is instead the domain scaling parameter. Finally, when both spline domain bounds are learnableparameters[b, -2, i]is the domain shifting parameter.As in the original paper, the passed widths and heights go through a
softmaxfunction and the slopes through asoftplusfunction to generate widths/heights that are positive and slopes that make a monotonic increasing transformation.
- Returns:
y (torch.Tensor) – Shape
(batch_size, n_features). Output.log_det_J (torch.Tensor) – Shape
(batch_size,). The logarithm of the absolute value of the Jacobian determinantdy / dx.
- get_degrees_out(degrees_in: Tensor) Tensor[source]
Returns the degrees associated to the conditioner’s output.
- Parameters:
degrees_in (torch.Tensor) – Shape
(n_transformed_features,). The autoregressive degrees associated to the features provided as input to the transformer.- Returns:
degrees_out – Shape
(n_parameters,). The autoregressive degrees associated to each output of the conditioner that will be fed to the transformer as parameters.- Return type:
torch.Tensor
- get_identity_parameters(n_features: int) Tensor[source]
Return the value of the parameters that makes this the identity function.
Note that if
x0 != y0ory0 != y1it is impossible to implement the identity using this transformer, and the returned parameters will be those to map linearly the input domain ofxto the output ofy.This can be used to initialize the normalizing flow to perform the identity transformation.
- Parameters:
n_features (int) – The dimension of the input vector of the transformer.
- Returns:
parameters – Shape
(n_parameters,). The parameters for the identity function.- Return type:
torch.Tensor
- inverse(y: Tensor, parameters: Tensor) tuple[Tensor][source]
Inverse function.
See
forwardfor the parameters description.
- property n_parameters_per_feature: int
Number of parameters needed by the transformer for each feature.
- Type:
int