-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistributions.py
293 lines (217 loc) · 9.62 KB
/
distributions.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""
collection of useful distributions
the methods defined here should work with
unspecified batch shapes (so we can work readily with sequence data)
"""
from torch.distributions import Categorical, MixtureSameFamily, Normal, Independent
import math
import torch
# define some constants
CONST_SQRT_2 = math.sqrt(2)
CONST_INV_SQRT_2PI = 1 / math.sqrt(2 * math.pi)
CONST_INV_SQRT_2 = 1 / math.sqrt(2)
CONST_LOG_INV_SQRT_2PI = math.log(CONST_INV_SQRT_2PI)
CONST_LOG_SQRT_2PI_E = 0.5 * math.log(2 * math.pi * math.e)
# will be used for numerical stability
EPS = 1e-20
class Gaussian:
"""
a simple gaussian distribution
"""
def __init__(self, mu, sigma):
"""
Inputs:
mu (BxD): means - B is batch size and D is dim of the variable
var (BxD): standard deviations
"""
self.mu = mu
self.sigma = sigma
self.torch_dist = Independent(Normal(mu, sigma), reinterpreted_batch_ndims=1)
def probability(self, target, multiple_samples=False):
"""
calculates the probability of target under the distribution
Inputs:
target (BxD)
multiple_samples (boolean): whether probability to be computed for multiple samples, in this case the
number of samples is expected to be the first dimension
Outputs:
probs (Bx1)
"""
if not multiple_samples:
sigma = self.sigma
mu = self.mu
else:
n_samples = target.shape[0]
sigma = self.sigma.reshape(-1, *self.sigma.shape).repeat_interleave(n_samples, dim=0)
mu = self.mu.reshape(-1, *self.mu.shape).repeat_interleave(n_samples, dim=0)
# compute the individual probabilities of target under each gaussian
gaussian_probs = (1.0 / math.sqrt(2 * math.pi)) * torch.exp(
-0.5 * ((target - mu) / sigma) ** 2) / sigma
# add a small value for numerical stability
gaussian_probs += torch.ones_like(gaussian_probs) * EPS
# multiply uni-variate probabilities to get multivariate probability
return torch.prod(gaussian_probs, -1)
def log_prob(self, target):
return self.torch_dist.log_prob(target)
def sample(self):
"""
draw a (reparameterized) sample
"""
return torch.randn_like(self.sigma) * self.sigma + self.mu
def sample_n(self, n):
"""
draw n (reparameterized) samples
"""
# reshape and repeat across the number of sample to vectorize operations
sigma = self.sigma.reshape(-1, *self.sigma.shape).repeat_interleave(n, dim=0)
mu = self.mu.reshape(-1, *self.mu.shape).repeat_interleave(n, dim=0)
return torch.randn_like(sigma) * sigma + mu
def detach(self):
self.mu = self.mu.detach()
self.sigma = self.sigma.detach()
self.torch_dist = Independent(Normal(self.mu, self.sigma), reinterpreted_batch_ndims=1)
return self
def reshape(self, shape):
self.mu = torch.reshape(self.mu, shape)
self.sigma = torch.reshape(self.sigma, shape)
self.torch_dist = Independent(Normal(self.mu, self.sigma), reinterpreted_batch_ndims=1)
return self
@property
def shape(self):
return self.mu.shape
def get_argmax(self):
return self.mu
def params(self):
return torch.cat([self.mu, self.sigma], dim=-1)
class GaussianMixture:
"""
a mixture of gaussian distributions
"""
def __init__(self, pi, sigma, mu):
"""
Supports batch input.
Here B is batch size, G is number of Gaussians, and D is the dimensionality of the variable
Inputs:
pi (BxG): weights of the mixture Gaussians
sigma (BxGxD): standard deviations (for now, the Gaussians are all diagonal)
mu (BxGxD): means
"""
self.pi = pi
self.sigma = sigma
self.mu = mu
self.n_gaussians = pi.shape[-1]
# torch distribution
mix = Categorical(pi)
comp = Independent(Normal(mu, sigma), reinterpreted_batch_ndims=1)
self.torch_dist = MixtureSameFamily(mix, comp)
def probability(self, target, multiple_samples=False):
"""
compute the probability of target under the distribution
Inputs:
target (BxD): target vector
multiple_samples (boolean): whether probability to be computed for multiple samples, in this case the
number of samples is expected to be the first dimension
Outputs:
probs (Bx1): probability under each distribution in the batch
"""
if not multiple_samples:
sigma = self.sigma
mu = self.mu
pi = self.pi
else:
n_samples = target.shape[0]
sigma = self.sigma.reshape(-1, *self.sigma.shape).repeat_interleave(n_samples, dim=0)
mu = self.mu.reshape(-1, *self.mu.shape).repeat_interleave(n_samples, dim=0)
pi = self.pi.reshape(-1, *self.pi.shape).repeat_interleave(n_samples, dim=0)
# replicate the target for each Gaussian in the mixture
target = target.unsqueeze(-2).repeat_interleave(self.n_gaussians, dim=-2)
# compute the individual probabilities of target under each gaussian
gaussian_probs = (1.0 / math.sqrt(2 * math.pi)) * torch.exp(
-0.5 * ((target - mu) / sigma) ** 2) / sigma
# add a small value for numerical stability
gaussian_probs += torch.ones_like(gaussian_probs) * EPS
# multiply univariate probabilities to get multivariate probability
gaussian_probs = torch.prod(gaussian_probs, -1)
# compute the weighted mixture probability
return torch.sum(pi * gaussian_probs, dim=-1)
def sample(self):
"""
draw a (non-reparameterized) sample from the mixture distribution
"""
# sample from a categorical first to decide which individual gaussian to sample from
pi_dist = Categorical(self.pi)
sample_pies = pi_dist.sample().view(*list(pi_dist.batch_shape), 1, 1)
# replicate and reshape so we can vector operate with the individual distribution params
sample_pies = torch.repeat_interleave(sample_pies, self.sigma.shape[-1], dim=-1)
# get the means and variances of the distributions corresponding to the sampled weights
stds = self.sigma.detach().gather(-2, sample_pies).squeeze()
means = self.mu.detach().gather(-2, sample_pies).squeeze()
# standard normal noise
normal_noise = torch.randn(
stds.shape, requires_grad=False
).to(stds.device)
return normal_noise * stds + means
def log_prob(self, target):
return self.torch_dist.log_prob(target)
def detach(self):
self.sigma = self.sigma.detach()
self.mu = self.mu.detach()
self.pi = self.pi.detach()
# detached torch distribution
mix = Categorical(self.pi)
comp = Independent(Normal(self.mu, self.sigma), reinterpreted_batch_ndims=1)
self.torch_dist = MixtureSameFamily(mix, comp)
return self
def reshape(self, shape):
new_shape = shape[:-1] + (self.n_gaussians, shape[-1])
self.sigma = self.sigma.reshape(new_shape)
self.mu = self.mu.reshape(new_shape)
self.pi = self.pi.reshape(shape[:-1] + (self.n_gaussians,))
mix = Categorical(self.pi)
comp = Independent(Normal(self.mu, self.sigma), reinterpreted_batch_ndims=1)
self.torch_dist = MixtureSameFamily(mix, comp)
return self
@property
def shape(self):
return self.mu.shape[:-2] + (self.mu.shape[-1],)
class Concrete:
def __init__(self, probs, table):
self.probs = probs
self.logits = torch.log(probs + EPS) # for numerical stability
self.num_classes = self.probs.shape[-1]
# torch categorical dist
self.torch_dist = Categorical(probs=probs)
# table to index locations when sampling
table_shape = tuple([1 for _ in self.torch_dist.batch_shape]) + table.shape
reps = tuple(self.torch_dist.batch_shape) + tuple([1 for _ in table.shape])
self.table = table.reshape(table_shape).repeat(*reps).to(probs.device)
self.class_dim = self.table.shape[-1]
def probability(self, sample):
""" sample can be (B,) or (B,N) with N = num_classes in the case of one-hot vectors """
if sample.shape == self.torch_dist.batch_shape:
# convert to one hot
sample = torch.nn.functional.one_hot(sample, self.num_classes)
return (sample * self.probs).sum(dim=-1)
def log_prob(self, target):
return torch.log(self.probability(target))
def sample(self, tau=0.5, hard=True, one_hot=False):
"""
draw a (reparameterized) sample using the gumbel softmax function
"""
one_hot_sample = torch.nn.functional.gumbel_softmax(self.logits, tau, hard=hard)
if one_hot:
return one_hot_sample
one_hot_sample = one_hot_sample.unsqueeze(-1).repeat_interleave(self.class_dim, dim=-1)
return (one_hot_sample * self.table).sum(-2)
def get_argmax(self):
return self.table[0][torch.argmax(self.probs, dim=-1), :]
def detach(self):
probs = self.probs.detach()
return self.__init__(probs, self.table)
@property
def shape(self):
return self.probs.shape
def kl_from_uniform(self):
return torch.log(torch.tensor(self.num_classes)) - self.torch_dist.entropy()
def kl_div(self, target_probs):
return torch.sum(self.probs * torch.log(self.probs/target_probs), dim=-1)