-
Notifications
You must be signed in to change notification settings - Fork 22
/
solver.py
280 lines (222 loc) · 10.2 KB
/
solver.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
import torch
import numpy as np
import abc
from tqdm import trange
from losses import get_score_fn
from utils.graph_utils import mask_adjs, mask_x, gen_noise
from sde import VPSDE, subVPSDE
class Predictor(abc.ABC):
"""The abstract class for a predictor algorithm."""
def __init__(self, sde, score_fn, probability_flow=False):
super().__init__()
self.sde = sde
# Compute the reverse SDE/ODE
self.rsde = sde.reverse(score_fn, probability_flow)
self.score_fn = score_fn
@abc.abstractmethod
def update_fn(self, x, t, flags):
pass
class Corrector(abc.ABC):
"""The abstract class for a corrector algorithm."""
def __init__(self, sde, score_fn, snr, scale_eps, n_steps):
super().__init__()
self.sde = sde
self.score_fn = score_fn
self.snr = snr
self.scale_eps = scale_eps
self.n_steps = n_steps
@abc.abstractmethod
def update_fn(self, x, t, flags):
pass
class EulerMaruyamaPredictor(Predictor):
def __init__(self, obj, sde, score_fn, probability_flow=False):
super().__init__(sde, score_fn, probability_flow)
self.obj = obj
def update_fn(self, x, adj, flags, t):
dt = -1. / self.rsde.N
if self.obj=='x':
z = gen_noise(x, flags, sym=False)
drift, diffusion = self.rsde.sde(x, adj, flags, t, is_adj=False)
x_mean = x + drift * dt
x = x_mean + diffusion[:, None, None] * np.sqrt(-dt) * z
return x, x_mean
elif self.obj=='adj':
z = gen_noise(adj, flags)
drift, diffusion = self.rsde.sde(x, adj, flags, t, is_adj=True)
adj_mean = adj + drift * dt
adj = adj_mean + diffusion[:, None, None] * np.sqrt(-dt) * z
return adj, adj_mean
else:
raise NotImplementedError(f"obj {self.obj} not yet supported.")
class ReverseDiffusionPredictor(Predictor):
def __init__(self, obj, sde, score_fn, probability_flow=False):
super().__init__(sde, score_fn, probability_flow)
self.obj = obj
def update_fn(self, x, adj, flags, t):
if self.obj == 'x':
f, G = self.rsde.discretize(x, adj, flags, t, is_adj=False)
z = gen_noise(x, flags, sym=False)
x_mean = x - f
x = x_mean + G[:, None, None] * z
return x, x_mean
elif self.obj == 'adj':
f, G = self.rsde.discretize(x, adj, flags, t, is_adj=True)
z = gen_noise(adj, flags)
adj_mean = adj - f
adj = adj_mean + G[:, None, None] * z
return adj, adj_mean
else:
raise NotImplementedError(f"obj {self.obj} not yet supported.")
class NoneCorrector(Corrector):
"""An empty corrector that does nothing."""
def __init__(self, obj, sde, score_fn, snr, scale_eps, n_steps):
self.obj = obj
pass
def update_fn(self, x, adj, flags, t):
if self.obj == 'x':
return x, x
elif self.obj == 'adj':
return adj, adj
else:
raise NotImplementedError(f"obj {self.obj} not yet supported.")
class LangevinCorrector(Corrector):
def __init__(self, obj, sde, score_fn, snr, scale_eps, n_steps):
super().__init__(sde, score_fn, snr, scale_eps, n_steps)
self.obj = obj
def update_fn(self, x, adj, flags, t):
sde = self.sde
score_fn = self.score_fn
n_steps = self.n_steps
target_snr = self.snr
seps = self.scale_eps
if isinstance(sde, VPSDE) or isinstance(sde, subVPSDE):
timestep = (t * (sde.N - 1) / sde.T).long()
alpha = sde.alphas.to(t.device)[timestep]
else:
alpha = torch.ones_like(t)
if self.obj == 'x':
for i in range(n_steps):
grad = score_fn(x, adj, flags, t)
noise = gen_noise(x, flags, sym=False)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean()
step_size = (target_snr * noise_norm / grad_norm) ** 2 * 2 * alpha
x_mean = x + step_size[:, None, None] * grad
x = x_mean + torch.sqrt(step_size * 2)[:, None, None] * noise * seps
return x, x_mean
elif self.obj == 'adj':
for i in range(n_steps):
grad = score_fn(x, adj, flags, t)
noise = gen_noise(adj, flags)
grad_norm = torch.norm(grad.reshape(grad.shape[0], -1), dim=-1).mean()
noise_norm = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean()
step_size = (target_snr * noise_norm / grad_norm) ** 2 * 2 * alpha
adj_mean = adj + step_size[:, None, None] * grad
adj = adj_mean + torch.sqrt(step_size * 2)[:, None, None] * noise * seps
return adj, adj_mean
else:
raise NotImplementedError(f"obj {self.obj} not yet supported")
# -------- PC sampler --------
def get_pc_sampler(sde_x, sde_adj, shape_x, shape_adj, predictor='Euler', corrector='None',
snr=0.1, scale_eps=1.0, n_steps=1,
probability_flow=False, continuous=False,
denoise=True, eps=1e-3, device='cuda'):
def pc_sampler(model_x, model_adj, init_flags):
score_fn_x = get_score_fn(sde_x, model_x, train=False, continuous=continuous)
score_fn_adj = get_score_fn(sde_adj, model_adj, train=False, continuous=continuous)
predictor_fn = ReverseDiffusionPredictor if predictor=='Reverse' else EulerMaruyamaPredictor
corrector_fn = LangevinCorrector if corrector=='Langevin' else NoneCorrector
predictor_obj_x = predictor_fn('x', sde_x, score_fn_x, probability_flow)
corrector_obj_x = corrector_fn('x', sde_x, score_fn_x, snr, scale_eps, n_steps)
predictor_obj_adj = predictor_fn('adj', sde_adj, score_fn_adj, probability_flow)
corrector_obj_adj = corrector_fn('adj', sde_adj, score_fn_adj, snr, scale_eps, n_steps)
with torch.no_grad():
# -------- Initial sample --------
x = sde_x.prior_sampling(shape_x).to(device)
adj = sde_adj.prior_sampling_sym(shape_adj).to(device)
flags = init_flags
x = mask_x(x, flags)
adj = mask_adjs(adj, flags)
diff_steps = sde_adj.N
timesteps = torch.linspace(sde_adj.T, eps, diff_steps, device=device)
# -------- Reverse diffusion process --------
for i in trange(0, (diff_steps), desc = '[Sampling]', position = 1, leave=False):
t = timesteps[i]
vec_t = torch.ones(shape_adj[0], device=t.device) * t
_x = x
x, x_mean = corrector_obj_x.update_fn(x, adj, flags, vec_t)
adj, adj_mean = corrector_obj_adj.update_fn(_x, adj, flags, vec_t)
_x = x
x, x_mean = predictor_obj_x.update_fn(x, adj, flags, vec_t)
adj, adj_mean = predictor_obj_adj.update_fn(_x, adj, flags, vec_t)
print(' ')
return (x_mean if denoise else x), (adj_mean if denoise else adj), diff_steps * (n_steps + 1)
return pc_sampler
# -------- S4 solver --------
def S4_solver(sde_x, sde_adj, shape_x, shape_adj, predictor='None', corrector='None',
snr=0.1, scale_eps=1.0, n_steps=1,
probability_flow=False, continuous=False,
denoise=True, eps=1e-3, device='cuda'):
def s4_solver(model_x, model_adj, init_flags):
score_fn_x = get_score_fn(sde_x, model_x, train=False, continuous=continuous)
score_fn_adj = get_score_fn(sde_adj, model_adj, train=False, continuous=continuous)
with torch.no_grad():
# -------- Initial sample --------
x = sde_x.prior_sampling(shape_x).to(device)
adj = sde_adj.prior_sampling_sym(shape_adj).to(device)
flags = init_flags
x = mask_x(x, flags)
adj = mask_adjs(adj, flags)
diff_steps = sde_adj.N
timesteps = torch.linspace(sde_adj.T, eps, diff_steps, device=device)
dt = -1. / diff_steps
# -------- Rverse diffusion process --------
for i in trange(0, (diff_steps), desc = '[Sampling]', position = 1, leave=False):
t = timesteps[i]
vec_t = torch.ones(shape_adj[0], device=t.device) * t
vec_dt = torch.ones(shape_adj[0], device=t.device) * (dt/2)
# -------- Score computation --------
score_x = score_fn_x(x, adj, flags, vec_t)
score_adj = score_fn_adj(x, adj, flags, vec_t)
Sdrift_x = -sde_x.sde(x, vec_t)[1][:, None, None] ** 2 * score_x
Sdrift_adj = -sde_adj.sde(adj, vec_t)[1][:, None, None] ** 2 * score_adj
# -------- Correction step --------
timestep = (vec_t * (sde_x.N - 1) / sde_x.T).long()
noise = gen_noise(x, flags, sym=False)
grad_norm = torch.norm(score_x.reshape(score_x.shape[0], -1), dim=-1).mean()
noise_norm = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean()
if isinstance(sde_x, VPSDE):
alpha = sde_x.alphas.to(vec_t.device)[timestep]
else:
alpha = torch.ones_like(vec_t)
step_size = (snr * noise_norm / grad_norm) ** 2 * 2 * alpha
x_mean = x + step_size[:, None, None] * score_x
x = x_mean + torch.sqrt(step_size * 2)[:, None, None] * noise * scale_eps
noise = gen_noise(adj, flags)
grad_norm = torch.norm(score_adj.reshape(score_adj.shape[0], -1), dim=-1).mean()
noise_norm = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean()
if isinstance(sde_adj, VPSDE):
alpha = sde_adj.alphas.to(vec_t.device)[timestep] # VP
else:
alpha = torch.ones_like(vec_t) # VE
step_size = (snr * noise_norm / grad_norm) ** 2 * 2 * alpha
adj_mean = adj + step_size[:, None, None] * score_adj
adj = adj_mean + torch.sqrt(step_size * 2)[:, None, None] * noise * scale_eps
# -------- Prediction step --------
x_mean = x
adj_mean = adj
mu_x, sigma_x = sde_x.transition(x, vec_t, vec_dt)
mu_adj, sigma_adj = sde_adj.transition(adj, vec_t, vec_dt)
x = mu_x + sigma_x[:, None, None] * gen_noise(x, flags, sym=False)
adj = mu_adj + sigma_adj[:, None, None] * gen_noise(adj, flags)
x = x + Sdrift_x * dt
adj = adj + Sdrift_adj * dt
mu_x, sigma_x = sde_x.transition(x, vec_t + vec_dt, vec_dt)
mu_adj, sigma_adj = sde_adj.transition(adj, vec_t + vec_dt, vec_dt)
x = mu_x + sigma_x[:, None, None] * gen_noise(x, flags, sym=False)
adj = mu_adj + sigma_adj[:, None, None] * gen_noise(adj, flags)
x_mean = mu_x
adj_mean = mu_adj
print(' ')
return (x_mean if denoise else x), (adj_mean if denoise else adj), 0
return s4_solver