-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtrainer_base.py
More file actions
713 lines (632 loc) · 25 KB
/
trainer_base.py
File metadata and controls
713 lines (632 loc) · 25 KB
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
import itertools
from dataclasses import dataclass
import random
import hydra.utils
import lightning as L
import numpy as np
import torch
import torch.nn.functional as F
import transformers
import dataloader
import metrics
import models
import utils
@dataclass
class Loss:
loss: torch.FloatTensor
nlls: torch.FloatTensor
reconstruction_loss: torch.FloatTensor
num_tokens: torch.FloatTensor
class LogLinear(torch.nn.Module):
def __init__(self, alpha_0=1):
super().__init__()
self.eps = 1e-3 # To be consistent with SEDD: https://github.com/louaaron/Score-Entropy-Discrete-Diffusion/blob/0605786da5ccb5747545e26d66fdf477187598b6/noise_lib.py#L56
self.alpha_0 = alpha_0
def forward(self, t):
t = (1 - self.eps) * t
alpha_t = self.alpha_0 * (1 - t)
dalpha_t = - self.alpha_0 * (1 - self.eps)
return dalpha_t, alpha_t
def sample_categorical(categorical_probs):
gumbel_norm = (
1e-10
- (torch.rand_like(categorical_probs) + 1e-10).log())
return (categorical_probs / gumbel_norm).argmax(dim=-1)
def _unsqueeze(x, reference):
return x.view(
* x.shape,
* ((1,) * (len(reference.shape) - len(x.shape))))
class TrainerBase(L.LightningModule):
def __init__(
self,
config,
tokenizer: transformers.PreTrainedTokenizer,
vocab_size=None):
super().__init__()
self.save_hyperparameters()
self.config = config
if hasattr(self.config.algo, 'loss_type'):
self.loss_type = config.algo.loss_type
self.tokenizer = tokenizer
if vocab_size is None:
self.vocab_size = len(self.tokenizer)
else:
self.vocab_size = vocab_size
self.sampler = self.config.sampling.predictor
self.antithetic_sampling = self.config.training.antithetic_sampling
self.parameterization = self.config.algo.parameterization
if self.config.algo.backbone == 'dit':
self.backbone = models.dit.DiT(
self.config, vocab_size=self.vocab_size)
elif self.config.algo.backbone == 'esolm_dit':
self.backbone = models.dit.EsoLMDiT(
self.config, vocab_size=self.vocab_size,
mask_index=self.mask_index) # mask_index is defined in the child class
elif self.config.algo.backbone == 'hf_dit':
self.backbone = transformers.AutoModelForMaskedLM.from_pretrained(
config.eval.checkpoint_path, trust_remote_code=True)
self.T = self.config.algo.T
self.num_tokens = self.config.model.length
self.softplus = torch.nn.Softplus()
self.noise = LogLinear()
self.p_nucleus = self.config.sampling.p_nucleus
self.metrics = metrics.Metrics(
gen_ppl_eval_model_name_or_path=\
self.config.eval.gen_ppl_eval_model_name_or_path,
eval_ppl_batch_size=\
self.config.eval.perplexity_batch_size)
if self.config.training.ema > 0:
self.ema = models.ema.ExponentialMovingAverage(
self._get_parameters(),
decay=self.config.training.ema)
else:
self.ema = None
self.lr = self.config.optim.lr
self.sampling_eps = self.config.training.sampling_eps
self.time_conditioning = self.config.algo.time_conditioning
self.neg_infinity = -1000000.0
self.fast_forward_epochs = None
self.fast_forward_batches = None
def setup(self, stage=None):
# different randomness for different ranks
# does not affect dataloading seed
del stage
if (self.config.data.train != 'lm1b' or
self.config.mode == 'ppl_eval'):
new_seed = self.config.seed + self.trainer.global_rank
torch.manual_seed(new_seed)
np.random.seed(new_seed)
random.seed(new_seed)
else:
# using rankwise randomness for lm1b-wrap leads to
# divergence during training for unknown reasons
print('not using rankwise randomness')
def _validate_configuration(self):
assert self.config.algo.backbone in {'dit', 'hf_dit',
'esolm_dit'}
if self.config.algo.parameterization == 'ar':
assert not self.config.algo.time_conditioning
assert self.config.prior.type == 'none'
if self.parameterization in {'score', 'mean'}:
assert self.time_conditioning
if self.T > 0:
assert self.parameterization != 'score'
def to(self, *args, **kwargs):
self = super().to(*args, **kwargs)
self.metrics.to(*args, **kwargs)
return self
def q_xt(self, x, alpha_t):
raise NotImplementedError
def _get_parameters(self):
return itertools.chain(self.backbone.parameters(),
self.noise.parameters())
def _eval_mode(self, sample_eval=False):
if self.ema:
self.ema.store(self._get_parameters())
self.ema.copy_to(self._get_parameters())
if sample_eval:
self.ema = None # free up memory
self.backbone.eval()
self.noise.eval()
def _train_mode(self):
if self.ema:
self.ema.restore(self._get_parameters())
self.backbone.train()
self.noise.train()
def on_load_checkpoint(self, checkpoint):
if self.ema:
self.ema.load_state_dict(checkpoint['ema'])
# Copied from:
# https://github.com/Dao-AILab/flash-attention/blob/main/training/src/datamodules/language_modeling_hf.py#L41
self.fast_forward_epochs = checkpoint['loops'][
'fit_loop']['epoch_progress']['current']['completed']
self.fast_forward_batches = checkpoint['loops'][
'fit_loop']['epoch_loop.batch_progress'][
'current']['completed']
def on_save_checkpoint(self, checkpoint):
if self.ema:
checkpoint['ema'] = self.ema.state_dict()
# Copied from:
# https://github.com/Dao-AILab/flash-attention/blob/main/training/src/tasks/seq.py
# ['epoch_loop.batch_progress']['total']['completed']
# is 1 iteration behind, so we're using the optimizer's progress.
checkpoint['loops']['fit_loop'][
'epoch_loop.batch_progress']['total'][
'completed'] = checkpoint['loops']['fit_loop'][
'epoch_loop.automatic_optimization.optim_progress'][
'optimizer']['step']['total'][
'completed'] * self.trainer.accumulate_grad_batches
checkpoint['loops']['fit_loop'][
'epoch_loop.batch_progress']['current'][
'completed'] = checkpoint['loops']['fit_loop'][
'epoch_loop.automatic_optimization.optim_progress'][
'optimizer']['step']['current'][
'completed'] * self.trainer.accumulate_grad_batches
# _batches_that_stepped tracks the number of global steps,
# not the number of local steps, so we don't multiply with
# self.trainer.accumulate_grad_batches here.
checkpoint['loops']['fit_loop'][
'epoch_loop.state_dict'][
'_batches_that_stepped'] = checkpoint['loops']['fit_loop'][
'epoch_loop.automatic_optimization.optim_progress'][
'optimizer']['step']['total']['completed']
if 'sampler' not in checkpoint.keys():
checkpoint['sampler'] = {}
if hasattr(self.trainer.train_dataloader.sampler,
'state_dict'):
sampler_state_dict = self.trainer.\
train_dataloader.sampler.state_dict()
checkpoint['sampler'][
'random_state'] = sampler_state_dict.get(
'random_state', None)
else:
checkpoint['sampler']['random_state'] = None
def on_train_start(self):
if self.ema:
self.ema.move_shadow_params_to_device(self.device)
# Adapted from:
# https://github.com/Dao-AILab/flash-attention/blob/main/training/src/datamodules/language_modeling_hf.py
distributed = (
self.trainer._accelerator_connector.use_distributed_sampler
and self.trainer._accelerator_connector.is_distributed)
if distributed:
sampler_cls = dataloader.FaultTolerantDistributedSampler
else:
sampler_cls = dataloader.RandomFaultTolerantSampler
updated_dls = []
for dl in self.trainer.fit_loop._combined_loader.flattened:
if hasattr(dl.sampler, 'shuffle'):
dl_sampler = sampler_cls(
dl.dataset, shuffle=dl.sampler.shuffle)
else:
dl_sampler = sampler_cls(dl.dataset)
if (distributed
and self.fast_forward_epochs is not None
and self.fast_forward_batches is not None):
dl_sampler.load_state_dict({
'epoch': self.fast_forward_epochs,
'counter': (self.fast_forward_batches
* self.config.loader.batch_size)})
updated_dls.append(
torch.utils.data.DataLoader(
dl.dataset,
batch_size=self.config.loader.batch_size,
num_workers=self.config.loader.num_workers,
pin_memory=self.config.loader.pin_memory,
sampler=dl_sampler,
shuffle=False,
persistent_workers=True))
self.trainer.fit_loop._combined_loader.flattened = updated_dls
def optimizer_step(self, *args, **kwargs):
super().optimizer_step(*args, **kwargs)
if self.ema:
self.ema.update(self._get_parameters())
def _process_sigma(self, sigma):
raise NotImplementedError
def _process_model_output(self, model_output, xt, sigma):
raise NotImplementedError
def forward(self, xt, sigma, sort_idx=None, x0=None):
sigma = self._process_sigma(sigma)
with torch.amp.autocast('cuda', dtype=torch.float32):
model_output = self.backbone(xt, sigma, sort_idx, x0)
return self._process_model_output(
model_output=model_output, xt=xt, sigma=sigma)
def on_train_epoch_start(self):
self.metrics.reset()
assert self.metrics.train_nlls.nll.mean_value == 0
assert self.metrics.train_nlls.nll.weight == 0
def training_step(self, batch, batch_idx):
current_accumulation_step = (
batch_idx % self.trainer.accumulate_grad_batches)
losses = self._loss(batch['input_ids'],
batch['attention_mask'],
current_accumulation_step,
train_mode=True)
self.metrics.update_train(losses.nlls,
losses.reconstruction_loss,
losses.num_tokens)
self.log(name='trainer/loss',
value=losses.loss.item(),
on_step=True,
on_epoch=False,
sync_dist=True)
return losses.loss
def on_train_epoch_end(self):
for k, v in self.metrics.train_nlls.items():
self.log(name=k, value=v.compute(), on_step=False,
on_epoch=True, sync_dist=True)
def on_validation_epoch_start(self):
self.metrics.reset()
self._eval_mode()
assert self.metrics.valid_nlls.nll.mean_value == 0
assert self.metrics.valid_nlls.nll.weight == 0
def validation_step(self, batch, batch_idx):
del batch_idx
losses = self._loss(batch['input_ids'],
batch['attention_mask'])
self.metrics.update_valid(losses.nlls,
losses.reconstruction_loss,
losses.num_tokens)
return losses.loss
def on_validation_epoch_end(self):
for k, v in self.metrics.valid_nlls.items():
self.log(name=k, value=v.compute(), on_step=False,
on_epoch=True, sync_dist=True)
if ((self.config.eval.compute_perplexity_on_sanity
or not self.trainer.sanity_checking)
and self.config.eval.generate_samples):
samples, text_samples = None, None
for _ in range(
self.config.sampling.num_sample_batches):
samples = self.generate_samples(
num_samples=self.config.loader.eval_batch_size)
self.metrics.record_entropy(samples)
# Decode the samples to be re-tokenized by eval model
text_samples = self.tokenizer.batch_decode(samples)
if self.config.eval.compute_generative_perplexity:
self.metrics.record_generative_perplexity(
text_samples, self.num_tokens, self.device)
if text_samples is not None:
if self.trainer.global_rank == 0 and hasattr(
self.trainer.logger, 'log_table'):
# Log the last generated samples
text_samples = text_samples[
: self.config.sampling.num_sample_log]
self.trainer.logger.log_table(
key=f'samples@global_step{self.global_step}',
columns=['Generated Samples'],
data=[[s] for s in text_samples])
if self.config.eval.compute_generative_perplexity:
self.log('val/gen_ppl',
self.metrics.gen_ppl.compute(),
on_epoch=True,
on_step=False,
sync_dist=True)
self.log('val/sample_entropy',
self.metrics.sample_entropy.compute(),
on_epoch=True,
on_step=False,
sync_dist=True)
self._train_mode()
def configure_optimizers(self):
optimizer = torch.optim.AdamW(
self._get_parameters(),
lr=self.config.optim.lr,
betas=(self.config.optim.beta1,
self.config.optim.beta2),
eps=self.config.optim.eps,
weight_decay=self.config.optim.weight_decay)
scheduler = hydra.utils.instantiate(
self.config.lr_scheduler, optimizer=optimizer)
scheduler_dict = {'scheduler': scheduler,
'interval': 'step',
'monitor': 'val/loss',
'name': 'trainer/lr'}
return [optimizer], [scheduler_dict]
def generate_samples(self, num_samples, num_steps, eps):
raise NotImplementedError
def restore_model_and_sample(self, num_steps, eps=1e-5, sample_eval=False):
"""Generate samples from the model."""
# Lightning auto-casting is not working in this method for some reason
self._eval_mode(sample_eval)
samples, nfe, duration = self.generate_samples(
num_samples=self.config.loader.eval_batch_size,
num_steps=num_steps,
eps=eps)
if not sample_eval:
self._train_mode()
return samples, nfe, duration
def _process_model_input(self, x0, valid_tokens):
raise NotImplementedError
def nll(self, input_tokens, output_tokens,
current_accumulation_step=None, train_mode=False):
raise NotImplementedError
def _loss(self, x0, valid_tokens,
current_accumulation_step=None,
train_mode=False):
(input_tokens, output_tokens,
valid_tokens) = self._process_model_input(
x0, valid_tokens)
loss = self.nll(input_tokens, output_tokens,
current_accumulation_step, train_mode)
assert loss.ndim == 2
nlls = (loss * valid_tokens).sum()
num_tokens = valid_tokens.sum()
token_nll = nlls / num_tokens
return Loss(loss=token_nll,
nlls=nlls,
reconstruction_loss=torch.tensor(0),
num_tokens=num_tokens)
class Diffusion(TrainerBase):
def _validate_configuration(self):
super()._validate_configuration()
assert self.config.sampling.noise_removal in {
'none', 'ancestral', 'greedy'}
assert self.loss_type in {'elbo', 'low_var'}
if self.config.sampling.noise_removal == 'greedy':
assert self.sampler != 'analytic'
assert self.parameterization in {'mean', 'subs'}
def _process_model_input(self, x0, valid_tokens):
return x0, None, valid_tokens
def _process_sigma(self, sigma):
assert sigma.ndim == 2
sigma = sigma.mean(-1).squeeze()
if sigma.ndim == 0:
sigma = sigma.unsqueeze(0)
if not self.time_conditioning:
sigma = torch.zeros_like(sigma)
assert sigma.ndim == 1, sigma.shape
return sigma
def _sample_t(self, n, accum_step):
if accum_step is not None:
# During training
batch_dim = n
n = self.config.loader.global_batch_size
_eps_t = torch.rand(n, device=self.device)
if self.antithetic_sampling:
offset = torch.arange(n, device=self.device) / n
_eps_t = (_eps_t / n + offset) % 1
t = (1 - self.sampling_eps) * _eps_t + self.sampling_eps
if accum_step is not None:
t = t.chunk(self.trainer.num_nodes)[self.trainer.node_rank]
t = t.chunk(self.trainer.num_devices)[self.trainer.local_rank]
t = t.chunk(self.trainer.accumulate_grad_batches)[
accum_step]
# corner case for the last datapoint
t = t[:batch_dim]
return t
def _sigma_from_alphat(self, alpha_t):
return -torch.log(alpha_t)
def _reconstruction_loss(self, x0):
t0 = torch.zeros(1, x0.shape[0], dtype=self.dtype,
device=self.device)
sigma_t0 = self._sigma_from_alphat(self.noise(t0)[1])
model_output_t0 = self.forward(x0, sigma_t0)
return - torch.gather(input=model_output_t0,
dim=-1,
index=x0[:, :, None]).squeeze(-1)
def nll_per_token(self, model_output, xt, x0, alpha_t,
dalpha_t, low_var):
raise NotImplementedError
def nll(self, x0, output_tokens,
current_accumulation_step=None, train_mode=False):
del output_tokens
t = self._sample_t(x0.shape[0],
current_accumulation_step)
assert t.shape[0] == x0.shape[0]
if self.T > 0:
t = (t * self.T).to(torch.int)
t = t / self.T
# t \in {1/T, 2/T, ..., 1}
t += (1 / self.T)
dalpha_t, alpha_t = self.noise(t)
alpha_t = alpha_t.unsqueeze(-1)
assert alpha_t.ndim == 2
sigma = self._sigma_from_alphat(alpha_t)
xt = self.q_xt(x0, alpha_t)
log_x_theta = self.forward(xt, sigma=sigma)
utils.print_nans(log_x_theta, 'model_output')
return self.nll_per_token(
log_x_theta=log_x_theta,
xt=xt,
x0=x0,
alpha_t=alpha_t,
dalpha_t=dalpha_t,
low_var=train_mode and self.loss_type == 'low_var')
def _get_score(self, **kwargs):
del kwargs
raise NotImplementedError
def _denoiser_update(self, x, t):
raise NotImplementedError
def _analytic_update(self, x, t, dt):
raise NotImplementedError
def _ancestral_update(self, x, t, dt, p_x0, noise_removal_step):
raise NotImplementedError
@torch.no_grad()
def generate_samples(self, num_samples, num_steps=None,
eps=1e-5):
"""Generate samples from the model."""
# Lightning auto-casting is not working in this method for some reason
if num_steps is None:
num_steps = self.config.sampling.steps
x = self.prior_sample(num_samples, self.num_tokens)
timesteps = torch.linspace(
1, eps, num_steps + 1, device=self.device)
dt = (1 - eps) / num_steps
p_x0_cache = None
for i in range(num_steps):
t = timesteps[i] * torch.ones(
x.shape[0], 1, device=self.device)
if self.sampler == 'ancestral':
_, x = self._ancestral_update(
x=x, t=t, dt=dt, p_x0=None)
elif self.sampler == 'ancestral_cache':
p_x0_cache, x_next = self._ancestral_update(
x=x, t=t, dt=dt, p_x0=p_x0_cache)
if (not torch.allclose(x_next, x)
or self.time_conditioning):
# Disable caching
p_x0_cache = None
x = x_next
else:
x = self._analytic_update(x=x,t=t, dt=dt)
t0 = timesteps[-1] * torch.ones(x.shape[0], 1,
device=self.device)
if self.config.sampling.noise_removal == 'ancestral':
if self.sampler == 'analytic':
x = self._denoiser_update(x=x, t=t0)
else:
_, x = self._ancestral_update(x=x, t=t0, dt=None,
p_x0=p_x0_cache,
noise_removal_step=True)
elif self.config.sampling.noise_removal == 'greedy':
sigma = self._sigma_from_alphat(self.noise(t0)[1])
x = self.forward(xt=x, sigma=sigma).argmax(dim=-1)
return x
@torch.no_grad
def _semi_ar_sampler(
self, n_samples, stride_length, num_strides, dt=0.001):
# TODO(subham): Test this method after refactoring.
ones = torch.ones(n_samples, dtype=self.dtype,
device=self.device)
num_steps = int(1 / dt)
sampling_steps = 0
intermediate_tokens = []
target = None
for _ in range(num_strides + 1):
p_x0_cache = None
x = self.prior_sample(n_samples, self.num_tokens)
if target is not None:
x[:, : -stride_length] = target
for i in range(num_steps + 1):
p_x0_cache, x_next = self._ancestral_update(
x=x, t=(1 - i * dt) * ones, dt=dt, p_x0=p_x0_cache)
if (not torch.allclose(x_next, x)
or self.time_conditioning):
p_x0_cache = None
sampling_steps += 1
x = x_next
x = self.forward(x, 0 * ones).argmax(dim=-1)
intermediate_tokens.append(
x[:, :stride_length].cpu().numpy())
target = x[:, stride_length:]
intermediate_tokens.append(target.cpu().numpy())
intermediate_text_samples = []
sequence_lengths = ((
np.concatenate(intermediate_tokens, axis=1)[:, 1:]
== self.tokenizer.eos_token_id).cumsum(-1) == 0).sum(-1)
for i in range(2, len(intermediate_tokens) + 1):
intermediate_text_samples.append(
self.tokenizer.batch_decode(
np.concatenate(intermediate_tokens[:i], axis=1)))
return (sampling_steps, intermediate_text_samples,
sequence_lengths)
def restore_model_and_semi_ar_sample(
self, stride_length, num_strides, dt=0.001):
"""Generate samples from the model."""
# Lightning auto-casting is not working in this method for some reason
# TODO(subham): Test this method after refactoring.
self._eval_mode()
(sampling_steps, samples,
sequence_lengths) = self._semi_ar_sampler(
n_samples=self.config.loader.eval_batch_size,
stride_length=stride_length,
num_strides=num_strides,
dt=dt)
self._train_mode()
return sampling_steps, samples, sequence_lengths
class AbsorbingState(Diffusion):
def __init__(self, config, tokenizer):
# NOTE: Ideally, we should do
# vocab_size = len(tokenizer), so that we account
# for the special tokens added in dataloader.py.
# But we use tokenizer.vocab_size so as to to be
# consistent with the prior checkpoints.
vocab_size = tokenizer.vocab_size
if (not hasattr(tokenizer, 'mask_token')
or tokenizer.mask_token is None):
self.mask_index = vocab_size
vocab_size += 1
else:
self.mask_index = tokenizer.mask_token_id
self.subs_masking = config.algo.subs_masking
super().__init__(config, tokenizer,
vocab_size=vocab_size)
self.save_hyperparameters()
def _validate_configuration(self):
super()._validate_configuration()
if self.parameterization in {'score', 'mean'}:
assert self.time_conditioning
assert not (self.parameterization == 'mean'
and self.T == 0)
if self.T > 0:
assert self.parameterization in {'mean', 'subs'}
if self.subs_masking:
assert self.parameterization == 'mean'
def q_xt(self, x, alpha_t):
"""Computes the noisy sample xt.
Args:
x: int torch.Tensor with shape (batch_size,
diffusion_model_input_length), input.
alpha_t: float torch.Tensor with shape (batch_size, 1).
"""
move_indices = torch.rand(
* x.shape, device=x.device) < 1 - alpha_t
xt = torch.where(move_indices, self.mask_index, x)
return xt
def prior_sample(self, *batch_dims):
return self.mask_index * torch.ones(
* batch_dims, dtype=torch.int64, device=self.device)
def _ancestral_update(self, x, t, dt, p_x0=None,
noise_removal_step=False):
_, alpha_t = self.noise(t)
if noise_removal_step:
alpha_s = torch.ones_like(alpha_t)
else:
_, alpha_s = self.noise(t - dt)
assert alpha_t.ndim == 2
if p_x0 is None:
log_p_x0 = self.forward(
x, self._sigma_from_alphat(alpha_t))
if self.config.sampling.use_float64:
log_p_x0 = log_p_x0.to(torch.float64)
p_x0 = log_p_x0.exp()
q_xs = p_x0 * (alpha_s - alpha_t)[:, :, None]
q_xs[:, :, self.mask_index] = 1 - alpha_s
_x = sample_categorical(q_xs)
copy_flag = (x != self.mask_index).to(x.dtype)
return p_x0, copy_flag * x + (1 - copy_flag) * _x
def _staggered_score(self, score, dsigma):
score = score.clone()
extra_const = (1 - dsigma.exp()) * score.sum(dim=-1)
score *= dsigma.exp()[:, None]
score[..., self.mask_index] += extra_const
return score
def _analytic_update(self, x, t, dt):
sigma_t = self._sigma_from_alphat(self.noise(t)[1])
sigma_s = self._sigma_from_alphat(self.noise(t - dt)[1])
dsigma = sigma_t - sigma_s
score = self._get_score(x, sigma_t)
if self.config.sampling.use_float64:
score = score.to(torch.float64)
stag_score = self._staggered_score(score, dsigma)
probs = stag_score * self._transp_transition(x, dsigma)
return sample_categorical(probs)
def _denoiser_update(self, x, t):
sigma = self._sigma_from_alphat(self.noise(t)[1])
score = self._get_score(x, sigma)
if self.config.sampling.use_float64:
score = score.to(torch.float64)
stag_score = self._staggered_score(score, sigma)
probs = stag_score * self._transp_transition(x, sigma)
probs[..., self.mask_index] = 0
samples = sample_categorical(probs)
return samples
def _transp_transition(self, i, sigma):
sigma = _unsqueeze(sigma, reference=i[..., None])
edge = torch.exp(-sigma) * F.one_hot(
i, num_classes=self.vocab_size)
edge += torch.where(i == self.mask_index,
1 - torch.exp(-sigma).squeeze(-1),
0)[..., None]
return edge