File size: 21,148 Bytes
93cd35a | 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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import scipy.integrate
import math
from tqdm import tqdm
import lib.sampling.sampling_utils as sampling_utils
def get_initial_samples(N, D, device, S, initial_dist, initial_dist_std=None):
if initial_dist == 'uniform':
x = torch.randint(low=0, high=S, size=(N, D), device=device)
elif initial_dist == 'gaussian':
target = np.exp(
- ((np.arange(1, S+1) - S//2)**2) / (2 * initial_dist_std**2)
)
target = target / np.sum(target)
cat = torch.distributions.categorical.Categorical(
torch.from_numpy(target)
)
x = cat.sample((N*D,)).view(N,D)
x = x.to(device)
else:
raise NotImplementedError('Unrecognized initial dist ' + initial_dist)
return x
def one_step_sampling(model, N, D, S, eps_ratio, x_t, ts, delta, p0t=None, batch_size=1):
device=model.device
with torch.no_grad():
qt0 = model.transition(ts) # (N, S, S)
rate = model.rate(ts) # (N, S, S)
if p0t is None:
p0t = F.softmax(model(x_t, ts), dim=2) # (N, D, S)
# x_0max = torch.max(p0t, dim=2)[1]
qt0_denom = qt0[
torch.arange(N, device=device).repeat_interleave(D*S),
torch.arange(S, device=device).repeat(N*D),
x_t.long().flatten().repeat_interleave(S)
].view(N,D,S) + eps_ratio
# First S is x0 second S is x tilde
qt0_numer = qt0 # (N, S, S)
forward_rates = rate[
torch.arange(N, device=device).repeat_interleave(D*S),
torch.arange(S, device=device).repeat(N*D),
x_t.long().flatten().repeat_interleave(S)
].view(N, D, S)
inner_sum = (p0t / qt0_denom) @ qt0_numer # (N, D, S)
reverse_rates = forward_rates * inner_sum # (N, D, S)
reverse_rates[
torch.arange(N, device=device).repeat_interleave(D),
torch.arange(D, device=device).repeat(N),
x_t.long().flatten()
] = 0.0
x_t = x_t.expand(N*batch_size, -1)
diffs = torch.arange(S, device=device).view(1,1,S) - x_t.view(N*batch_size,D,1)
poisson_dist = torch.distributions.poisson.Poisson(
reverse_rates.expand(N*batch_size, -1, -1) * delta.view(-1, 1, 1))
jump_nums = poisson_dist.sample()
adj_diffs = jump_nums * diffs
overall_jump = torch.sum(adj_diffs, dim=2)
xp = x_t + overall_jump
x_new = torch.clamp(xp, min=0, max=S-1)
return x_new
@sampling_utils.register_sampler
class TauLeaping():
def __init__(self, cfg):
self.cfg =cfg
def sample(self, model, N, num_intermediates):
t = 1.0
C,H,W = self.cfg.data.shape
D = C*H*W
S = self.cfg.data.S
scfg = self.cfg.sampler
num_steps = scfg.num_steps
min_t = scfg.min_t
eps_ratio = scfg.eps_ratio
initial_dist = scfg.initial_dist
if initial_dist == 'gaussian':
initial_dist_std = model.Q_sigma
else:
initial_dist_std = None
device = model.device
with torch.no_grad():
x = get_initial_samples(N, D, device, S, initial_dist,
initial_dist_std)
ts = np.concatenate((np.linspace(1.0, min_t, num_steps), np.array([0])))
save_ts = ts[np.linspace(0, len(ts)-2, num_intermediates, dtype=int)]
x_hist = []
x0_hist = []
counter = 0
for idx, t in tqdm(enumerate(ts[0:-1])):
h = ts[idx] - ts[idx+1]
qt0 = model.transition(t * torch.ones((N,), device=device)) # (N, S, S)
rate = model.rate(t * torch.ones((N,), device=device)) # (N, S, S)
p0t = F.softmax(model(x, t * torch.ones((N,), device=device)), dim=2) # (N, D, S)
x_0max = torch.max(p0t, dim=2)[1]
if t in save_ts:
x_hist.append(x.clone().detach().cpu().numpy())
x0_hist.append(x_0max.clone().detach().cpu().numpy())
qt0_denom = qt0[
torch.arange(N, device=device).repeat_interleave(D*S),
torch.arange(S, device=device).repeat(N*D),
x.long().flatten().repeat_interleave(S)
].view(N,D,S) + eps_ratio
# First S is x0 second S is x tilde
qt0_numer = qt0 # (N, S, S)
forward_rates = rate[
torch.arange(N, device=device).repeat_interleave(D*S),
torch.arange(S, device=device).repeat(N*D),
x.long().flatten().repeat_interleave(S)
].view(N, D, S)
inner_sum = (p0t / qt0_denom) @ qt0_numer # (N, D, S)
reverse_rates = forward_rates * inner_sum # (N, D, S)
reverse_rates[
torch.arange(N, device=device).repeat_interleave(D),
torch.arange(D, device=device).repeat(N),
x.long().flatten()
] = 0.0
diffs = torch.arange(S, device=device).view(1,1,S) - x.view(N,D,1)
poisson_dist = torch.distributions.poisson.Poisson(reverse_rates * h)
jump_nums = poisson_dist.sample()
adj_diffs = jump_nums * diffs
overall_jump = torch.sum(adj_diffs, dim=2)
xp = x + overall_jump
x_new = torch.clamp(xp, min=0, max=S-1)
x = x_new
x_hist = np.array(x_hist).astype(int)
x0_hist = np.array(x0_hist).astype(int)
p_0gt = F.softmax(model(x, min_t * torch.ones((N,), device=device)), dim=2) # (N, D, S)
x_0max = torch.max(p_0gt, dim=2)[1]
return x_0max.detach().cpu().numpy().astype(int), x_hist, x0_hist
@sampling_utils.register_sampler
class PCTauLeaping():
def __init__(self, cfg):
self.cfg =cfg
def sample(self, model, N, num_intermediates):
t = 1.0
C,H,W = self.cfg.data.shape
D = C*H*W
S = self.cfg.data.S
scfg = self.cfg.sampler
num_steps = scfg.num_steps
min_t = scfg.min_t
eps_ratio = scfg.eps_ratio
num_corrector_steps = scfg.num_corrector_steps
corrector_step_size_multiplier = scfg.corrector_step_size_multiplier
corrector_entry_time = scfg.corrector_entry_time
device = model.device
initial_dist = scfg.initial_dist
if initial_dist == 'gaussian':
initial_dist_std = model.Q_sigma
else:
initial_dist_std = None
with torch.no_grad():
x = get_initial_samples(N, D, device, S, initial_dist,
initial_dist_std)
h = 1.0 / num_steps # approximately
ts = np.linspace(1.0, min_t+h, num_steps)
save_ts = ts[np.linspace(0, len(ts)-2, num_intermediates, dtype=int)]
x_hist = []
x0_hist = []
for idx, t in tqdm(enumerate(ts[0:-1])):
h = ts[idx] - ts[idx+1]
def get_rates(in_x, in_t):
qt0 = model.transition(in_t * torch.ones((N,), device=device)) # (N, S, S)
rate = model.rate(in_t * torch.ones((N,), device=device)) # (N, S, S)
p0t = F.softmax(model(in_x, in_t * torch.ones((N,), device=device)), dim=2) # (N, D, S)
x_0max = torch.max(p0t, dim=2)[1]
qt0_denom = qt0[
torch.arange(N, device=device).repeat_interleave(D*S),
torch.arange(S, device=device).repeat(N*D),
in_x.long().flatten().repeat_interleave(S)
].view(N,D,S) + eps_ratio
# First S is x0 second S is x tilde
qt0_numer = qt0 # (N, S, S)
forward_rates = rate[
torch.arange(N, device=device).repeat_interleave(D*S),
torch.arange(S, device=device).repeat(N*D),
in_x.long().flatten().repeat_interleave(S)
].view(N, D, S)
reverse_rates = forward_rates * ((p0t / qt0_denom) @ qt0_numer) # (N, D, S)
reverse_rates[
torch.arange(N, device=device).repeat_interleave(D),
torch.arange(D, device=device).repeat(N),
in_x.long().flatten()
] = 0.0
transpose_forward_rates = rate[
torch.arange(N, device=device).repeat_interleave(D*S),
in_x.long().flatten().repeat_interleave(S),
torch.arange(S, device=device).repeat(N*D)
].view(N, D, S)
return transpose_forward_rates, reverse_rates, x_0max
def take_poisson_step(in_x, in_reverse_rates, in_h):
diffs = torch.arange(S, device=device).view(1,1,S) - in_x.view(N,D,1)
poisson_dist = torch.distributions.poisson.Poisson(in_reverse_rates * in_h)
jump_nums = poisson_dist.sample()
adj_diffs = jump_nums * diffs
overall_jump = torch.sum(adj_diffs, dim=2)
unclip_x_new = in_x + overall_jump
x_new = torch.clamp(unclip_x_new, min=0, max=S-1)
return x_new
transpose_forward_rates, reverse_rates, x_0max = get_rates(x, t)
if t in save_ts:
x_hist.append(x.detach().cpu().numpy())
x0_hist.append(x_0max.detach().cpu().numpy())
x = take_poisson_step(x, reverse_rates, h)
if t <= corrector_entry_time:
for _ in range(num_corrector_steps):
transpose_forward_rates, reverse_rates, _ = get_rates(x, t-h)
corrector_rate = transpose_forward_rates + reverse_rates
corrector_rate[
torch.arange(N, device=device).repeat_interleave(D),
torch.arange(D, device=device).repeat(N),
x.long().flatten()
] = 0.0
x = take_poisson_step(x, corrector_rate,
corrector_step_size_multiplier * h)
x_hist = np.array(x_hist).astype(int)
x0_hist = np.array(x0_hist).astype(int)
p_0gt = F.softmax(model(x, min_t * torch.ones((N,), device=device)), dim=2) # (N, D, S)
x_0max = torch.max(p_0gt, dim=2)[1]
return x_0max.detach().cpu().numpy().astype(int), x_hist, x0_hist
@sampling_utils.register_sampler
class ConditionalTauLeaping():
def __init__(self, cfg):
self.cfg = cfg
def sample(self, model, N, num_intermediates, conditioner):
assert conditioner.shape[0] == N
t = 1.0
condition_dim = self.cfg.sampler.condition_dim
total_D = self.cfg.data.shape[0]
sample_D = total_D - condition_dim
S = self.cfg.data.S
scfg = self.cfg.sampler
num_steps = scfg.num_steps
min_t = scfg.min_t
eps_ratio = scfg.eps_ratio
reject_multiple_jumps = scfg.reject_multiple_jumps
initial_dist = scfg.initial_dist
if initial_dist == 'gaussian':
initial_dist_std = model.Q_sigma
else:
initial_dist_std = None
device = model.device
with torch.no_grad():
x = get_initial_samples(N, sample_D, device, S, initial_dist,
initial_dist_std)
ts = np.concatenate((np.linspace(1.0, min_t, num_steps), np.array([0])))
save_ts = ts[np.linspace(0, len(ts)-2, num_intermediates, dtype=int)]
x_hist = []
x0_hist = []
counter = 0
for idx, t in tqdm(enumerate(ts[0:-1])):
h = ts[idx] - ts[idx+1]
qt0 = model.transition(t * torch.ones((N,), device=device)) # (N, S, S)
rate = model.rate(t * torch.ones((N,), device=device)) # (N, S, S)
model_input = torch.concat((conditioner, x), dim=1)
p0t = F.softmax(model(model_input, t * torch.ones((N,), device=device)), dim=2) # (N, D, S)
p0t = p0t[:, condition_dim:, :]
x_0max = torch.max(p0t, dim=2)[1]
if t in save_ts:
x_hist.append(x.clone().detach().cpu().numpy())
x0_hist.append(x_0max.clone().detach().cpu().numpy())
qt0_denom = qt0[
torch.arange(N, device=device).repeat_interleave(sample_D*S),
torch.arange(S, device=device).repeat(N*sample_D),
x.long().flatten().repeat_interleave(S)
].view(N,sample_D,S) + eps_ratio
# First S is x0 second S is x tilde
qt0_numer = qt0 # (N, S, S)
forward_rates = rate[
torch.arange(N, device=device).repeat_interleave(sample_D*S),
torch.arange(S, device=device).repeat(N*sample_D),
x.long().flatten().repeat_interleave(S)
].view(N, sample_D, S)
inner_sum = (p0t / qt0_denom) @ qt0_numer # (N, D, S)
reverse_rates = forward_rates * inner_sum # (N, D, S)
reverse_rates[
torch.arange(N, device=device).repeat_interleave(sample_D),
torch.arange(sample_D, device=device).repeat(N),
x.long().flatten()
] = 0.0
diffs = torch.arange(S, device=device).view(1,1,S) - x.view(N,sample_D,1)
poisson_dist = torch.distributions.poisson.Poisson(reverse_rates * h)
jump_nums = poisson_dist.sample()
if reject_multiple_jumps:
jump_num_sum = torch.sum(jump_nums, dim=2)
jump_num_sum_mask = jump_num_sum <= 1
masked_jump_nums = jump_nums * jump_num_sum_mask.view(N, sample_D, 1)
adj_diffs = masked_jump_nums * diffs
else:
adj_diffs = jump_nums * diffs
adj_diffs = jump_nums * diffs
overall_jump = torch.sum(adj_diffs, dim=2)
xp = x + overall_jump
x_new = torch.clamp(xp, min=0, max=S-1)
x = x_new
x_hist = np.array(x_hist).astype(int)
x0_hist = np.array(x0_hist).astype(int)
model_input = torch.concat((conditioner, x), dim=1)
p_0gt = F.softmax(model(model_input, min_t * torch.ones((N,), device=device)), dim=2) # (N, D, S)
p_0gt = p_0gt[:, condition_dim:, :]
x_0max = torch.max(p_0gt, dim=2)[1]
output = torch.concat((conditioner, x_0max), dim=1)
return output.detach().cpu().numpy().astype(int), x_hist, x0_hist
@sampling_utils.register_sampler
class ConditionalPCTauLeaping():
def __init__(self, cfg):
self.cfg = cfg
def sample(self, model, N, num_intermediates, conditioner):
assert conditioner.shape[0] == N
t = 1.0
condition_dim = self.cfg.sampler.condition_dim
total_D = self.cfg.data.shape[0]
sample_D = total_D - condition_dim
S = self.cfg.data.S
scfg = self.cfg.sampler
num_steps = scfg.num_steps
min_t = scfg.min_t
reject_multiple_jumps = scfg.reject_multiple_jumps
eps_ratio = scfg.eps_ratio
num_corrector_steps = scfg.num_corrector_steps
corrector_step_size_multiplier = scfg.corrector_step_size_multiplier
corrector_entry_time = scfg.corrector_entry_time
initial_dist = scfg.initial_dist
if initial_dist == 'gaussian':
initial_dist_std = model.Q_sigma
else:
initial_dist_std = None
device = model.device
with torch.no_grad():
x = get_initial_samples(N, sample_D, device, S, initial_dist,
initial_dist_std)
h = 1.0 / num_steps # approximately
ts = np.linspace(1.0, min_t+h, num_steps)
save_ts = ts[np.linspace(0, len(ts)-2, num_intermediates, dtype=int)]
x_hist = []
x0_hist = []
for idx, t in tqdm(enumerate(ts[0:-1])):
h = ts[idx] - ts[idx+1]
def get_rates(in_x, in_t):
qt0 = model.transition(in_t * torch.ones((N,), device=device)) # (N, S, S)
rate = model.rate(in_t * torch.ones((N,), device=device)) # (N, S, S)
model_input = torch.concat((conditioner, in_x), dim=1)
p0t = F.softmax(model(model_input, in_t * torch.ones((N,), device=device)), dim=2) # (N, D, S)
p0t = p0t[:, condition_dim:, :]
x_0max = torch.max(p0t, dim=2)[1]
qt0_denom = qt0[
torch.arange(N, device=device).repeat_interleave(sample_D*S),
torch.arange(S, device=device).repeat(N*sample_D),
x.long().flatten().repeat_interleave(S)
].view(N,sample_D,S) + eps_ratio
# First S is x0 second S is x tilde
qt0_numer = qt0 # (N, S, S)
forward_rates = rate[
torch.arange(N, device=device).repeat_interleave(sample_D*S),
torch.arange(S, device=device).repeat(N*sample_D),
in_x.long().flatten().repeat_interleave(S)
].view(N, sample_D, S)
reverse_rates = forward_rates * ((p0t/qt0_denom) @ qt0_numer) # (N, D, S)
reverse_rates[
torch.arange(N, device=device).repeat_interleave(sample_D),
torch.arange(sample_D, device=device).repeat(N),
in_x.long().flatten()
] = 0.0
transpose_forward_rates = rate[
torch.arange(N, device=device).repeat_interleave(sample_D*S),
in_x.long().flatten().repeat_interleave(S),
torch.arange(S, device=device).repeat(N*sample_D)
].view(N, sample_D, S)
return transpose_forward_rates, reverse_rates, x_0max
def take_poisson_step(in_x, in_reverse_rates, in_h):
diffs = torch.arange(S, device=device).view(1,1,S) - in_x.view(N,sample_D,1)
poisson_dist = torch.distributions.poisson.Poisson(in_reverse_rates * in_h)
jump_nums = poisson_dist.sample()
if reject_multiple_jumps:
jump_num_sum = torch.sum(jump_nums, dim=2)
jump_num_sum_mask = jump_num_sum <= 1
masked_jump_nums = jump_nums * jump_num_sum_mask.view(N, sample_D, 1)
adj_diffs = masked_jump_nums * diffs
else:
adj_diffs = jump_nums * diffs
overall_jump = torch.sum(adj_diffs, dim=2)
xp = in_x + overall_jump
x_new = torch.clamp(xp, min=0, max=S-1)
return x_new
transpose_forward_rates, reverse_rates, x_0max = get_rates(x, t)
if t in save_ts:
x_hist.append(x.clone().detach().cpu().numpy())
x0_hist.append(x_0max.clone().detach().cpu().numpy())
x = take_poisson_step(x, reverse_rates, h)
if t <= corrector_entry_time:
for _ in range(num_corrector_steps):
transpose_forward_rates, reverse_rates, _ = get_rates(x, t-h)
corrector_rate = transpose_forward_rates + reverse_rates
corrector_rate[
torch.arange(N, device=device).repeat_interleave(sample_D),
torch.arange(sample_D, device=device).repeat(N),
x.long().flatten()
] = 0.0
x = take_poisson_step(x, corrector_rate,
corrector_step_size_multiplier * h)
x_hist = np.array(x_hist).astype(int)
x0_hist = np.array(x0_hist).astype(int)
model_input = torch.concat((conditioner, x), dim=1)
p_0gt = F.softmax(model(model_input, min_t * torch.ones((N,), device=device)), dim=2) # (N, D, S)
p_0gt = p_0gt[:, condition_dim:, :]
x_0max = torch.max(p_0gt, dim=2)[1]
output = torch.concat((conditioner, x_0max), dim=1)
return output.detach().cpu().numpy().astype(int), x_hist, x0_hist
|