-
Notifications
You must be signed in to change notification settings - Fork 19
/
autoregressive.py
243 lines (208 loc) · 7.75 KB
/
autoregressive.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
r"""Autoregressive flows and transformations."""
__all__ = [
'MaskedAutoregressiveTransform',
'MAF',
]
import torch
import torch.nn as nn
from functools import partial
from math import ceil, prod
from torch import Tensor, LongTensor, Size
from torch.distributions import Transform
from typing import *
from .core import *
from .gaussianization import ElementWiseTransform
from ..distributions import DiagNormal
from ..transforms import *
from ..nn import MaskedMLP
from ..utils import broadcast, unpack
class MaskedAutoregressiveTransform(LazyTransform):
r"""Creates a lazy masked autoregressive transformation.
See also:
:class:`zuko.transforms.AutoregressiveTransform`
References:
| Masked Autoregressive Flow for Density Estimation (Papamakarios et al., 2017)
| https://arxiv.org/abs/1705.07057
Arguments:
features: The number of features.
context: The number of context features.
passes: The number of sequential passes for the inverse transformation. If
:py:`None`, use the number of features instead, making the transformation
fully autoregressive. Coupling corresponds to :py:`passes=2`.
order: The feature ordering. If :py:`None`, use :py:`range(features)` instead.
univariate: The univariate transformation constructor.
shapes: The shapes of the univariate transformation parameters.
kwargs: Keyword arguments passed to :class:`zuko.nn.MaskedMLP`.
Example:
>>> t = MaskedAutoregressiveTransform(3, 4)
>>> t
MaskedAutoregressiveTransform(
(base): MonotonicAffineTransform()
(order): [0, 1, 2]
(hyper): MaskedMLP(
(0): MaskedLinear(in_features=7, out_features=64, bias=True)
(1): ReLU()
(2): MaskedLinear(in_features=64, out_features=64, bias=True)
(3): ReLU()
(4): MaskedLinear(in_features=64, out_features=6, bias=True)
)
)
>>> x = torch.randn(3)
>>> x
tensor([-0.9485, 1.5290, 0.2018])
>>> c = torch.randn(4)
>>> y = t(c)(x)
>>> t(c).inv(y)
tensor([-0.9485, 1.5290, 0.2018])
"""
def __new__(
cls,
features: int = None,
context: int = 0,
passes: int = None,
order: LongTensor = None,
*args,
**kwargs,
) -> LazyTransform:
if features is None or features > 1:
return super().__new__(cls)
else:
return ElementWiseTransform(features, context, *args, **kwargs)
def __init__(
self,
features: int,
context: int = 0,
passes: int = None,
order: LongTensor = None,
univariate: Callable[..., Transform] = MonotonicAffineTransform,
shapes: Sequence[Size] = ((), ()),
**kwargs,
):
super().__init__()
# Univariate transformation
self.univariate = univariate
self.shapes = shapes
self.total = sum(prod(s) for s in shapes)
# Adjacency
self.register_buffer('order', None)
if passes is None:
passes = features
if order is None:
order = torch.arange(features)
else:
order = torch.as_tensor(order)
self.passes = min(max(passes, 1), features)
self.order = torch.div(order, ceil(features / self.passes), rounding_mode='floor')
in_order = torch.cat((self.order, torch.full((context,), -1)))
out_order = torch.repeat_interleave(self.order, self.total)
adjacency = out_order[:, None] > in_order
# Hyper network
self.hyper = MaskedMLP(adjacency, **kwargs)
def extra_repr(self) -> str:
base = self.univariate(*map(torch.randn, self.shapes))
order = self.order.tolist()
if len(order) > 10:
order = order[:5] + [...] + order[-5:]
order = str(order).replace('Ellipsis', '...')
return '\n'.join([
f'(base): {base}',
f'(order): {order}',
])
def meta(self, c: Tensor, x: Tensor) -> Transform:
if c is not None:
x = torch.cat(broadcast(x, c, ignore=1), dim=-1)
phi = self.hyper(x)
phi = phi.unflatten(-1, (-1, self.total))
phi = unpack(phi, self.shapes)
return DependentTransform(self.univariate(*phi), 1)
def forward(self, c: Tensor = None) -> Transform:
return AutoregressiveTransform(partial(self.meta, c), self.passes)
class MAF(Flow):
r"""Creates a masked autoregressive flow (MAF).
References:
| Masked Autoregressive Flow for Density Estimation (Papamakarios et al., 2017)
| https://arxiv.org/abs/1705.07057
Arguments:
features: The number of features.
context: The number of context features.
transforms: The number of autoregressive transformations.
randperm: Whether features are randomly permuted between transformations or not.
If :py:`False`, features are in ascending (descending) order for even
(odd) transformations.
kwargs: Keyword arguments passed to :class:`MaskedAutoregressiveTransform`.
Example:
>>> flow = MAF(3, 4, transforms=3)
>>> flow
MAF(
(transform): LazyComposedTransform(
(0): MaskedAutoregressiveTransform(
(base): MonotonicAffineTransform()
(order): [0, 1, 2]
(hyper): MaskedMLP(
(0): MaskedLinear(in_features=7, out_features=64, bias=True)
(1): ReLU()
(2): MaskedLinear(in_features=64, out_features=64, bias=True)
(3): ReLU()
(4): MaskedLinear(in_features=64, out_features=6, bias=True)
)
)
(1): MaskedAutoregressiveTransform(
(base): MonotonicAffineTransform()
(order): [2, 1, 0]
(hyper): MaskedMLP(
(0): MaskedLinear(in_features=7, out_features=64, bias=True)
(1): ReLU()
(2): MaskedLinear(in_features=64, out_features=64, bias=True)
(3): ReLU()
(4): MaskedLinear(in_features=64, out_features=6, bias=True)
)
)
(2): MaskedAutoregressiveTransform(
(base): MonotonicAffineTransform()
(order): [0, 1, 2]
(hyper): MaskedMLP(
(0): MaskedLinear(in_features=7, out_features=64, bias=True)
(1): ReLU()
(2): MaskedLinear(in_features=64, out_features=64, bias=True)
(3): ReLU()
(4): MaskedLinear(in_features=64, out_features=6, bias=True)
)
)
)
(base): Unconditional(DiagNormal(loc: torch.Size([3]), scale: torch.Size([3])))
)
>>> c = torch.randn(4)
>>> x = flow(c).sample()
>>> x
tensor([-1.7154, -0.4401, 0.7505])
>>> flow(c).log_prob(x)
tensor(-4.4630, grad_fn=<AddBackward0>)
"""
def __init__(
self,
features: int,
context: int = 0,
transforms: int = 3,
randperm: bool = False,
**kwargs,
):
orders = [
torch.arange(features),
torch.flipud(torch.arange(features)),
]
transforms = [
MaskedAutoregressiveTransform(
features=features,
context=context,
order=torch.randperm(features) if randperm else orders[i % 2],
**kwargs,
)
for i in range(transforms)
]
base = Unconditional(
DiagNormal,
torch.zeros(features),
torch.ones(features),
buffer=True,
)
super().__init__(transforms, base)