-
Notifications
You must be signed in to change notification settings - Fork 1
/
samplers.py
194 lines (158 loc) · 5.9 KB
/
samplers.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
"""
File for different sampling procedures
"""
import numpy as np
import torch
class Sampler:
def __init__(self, model, data):
"""
Args:
model (torch.nn.Module): pytorch model
data (torch.utils.data.Dataset): pytorch dataset
"""
self.model = model
self.data = data
self.length = len(data)
self.dsize = len(self.data[0][0])
def sumexp(self, x):
"""Compute the sum over the last dimension of exp(x)
"""
return torch.exp(self.model(x)).sum(dim=-1)
def E(self, x):
"""Computes the negative logsumexp i.e. the energy function
"""
return torch.logsumexp(self.model(x), dim=-1)
def sample(self, n):
"""Abstract method for producing samples
"""
pass
def EV(self, n):
"""Estimates expected value from n samples
"""
return torch.mean(self.E(self.sample(n)))
def sample_posterior(self, n, batchsize, granularity=1000):
"""Samples from the model distribution
"""
data = np.random.uniform(-10, 10, size=(2 * self.length, self.dsize))
unnormed_probs = [self.sumexp(torch.Tensor(data[i: i + batchsize])) \
for i in range(0, 2 * self.length, batchsize)]
unnormed_probs = torch.cat(unnormed_probs)
# sample from the unnormed probabilities
return self.data[torch.multinomial(unnormed_probs, n, replacement=True)]
class LangevinSampler(Sampler):
"""Stochastic Gradient Langevin Sampler"""
def __init__(self,
model,
data,
batchsize,
stepsize=1,
noise=0.01,
reinit_prob=0.05,
buffer_size=10000,
decay=0.9999):
"""
Args:
batchsize (int): training batchsize
stepsize (float): SGLD stepsize
noise (float): Stddev of SGLD noise
reinit_prob (float): Probability of reiniting a markov chain
buffer_size (int): size of PCD buffer
"""
super().__init__(model, data)
self.buffer_size = buffer_size
self.bs = batchsize
self.reinit_prob = reinit_prob
self.stepsize = stepsize
self.noise = noise
self.decay = decay
# get the data shape
self.data_size = self.data[0][0].size()[0]
self.replay_buff = self.randTensor(buffer_size, self.data_size)
def randTensor(self, *size):
"""Generates float tensors sampled from uniform distribution
"""
return torch.FloatTensor(*size).uniform_(-1, 1)
def sample(self, n):
"""
Runs SGLD with persistent contrastive divergence
Args:
n (int): SGLD steps to take
"""
# initialize x
buffer_inds = torch.randint(0, self.buffer_size, (self.bs,))
x_0 = self.randTensor(self.bs, self.data_size)
if self.model.training and np.random.rand() < self.reinit_prob:
x_0 = self.replay_buff[buffer_inds]
# run the chain
self.model.eval()
x = torch.autograd.Variable(x_0, requires_grad=True)
for i in range(n):
# compute the energy and get the gradient
energy = self.E(x)
# sgld update
grad = torch.autograd.grad(energy.sum(), [x], retain_graph=True)[0]
x.data += (self.stepsize * grad + \
self.noise * torch.randn_like(x))
self.model.train()
# add example to buffer
if len(self.replay_buff) > 0 and self.model.training:
self.replay_buff[buffer_inds] = x.detach()
return x
def EV(self, n):
return self.E(self.sample(n)).mean()
class CategoricalSampler(Sampler):
"""Uniform categorical sampler from unnormalized probabilities"""
def __init__(self, model, data, interval, interp=None, sample_bs=100):
"""
Args:
interval (int): interval to recompute the unnormed probabilities
interp (float): interpolate uniformly random sampled pairs of samples
(doubles amount of samples if true)
sample_bs (int): batchsize to evauluate sample rankings
"""
super().__init__(model, data)
self.interp = interp
self.interval = interval
self.sample_bs = sample_bs
self.updater = 0
self.probs = None
def sample(self, n):
"""Samples from multinomial based on the unnormalized probs
"""
# sample with replacement from the probs
if self.updater % self.interval == 0:
self.probs = torch.Tensor([
self.sumexp(torch.FloatTensor(x).unsqueeze(0)) \
for x, _ in self.data
])
self.updater += 1
sampled_inds = torch.multinomial(self.probs, n, replacement=True)
return torch.stack([self.data[i][0] for i in sampled_inds])
class MetroplisSampler(Sampler):
"""Sampler based on the metropolis hastings algorithm"""
def __init__(self, model, data):
"""
Args:
steps (int): number of steps to simulate markov chains for
"""
super().__init__(model, data)
def tkernel(self, x):
"""Random walk kernel as proposal distribution
"""
return x + torch.randn(2)
def sample(self, n):
"""Samples using the MH sampling algorithm
"""
# initialize x and run MH
x = torch.zeros(2)
for i in range(n):
# generate new candidate using transition kernel
y = self.tkernel(x)
# choose whether or not to accept candidate
accept = min(1, self.sumexp(y) / self.sumexp(x))
if np.random.rand() <= accept:
x = y
# return the stationary sample
return x
def EV(self, n):
return self.E(self.sample(n))