-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwalk_jump.py
More file actions
3355 lines (2681 loc) · 161 KB
/
Copy pathwalk_jump.py
File metadata and controls
3355 lines (2681 loc) · 161 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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Credit : gpt-4o , Claude-3.5-Sonnet-200k , Gemini-Pro-1.5
# Reference :
# [Protein Discovery with Discrete Walk-Jump Sampling](http://arxiv.org/abs/2306.12360)
# [Diffusion Forcing: Next-token Prediction Meets Full-Sequence Diffusion](http://arxiv.org/abs/2407.01392)
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import math
import numpy
import os
import random
import string
from collections import Counter
from transformers import AutoTokenizer, AutoConfig, AutoModel, AutoModelForMaskedLM, AutoModelForSeq2SeqLM, T5Tokenizer, T5ForConditionalGeneration
from transformers.optimization import Adafactor, AdafactorSchedule
from torch.nn.utils.rnn import pad_sequence
from torch.nn.utils.parametrizations import weight_norm
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import DataLoader, Dataset
from datasets import load_dataset
from adam_mini import Adam_mini
# the models have been trained / finetuned, run inference code only
INFERENCE_ONLY = 0
# Just for code development / debugging purpose
TEST_OVERFIT = 0
# for the denoiser module, choose only ONE of the following options :
USE_PRETRAINED_BERT = 0
USE_PRETRAINED_BERT_MLM = 0
USE_PRETRAINED_T5 = 0
USE_CUSTOM_TRANSFORMER_ENCODER = 0 # the most RAM memory efficient option
USE_CUSTOM_TRANSFORMER_ENCODER_DECODER = 1
# Early-stopping for the models training
USE_EARLY_STOP = 0
EARLY_STOP_THRESHOLD = 2.175 #1.91
# for sentence completion downstream task
ENABLE_MASK_LEARNING = 1
# google colab T4 GPU does not have a lot of RAM for computation
# custom transformer module can now handle multiple masked tokens
if torch.cuda.is_available(): #or USE_CUSTOM_TRANSFORMER_ENCODER_DECODER or USE_CUSTOM_TRANSFORMER_ENCODER:
MASK_RATIO = 0.15 # use 0.15 for 15% masking probability, use the value of -1 to indicate only a single masked token
else:
MASK_RATIO = 0.15 # use 0.15 for 15% masking probability, use the value of -1 to indicate only a single masked token
# allows the denoiser model to train on [batch_size, sequence_length, vocab_size]
USE_LOGITS_FOR_THE_ENTIRE_SENTENCE = 1
USE_LOGITS_FOR_THE_ENTIRE_SENTENCE = USE_LOGITS_FOR_THE_ENTIRE_SENTENCE or (MASK_RATIO != -1) # if masking more than 1 token, then it makes sense to train on [batch_size, sequence_length, vocab_size]
# custom transformer module can now handle multiple masked tokens
#USE_LOGITS_FOR_THE_ENTIRE_SENTENCE = USE_LOGITS_FOR_THE_ENTIRE_SENTENCE and not (USE_CUSTOM_TRANSFORMER_ENCODER_DECODER or USE_CUSTOM_TRANSFORMER_ENCODER)
# Analyze walk-jump's output samples for debugging purpose
ENABLE_SAMPLE_ANALYSIS = 0 # turns off for reducing memory consumption
if torch.cuda.is_available():
device_str = "cuda"
else:
device_str = "mps"
device = torch.device(device_str)
# Automatic Mixed Precision for training
from torch import autocast
if torch.cuda.is_available():
from torch.amp import GradScaler
USE_MIXED_PRECISION_TRAINING = 0 # optional, turns off for this code since it hurts model performance
else:
USE_MIXED_PRECISION_TRAINING = 0 # not implemented
# for saving RAM memory during training : https://github.com/zyushun/Adam-mini
USE_ADAM_MINI = 0
# 0: Sinusoidal Positional Embedding , 1: Rotary Positional Embedding
USE_ROPE = 0
# Just for code development / debugging purpose
USE_DUMMY_TRAINING_DATA = 0
# for adjusting the generation process due to fixed output length
GENERATES_OUTPUT_OF_VARYING_LENGTH = 0
# for more difficult denoising task
ADD_EXTRA_GAUSSIAN_NOISE = 0 # turns off for now
# Select between diffusion forcing and walk-jump
# if the following two variables are turned off, it would be walk-jump (single constant noise level)
USE_DIFFUSION_FORCING = 1 & ADD_EXTRA_GAUSSIAN_NOISE
USE_PRECOMPUTE_NOISE_SCHEDULE = 0 # testing only, do not recommend to use due to expensive storage
# Regarding two different approaches for Langevin MCMC sampling
USE_MCMC = 1
USE_ALGORITHM_1_OR_4 = 0 # value of 1 means Algorithm 1, value of 0 means Algorithm 4, see walk-jump paper
USE_OBABO = 0 # Using KIPLMC2 is slow because of the need to compute gradients of U with respect to both theta and X
# sequential monte-carlo (SMC)
USE_SMC = 0 # if use SMC, then ignore USE_ALGORITHM_1_OR_4 which is related to Langevin MCMC
# Markov-approximate fractional Brownian motion (MA-fBM)
USE_MAFBM = 0 # if use MAFBM, then ignore USE_ALGORITHM_1_OR_4 which is related to Langevin MCMC
# Once turned on, it will be different from the walk-jump denoise update equation
USE_LOGITS_FOR_DENOISING = 0 # consumes much more RAM memory
USE_LOGITS_FOR_DENOISING = USE_LOGITS_FOR_DENOISING and (USE_SMC or USE_MAFBM or USE_MCMC)
# kl_div method (requires extra run of denoiser model) to improve sampling based on prior distribution
# Only turn on USE_GRAD_KL if USE_PRETRAINED_T5 is disabled, because USE_GRAD_KL uses
# "tokenizer.vocab_size"-rounds of denoiser module execution, hence extremely long execution time.
# Using large pretrained T5 model as denoiser module will only worsen the runtime issue.
USE_GRAD_KL = 0
# Choose only one of the following training receipes for walk-jump sampling
USE_dWJS_ENERGY = 1
USE_dWJS_SCORE = ~USE_dWJS_ENERGY
# Define parameters
input_dim = 128
model_dim = input_dim
model_dim_ebm = model_dim >> 2 # specific only to EBM model
hidden_dim = 256
num_layers = 4
num_layers_ebm = num_layers >> 1 # specific only to EBM model
num_heads = 8
num_heads_ebm = num_heads >> 2 # specific only to EBM model
num_smc_steps = 5 # sequential monte-carlo (SMC)
N_particles = 10 # sequential monte-carlo (SMC)
hurst = 0.7 # Markov-approximate fractional Brownian motion (MA-fBM)
T_fbm = 1.0 # Markov-approximate fractional Brownian motion (MA-fBM)
n_steps = 1000 # Markov-approximate fractional Brownian motion (MA-fBM)
K_fbm = 3 # Markov-approximate fractional Brownian motion (MA-fBM)
num_walk_steps = 5 # for langevin dynamics MCMC sampling process
num_jump_steps = 20 #num_walk_steps
walk_step_size = 0.6 # for langevin dynamics MCMC sampling process
sigma_max = 1.1
sigma_min = 0.1
num_epochs = 500
batch_size = 512
if USE_PRETRAINED_BERT or USE_PRETRAINED_BERT_MLM:
# BERT model is larger than TransformerDenoiser() module
batch_size = batch_size >> 6
elif USE_PRETRAINED_T5:
# T5 models are way larger than both BERT model and TransformerDenoiser() module
batch_size = 1
elif USE_CUSTOM_TRANSFORMER_ENCODER_DECODER:
# we have extra decoder layers inside the TransformerDenoiser() module
batch_size = batch_size >> 4
else: # USE_CUSTOM_TRANSFORMER_ENCODER
# we do not have extra decoder layers inside the TransformerDenoiser() module
batch_size = batch_size >> 3
#if torch.cuda.is_available(): # so far colab run session has some extra unused GPU RAM on T4 GPU
# batch_size = batch_size << 2 # increasing batch_size worsens the validation loss convergence rate
# Monitors the quality of the generated samples throughout the training and validation
# processes to assess the model's performance and identify potential issues
def analyze_samples(generated_samples, tokenizer, skip_special_tokens=False, num_samples=1):
decoded_samples = []
if num_samples != 1:
num_samples = generated_samples.size(0)
for i in range(num_samples):
sample = generated_samples[i]
sample = sample.long() # Convert the sample to integer tensor
decoded_sample = tokenizer.decode(sample, skip_special_tokens=skip_special_tokens)
print(f"Sample {i+1}: {decoded_sample}")
decoded_samples.append(decoded_sample)
return decoded_samples
def assert_sample_range_compliance(sample, tokenizer):
# Assert that all token IDs are within the valid range
assert sample.min() >= 0, f"Token ID is less than 0! sample = {sample}, sample.min() = {sample.min()}"
assert sample.max() < tokenizer.vocab_size, f"Token ID exceeds valid range! Max ID: {sample.max()}, Vocab Size: {tokenizer.vocab_size}"
# Assert that the tokens input to the model are not all zeros
assert not torch.all(sample == 0), "Error: sample contains all zeros!"
return True
def check_for_vanishing_gradients(model):
for name, param in model.named_parameters():
if param.grad is not None:
grad_norm = param.grad.data.norm(2)
if grad_norm < 1e-5: # Threshold for detecting vanishing gradients
print(f"Warning: Vanishing gradient detected in {name} with norm {grad_norm.item():.6f}")
if USE_PRETRAINED_T5: #or USE_CUSTOM_TRANSFORMER_ENCODER_DECODER or USE_CUSTOM_TRANSFORMER_ENCODER:
tokenizer = AutoTokenizer.from_pretrained("pnawrot/nanoT5-base")
#tokenizer = T5Tokenizer.from_pretrained('google/t5-efficient-tiny')
else:
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
def tokenizer_function(raw_sequence_input, tokenizer, max_length=input_dim):
tokenized_sequence = tokenizer(
raw_sequence_input,
padding='max_length',
truncation=True,
max_length=max_length,
return_tensors="pt"
)
return tokenized_sequence.to(device)
#print(f"tokenizer.pad_token_id = {tokenizer.pad_token_id}")
# for initializing target_label for denoiser module
CONSTANTS_VALUE_IGNORE = tokenizer.pad_token_id # -100
# for creating data loader for span-masking task
class DataCollatorForSpanCorruption:
def __init__(self, tokenizer, mlm_probability=0.15, mean_noise_span_length=3, input_length=input_dim):
self.tokenizer = tokenizer
self.mlm_probability = mlm_probability
self.mean_noise_span_length = mean_noise_span_length
self.input_length = input_length
def __call__(self, examples):
# If examples are tensors, convert them to lists
if isinstance(examples[0], torch.Tensor):
input_ids = [example.tolist() for example in examples]
attention_mask = None # No attention mask for tensor inputs
else:
# Assuming examples are dicts with 'input_ids' keys
input_ids = [example['input_ids'] for example in examples]
attention_mask = [example['attention_mask'] for example in examples] if 'attention_mask' in examples[0] else None
batch = self._collate_batch(input_ids)
# Add attention mask if it exists
if attention_mask is not None:
batch['attention_mask'] = pad_sequence(
[mask.clone().detach() for mask in attention_mask],
batch_first=True,
padding_value=0
)
return batch
def _collate_batch(self, input_ids_list):
# Pad input_ids to the same length
batch_input_ids = pad_sequence(
[ids.clone().detach() for ids in input_ids_list],
batch_first=True,
padding_value=self.tokenizer.pad_token_id
)
# Create masked inputs and labels
if USE_PRETRAINED_T5:
masked_input_ids, labels, mlm_mask = self._mask_tokens_span(batch_input_ids)
return {'input_ids': masked_input_ids, 'labels': labels, 'mask_indices': mlm_mask}
elif USE_PRETRAINED_BERT or USE_PRETRAINED_BERT_MLM:
#labels, mlm_mask = self._mask_tokens_span(batch_input_ids)
labels, mlm_mask = self._mask_tokens_standard(batch_input_ids)
return {'input_ids': batch_input_ids, 'labels': labels, 'mask_indices': mlm_mask}
else: # USE_CUSTOM_TRANSFORMER_ENCODER or USE_CUSTOM_TRANSFORMER_ENCODER_DECODER
#labels, mlm_mask = self._mask_tokens_span(batch_input_ids)
labels, mlm_mask = self._mask_tokens_standard(batch_input_ids)
return {'input_ids': batch_input_ids, 'labels': labels, 'mask_indices': mlm_mask}
# span-masking strategy
def _mask_tokens_span(self, inputs):
"""
Prepare masked tokens inputs/labels for masked span language modeling according to T5's objective.
"""
inputs = inputs.clone()
labels = torch.full(inputs.shape, self.tokenizer.pad_token_id)
special_tokens = {self.tokenizer.pad_token_id}
batch_size, seq_len = inputs.shape
mask_indices = []
# Track masking locations
mask_indices_tensor = torch.zeros_like(inputs, dtype=torch.bool)
for i in range(batch_size):
input_ids = inputs[i].tolist()
num_to_mask = max(1, int(round(seq_len * self.mlm_probability)))
# Get candidate indices to mask
candidate_indices = [
idx for idx in range(len(input_ids)) if input_ids[idx] not in special_tokens
]
# Shuffle candidate indices
random.shuffle(candidate_indices)
masked_indices = set()
current_idx = 0
spans = []
while len(masked_indices) < num_to_mask and current_idx < len(candidate_indices):
span_length = max(1, int(numpy.random.poisson(lam=self.mean_noise_span_length)))
start = candidate_indices[current_idx]
end = min(start + span_length, seq_len)
span_indices = list(range(start, end))
# Avoid overlapping spans
if any(idx in masked_indices for idx in span_indices):
current_idx += 1
continue
masked_indices.update(span_indices)
spans.append((start, end))
current_idx += 1
# Sort spans in reverse order to avoid index shifting issues
spans = sorted(spans, key=lambda x: x[0], reverse=True)
target_tokens = []
prev_end = seq_len
for idx, (start, end) in enumerate(spans):
# Replace span with sentinel token in inputs
if USE_PRETRAINED_T5:
sentinel_token_id = self.tokenizer.convert_tokens_to_ids(f'<extra_id_{idx}>')
else:
sentinel_token_id = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
inputs[i, start:end] = sentinel_token_id
# Build labels
target_tokens = [sentinel_token_id] + input_ids[start:end] + target_tokens
# Record the masked positions
for start, end in spans:
mask_indices_tensor[i, start:end] = True
# Handle unmasked positions in labels
#labels[~mask_indices_tensor] = CONSTANTS_VALUE_IGNORE
#labels[i, :len(target_tokens)] = torch.tensor(target_tokens, dtype=torch.long)
# debug prints
if len(spans) > 0:
total_masked = sum(end - start for start, end in spans)
#print(f"Sequence {i}: Created {len(spans)} spans, masking {total_masked} tokens")
#print(f"Spans: {spans}")
if USE_PRETRAINED_T5:
return inputs, labels, mask_indices_tensor # T5 masking tokens are not unique, so need to return masked "inputs"
else:
return labels, mask_indices_tensor # Return the mask information
# standard BERT masking strategy without any span-masking
def _mask_tokens_standard(self, inputs):
"""
Prepare masked tokens inputs/labels for standard masked language modeling (e.g., BERT).
"""
labels = inputs.clone()
# Create a mask for tokens to mask
probability_matrix = torch.full(labels.shape, self.mlm_probability)
special_tokens_mask = [
self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
]
special_tokens_mask = torch.tensor(special_tokens_mask, dtype=torch.bool)
probability_matrix.masked_fill_(special_tokens_mask, value=0.0)
masked_indices = torch.bernoulli(probability_matrix).bool()
# Set labels for masked tokens, set CONSTANTS_VALUE_IGNORE for others
#labels[~masked_indices] = CONSTANTS_VALUE_IGNORE # We only compute loss on masked tokens
# Replace masked input tokens according to BERT's strategy
# 80% of the time, replace with [MASK]
indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
# 10% of the time, replace with random token
indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
random_words = torch.randint(len(self.tokenizer), inputs.shape, device=device, dtype=torch.long)
indices_random = indices_random.to(device)
inputs[indices_random] = random_words[indices_random]
# The rest 10% of the time, keep the original token (do nothing)
return labels, masked_indices
sigma = 0.5 # single noise level
mask_token_penalty_weight = 1.0 # Increase this value to penalize more heavily
sep_token_penalty_weight = 1.0 # Increase this value to penalize more heavily
unused_token_penalty_weight = 0.005 # Increase this value to penalize more heavily
ebm_energy_regularization_scale = 16 # for L2 regularization on EBM loss
if USE_CUSTOM_TRANSFORMER_ENCODER_DECODER:
ebm_energy_regularization_scale = ebm_energy_regularization_scale << 1 # for L2 regularization on EBM loss
'''
log(Σ exp(x_i)) = log(Σ exp(x_i - C + C))
= log(Σ exp(x_i - C) * exp(C))
= log(exp(C) * Σ exp(x_i - C))
= log(exp(C)) + log(Σ exp(x_i - C))
= C + log(Σ exp(x_i - C))
where C is any constant.
The log_sum_exp() implementation chooses C to be max_val (the maximum value among the x_i values). Here's why this is brilliant:
1. Shifting by max_val: By subtracting max_val from each x_i before exponentiating, we ensure that:
- The largest value among x_i - max_val will be 0 (because max_val - max_val = 0).
- All other values of x_i - max_val will be negative or 0.
2. Avoiding Overflow: Since exp(0) = 1, and exp(x) for negative x is always between 0 and 1, we avoid computing exp() of large positive numbers, thus preventing overflow.
3. Reducing Underflow: While underflow might still occur for extremely small values of exp(x_i - max_val), it's less severe because we are summing these values. The sum is less likely to underflow to zero compared to individual terms.
4. Adding Back max_val: Finally, we add max_val back to the result to compensate for the subtraction we did earlier. This ensures that we get the correct value of log_sum_exp(x_i).
'''
def log_sum_exp(x):
max_val = x.max()
return max_val + torch.log(torch.sum(torch.exp(x - max_val)))
# USE_ROPE = 0
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super(PositionalEncoding, self).__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
self.register_buffer('pe', pe)
def forward(self, x):
#print(f"pe.shape = {self.pe.shape}")
return x + self.pe[:x.size(0), :]
# USE_ROPE = 1
class RotaryEmbedding(nn.Module):
def __init__(self, dim, max_position_embeddings=2048, base=10000):
super().__init__()
inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer('inv_freq', inv_freq)
self.max_position_embeddings = max_position_embeddings
self.dim = dim
def forward(self, seq_len):
positions = torch.arange(seq_len, device=self.inv_freq.device)
sinusoid = torch.einsum('i,j->ij', positions, self.inv_freq)
sin = sinusoid.sin()
cos = sinusoid.cos()
return cos, sin
class RoPEMultiheadAttention(nn.Module):
def __init__(self, d_model, nhead, dropout=0.1, is_causal=False, batch_first=False):
super().__init__()
assert d_model % nhead == 0
self.head_dim = d_model // nhead
self.nhead = nhead
self.d_model = d_model
self.is_causal = is_causal
self.batch_first = batch_first
self.q_proj = nn.Linear(d_model, d_model)
self.k_proj = nn.Linear(d_model, d_model)
self.v_proj = nn.Linear(d_model, d_model)
self.out_proj = nn.Linear(d_model, d_model)
self.dropout = nn.Dropout(dropout)
self.rope = RotaryEmbedding(self.head_dim)
def apply_rotary_emb(self, x, cos, sin):
"""
Apply rotary embeddings to the input tensor using the provided cosine and sine values.
Args:
x (torch.Tensor): Input tensor.
cos (torch.Tensor): Precomputed cosine values.
sin (torch.Tensor): Precomputed sine values.
Returns:
torch.Tensor: Tensor with rotary embeddings applied.
"""
assert x.ndim == 4 # Ensure input is for multi-head attention
#print(f"x.ndim = {x.ndim}")
d = x.shape[3] // 2
x1 = x[..., :d]
x2 = x[..., d:]
y1 = x1 * cos - x2 * sin
y2 = x1 * sin + x2 * cos
return torch.cat([y1, y2], 3).type_as(x)
def forward(self, query, key, value, attn_mask=None, key_padding_mask=None):
if self.batch_first:
batch_size, tgt_len, embed_dim = query.shape
else:
tgt_len, batch_size, embed_dim = query.shape
src_len = key.shape[1]
scaling = float(self.head_dim) ** -0.5
q = self.q_proj(query).view(batch_size, tgt_len, self.nhead, self.head_dim).transpose(1, 2)
k = self.k_proj(key).view(batch_size, src_len, self.nhead, self.head_dim).transpose(1, 2)
v = self.v_proj(value).view(batch_size, src_len, self.nhead, self.head_dim).transpose(1, 2)
# Apply RoPE to Q and K
cos, sin = self.rope(max(src_len, tgt_len))
q = self.apply_rotary_emb(q, cos, sin)
k = self.apply_rotary_emb(k, cos, sin)
# Attention weights
attn = torch.matmul(q, k.transpose(-2, -1)) * scaling
# Apply causal mask for decoder self-attention
if self.is_causal:
causal_mask = torch.triu(torch.ones(tgt_len, tgt_len, dtype=torch.bool, device=q.device), diagonal=1)
attn = attn.masked_fill(causal_mask.unsqueeze(0).unsqueeze(0), float('-inf'))
if attn_mask is not None:
attn += attn_mask
if key_padding_mask is not None:
attn = attn.masked_fill(
key_padding_mask.unsqueeze(1).unsqueeze(2),
float('-inf'),
)
attn = F.softmax(attn, dim=-1)
attn = self.dropout(attn)
# Attention output
output = torch.matmul(attn, v)
#print(f"After attention, output.shape = {output.shape}, tgt_len = {tgt_len}")
# This is for USE_CUSTOM_TRANSFORMER_ENCODER_DECODER or USE_CUSTOM_TRANSFORMER_DECODER
# Before the final reshape, handle the case where tgt_len < embed_dim
if tgt_len < embed_dim:
# Method 1: Pad with zeros to reach embed_dim
padding = torch.zeros(batch_size, self.nhead, embed_dim - tgt_len, self.head_dim, device=output.device)
#print(f"padding.shape = {padding.shape}")
output = torch.cat([output, padding], dim=2)
tgt_len = embed_dim
# OR Method 2: Repeat the output to reach embed_dim
# output = output.repeat_interleave(math.ceil(embed_dim / tgt_len), dim=1)[:, :embed_dim, :]
output = output.transpose(1, 2).contiguous().view(batch_size, tgt_len, embed_dim)
#print(f"After reshape view, output.shape = {output.shape}")
output = self.out_proj(output)
return output
# Encoder Layer: Uses single self-attention (bidirectional)
class RoPETransformerEncoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, batch_first=False):
super().__init__()
# Single self-attention layer (non-causal/bidirectional)
self.self_attn = RoPEMultiheadAttention(d_model, nhead, dropout=dropout, is_causal=False, batch_first=batch_first)
# One set of normalization and feedforward
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
# Two layer norms (pre-attention and pre-FFN)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
# Two dropouts
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
def forward(self, src, src_mask=None, src_key_padding_mask=None, is_causal=False):
x = src
# Single self-attention block
attn_output = self.self_attn(
self.norm1(x), self.norm1(x), self.norm1(x),
attn_mask=src_mask,
key_padding_mask=src_key_padding_mask
)
x = x + self.dropout1(attn_output)
# Single feedforward block
ff_output = self.linear2(self.dropout(F.relu(self.linear1(self.norm2(x)))))
x = x + self.dropout2(ff_output)
return x
# Decoder Layer: Uses both self-attention (causal) and cross-attention
class RoPETransformerDecoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, batch_first=False):
super().__init__()
# Causal self-attention for decoder
self.self_attn = RoPEMultiheadAttention(d_model, nhead, dropout=dropout, is_causal=True, batch_first=batch_first)
# Cross-attention to connect with encoder outputs
self.multihead_attn = RoPEMultiheadAttention(d_model, nhead, dropout=dropout, is_causal=False, batch_first=batch_first)
# Same feedforward as encoder
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
# Three layer norms (pre-self-attn, pre-cross-attn, pre-FFN)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.norm3 = nn.LayerNorm(d_model)
# Three dropouts
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.dropout3 = nn.Dropout(dropout)
def forward(self, tgt, memory, tgt_mask=None, memory_mask=None,
tgt_key_padding_mask=None, memory_key_padding_mask=None,
memory_is_causal=True, tgt_is_causal=True):
x = tgt
# Self-attention block (causal)
attn_output = self.self_attn(
self.norm1(x), self.norm1(x), self.norm1(x),
attn_mask=tgt_mask,
key_padding_mask=tgt_key_padding_mask
)
#print(f"In RoPETransformerDecoderLayer(), x.shape = {x.shape}, attn_output = {attn_output.shape}")
if USE_CUSTOM_TRANSFORMER_ENCODER_DECODER:
x = x.mean(dim=1).unsqueeze(1)
x = x + self.dropout1(attn_output)
# Cross-attention block
cross_attn_output = self.multihead_attn(
self.norm2(x), self.norm2(memory), self.norm2(memory),
attn_mask=memory_mask,
key_padding_mask=memory_key_padding_mask
)
x = x + self.dropout2(cross_attn_output)
# Feedforward block
ff_output = self.linear2(self.dropout(F.relu(self.linear1(self.norm3(x)))))
x = x + self.dropout3(ff_output)
return x
# USE_PRETRAINED_BERT = 1
class BertDenoiser(nn.Module):
def __init__(self, model_dim, use_bert_mlm=USE_PRETRAINED_BERT_MLM): # model_dim == sequence_length
super(BertDenoiser, self).__init__()
self.use_bert_mlm = use_bert_mlm
self.final_layer = nn.Linear(tokenizer.vocab_size, 1)
# SiLU layer
self.SiLU = nn.SiLU()
# ReLU layer
self.ReLU = nn.ReLU()
if self.use_bert_mlm:
self.model = AutoModelForMaskedLM.from_pretrained("prajjwal1/bert-tiny").to(device)
#self.model = AutoModelForMaskedLM.from_pretrained("bert-base-uncased").to(device)
self.config = AutoConfig.from_pretrained("prajjwal1/bert-tiny")
#self.config = AutoConfig.from_pretrained("google-bert/bert-base-cased")
else:
self.model = AutoModel.from_pretrained("prajjwal1/bert-tiny").to(device)
#self.model = AutoModel.from_pretrained("bert-base-uncased").to(device)
self.middle_layer = nn.Linear(self.model.config.hidden_size, tokenizer.vocab_size)
self.dropout = nn.Dropout(0.2) # Add dropout
# Apply Xavier/Glorot or He initialization
#self._initialize_weights()
# Initialize the final layer
#nn.init.xavier_uniform_(self.final_layer_A.weight)
#nn.init.xavier_uniform_(self.final_layer_B.weight)
#nn.init.zeros_(self.final_layer_A.bias)
#nn.init.zeros_(self.final_layer_B.bias)
def initialize_weights(m):
if isinstance(m, nn.Linear):
torch.nn.init.xavier_normal_(m.weight)
if m.bias is not None:
m.bias.data.fill_(0.01)
elif isinstance(m, nn.Conv1d):
torch.nn.init.kaiming_normal_(m.weight, nonlinearity='relu')
if m.bias is not None:
m.bias.data.fill_(0.01)
def _initialize_weights(self):
for name, param in self.named_parameters():
if 'weight' in name:
if isinstance(param, torch.nn.Parameter):
if param.dim() > 1: # Only apply to matrices, not biases
if 'self_attn' in name or 'multihead_attn' in name:
torch.nn.init.xavier_uniform_(param) # Xavier for attention layers
else:
torch.nn.init.kaiming_uniform_(param, nonlinearity='relu') # He for ReLU-based layers
elif 'bias' in name:
torch.nn.init.zeros_(param) # Biases are usually initialized to zero
def forward(self, inputs, mlm_mask=None):
if isinstance(inputs, dict):
# Convert input_ids to long tensor
input_ids = inputs['input_ids'].long()
labels = inputs['labels'].to(device)
attention_mask = inputs['attention_mask']
else:
input_ids = inputs.long()
labels = input_ids.clone().detach()
attention_mask = (input_ids != tokenizer.pad_token_id).long()
#print(f"input_ids.shape = {input_ids.shape}")
if self.use_bert_mlm:
# Process text
outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
labels=labels
).logits
else:
# Process text
outputs = self.model(
input_ids,
attention_mask=attention_mask,
labels=labels
).last_hidden_state # [batch_size, sequence_length, hidden_size=128]
outputs = self.middle_layer(outputs)
# Shape: [batch_size, seq_len, vocab_size]
#print(f"outputs.shape = {outputs.shape}")
outputs = self.dropout(outputs) # Apply dropout
denoised_sentence = self.final_layer(outputs).squeeze(-1) # shape : [batch_size, sequence_length]
# Apply activation function
denoised_sentence = self.SiLU(denoised_sentence)
if mlm_mask is not None:
masked_positions = mlm_mask.bool()
denoised_masked_token_logits = outputs[masked_positions] # shape : [batch_size, vocab_size] if MASK_RATIO = -1
denoised_token_logits = outputs
#print(f"denoised_sentence.shape = {denoised_sentence.shape}, denoised_masked_token_logits.shape = {denoised_masked_token_logits.shape}, denoised_token_logits.shape = {denoised_token_logits.shape}")
if USE_LOGITS_FOR_THE_ENTIRE_SENTENCE: # denoised_token_logits will have a shape of [batch_size, sequence_length, vocab_size]
return denoised_sentence, denoised_masked_token_logits, denoised_token_logits
else:
return denoised_sentence, denoised_masked_token_logits
else:
return denoised_sentence
'''
Original Sentence: "The quick brown fox jumps over the lazy dog."
Masked Encoder Input (input_ids): ['The', 'quick', '‹extra_id_0>', 'jumps', 'over', 'the', '<extra_id_1>', 'dog', '.']
Decoder's Target Output (labels): ['<extra_id_0>', 'brown', 'fox', '<extra_id_1>', 'lazy']
Decoder's Generation Process:
-----------------------------------------------------------------------------------
Time Step | Decoder Input Token | Target Label Token | Prediction Objective
-----------------------------------------------------------------------------------
t=0 | ‹pad> | ‹extra_id_0> | Predict < extra_id_0>
t=1 | ‹extra_id_0> | brown | Predict brown
t=2 | brown | fox | Predict fox
t=3 | fox | ‹extra_id_ 1> | Predict < extra_id_1›
t=4 | ‹extra_id_ 1> | lazy | Predict lazy
-----------------------------------------------------------------------------------
Note: There are no timesteps corresponding to 'jumps', 'over', 'the' in the decoder's output because these tokens are unmasked and present in the encoder input.
'''
# USE_PRETRAINED_T5 = 1
class T5Denoiser(nn.Module):
def __init__(self, model_dim):
super(T5Denoiser, self).__init__()
#self.model = T5ForConditionalGeneration.from_pretrained('google/t5-efficient-tiny')
self.model = AutoModelForSeq2SeqLM.from_pretrained("pnawrot/nanoT5-base")
# Projection layer to map logits space back to sequence_length (which is same as model_sim)
self.projection_A = nn.Sequential(
nn.Linear(self.model.config.vocab_size, model_dim),
#nn.ReLU() # no need of activation function before being fed into cross-entropy loss function
)
# Projection layer to map logits space back to a single token embedding
self.projection_B = nn.Sequential(
nn.Linear(self.model.config.vocab_size, 1),
#nn.ReLU() # no need of activation function before being fed into cross-entropy loss function
)
def forward(self, input_ids, target_label=None, decoder_input_ids=None, mlm_mask=None):
if decoder_input_ids is not None:
# Shift tgt to the right to create decoder input ids
decoder_input_ids = self.model._shift_right(decoder_input_ids)
else:
batch_size = input_ids.size(0)
# Use the decoder start token and expand it to match the batch size
# If tgt is not provided, use the BOS token as the initial input for decoder
decoder_start_token = torch.tensor([[self.model.config.decoder_start_token_id]], device=device)
decoder_input_ids = torch.full((batch_size, 1), self.model.config.decoder_start_token_id, device=device)
decoder_input_ids = torch.cat((decoder_input_ids, decoder_start_token.expand(batch_size, -1)), dim=1)
#print(f"decoder_input_ids.shape = {decoder_input_ids.shape}")
# Generate output logits
# We do not need to manually feed in decoder_input_ids, we let the model handles them internally during training
output = self.model(input_ids=input_ids.long(), labels=target_label)
#output = self.model(input_ids=input_ids.long(), decoder_input_ids=decoder_input_ids.long())
output = output.logits # shape : [batch_size, tgt_sequence_length, vocab_size]
#print(f"output.shape = {output.shape}")
if ENABLE_MASK_LEARNING: # there is a new token concatenated to tgt tensor
# Get the most recent timestep prediction
# We want to update denoised_sentence based on the prediction for the last token in the sequence
denoised_sentence = output[:, -1, :] # Select the last timestep
else:
# Remove unnecessary dimension
denoised_sentence = output.squeeze(1)
#print(f"denoised_sentence.shape = {denoised_sentence.shape}")
# denoised_sentence has a shape of [batch_size, vocab_size]
# projection_A layer uses almost same amount of RAM as projection_B layer (which relies on broadcast operation)
# We should not use torch.max() because introduces non-differentiable points, hindering gradient-based optimization.
# Besides, only the maximum value receives a gradient; all other inputs get zero gradients, which is inefficient for learning.
if mlm_mask is not None:
if USE_LOGITS_FOR_THE_ENTIRE_SENTENCE: # denoised_token_logits will have a shape of [batch_size, sequence_length, vocab_size]
denoised_token_logits = output
denoised_masked_token_logits = denoised_sentence
denoised_sentence = self.projection_A(denoised_sentence) # shape : [batch_size, sequence_length]
#denoised_sentence = self.projection_B(denoised_sentence) # shape : [batch_size, 1]
#denoised_sentence, _ = torch.max(denoised_sentence, dim=-1, keepdim=True) # shape : [batch_size, 1]
return denoised_sentence, denoised_masked_token_logits, denoised_token_logits
else:
denoised_masked_token_logits = denoised_sentence
denoised_sentence = self.projection_A(denoised_sentence) # shape : [batch_size, sequence_length]
#denoised_sentence = self.projection_B(denoised_sentence) # shape : [batch_size, 1]
#denoised_sentence, _ = torch.max(denoised_sentence, dim=-1, keepdim=True) # shape : [batch_size, 1]
return denoised_sentence, denoised_masked_token_logits
else:
denoised_sentence = self.projection_A(denoised_sentence) # shape : [batch_size, sequence_length]
#denoised_sentence = self.projection_B(denoised_sentence) # shape : [batch_size, 1]
#denoised_sentence, _ = torch.max(denoised_sentence, dim=-1, keepdim=True) # shape : [batch_size, 1]
return denoised_sentence
# USE_CUSTOM_TRANSFORMER_ENCODER_DECODER or USE_CUSTOM_TRANSFORMER_ENCODER
class TransformerDenoiser(nn.Module):
def __init__(self, input_dim, model_dim, num_layers, num_heads, max_noise_level):
super(TransformerDenoiser, self).__init__()
self.embedding = nn.Embedding(tokenizer.vocab_size, model_dim)
#self.noise_level_embeddings = nn.Embedding(max_noise_level, model_dim)
if not USE_ROPE:
self.pos_encoder = PositionalEncoding(model_dim)
self.pos_decoder = PositionalEncoding(model_dim)
if USE_ROPE:
# Use RoPE Transformer Encoder layers
encoder_layers = RoPETransformerEncoderLayer(
model_dim,
num_heads,
model_dim,
batch_first=True
)
# Use RoPE Transformer Decoder layers
decoder_layers = RoPETransformerDecoderLayer(
model_dim,
num_heads,
model_dim,
batch_first=True
)
else:
# Use Transformer Encoder Layers from Pytorch library
encoder_layers = nn.TransformerEncoderLayer(model_dim, num_heads, model_dim, batch_first=True)
# Use Transformer Decoder Layers from Pytorch library
decoder_layers = nn.TransformerDecoderLayer(model_dim, num_heads, model_dim, batch_first=True)
self.transformer_encoder = nn.TransformerEncoder(encoder_layers, num_layers)
self.transformer_decoder = nn.TransformerDecoder(decoder_layers, num_layers)
# Layer Normalization to prevent vanishing gradients
self.norm = nn.LayerNorm(model_dim)
# SiLU layer
self.SiLU = nn.SiLU()
#Sigmoid layer
#self.Sigmoid = nn.Sigmoid()
"""
# Projection layer to map single token embedding back to logits space
self.projection = nn.Sequential(
nn.Linear(1, tokenizer.vocab_size),
#nn.ReLU() # no need of activation function before being fed into cross-entropy loss function
)
"""
# Projection layer (tie weights with embedding)
self.projection = nn.Linear(model_dim, tokenizer.vocab_size)
self.projection.weight = self.embedding.weight # Weight tying
"""
self.denoise_head = nn.Sequential(
nn.Linear(model_dim, model_dim),
nn.ReLU()
)
"""
# Convolutional denoise head does not depend on input_dim or
# input sequence length. This is helpful in NLP domain, because the
# NLP model will see varying input sequence length
# Weight normalization is one technique to address vanishing gradients
self.denoise_head = nn.Sequential(
weight_norm(nn.Conv1d(in_channels=model_dim, out_channels=model_dim, kernel_size=3, padding=1)),
#nn.SiLU(),
#weight_norm(nn.Conv1d(in_channels=model_dim, out_channels=model_dim, kernel_size=3, padding=1)),
#nn.SiLU(),
#weight_norm(nn.Conv1d(in_channels=model_dim, out_channels=model_dim, kernel_size=3, padding=1)),
#nn.ReLU()
)
# Apply Xavier/Glorot or He initialization
self._initialize_weights()
def initialize_weights(m):
if isinstance(m, nn.Linear):
torch.nn.init.xavier_normal_(m.weight)
if m.bias is not None:
m.bias.data.fill_(0.01)
elif isinstance(m, nn.Conv1d):
torch.nn.init.kaiming_normal_(m.weight, nonlinearity='relu')
if m.bias is not None:
m.bias.data.fill_(0.01)
def _initialize_weights(self):
for name, param in self.named_parameters():
if 'weight' in name:
if isinstance(param, torch.nn.Parameter):
if param.dim() > 1: # Only apply to matrices, not biases
if 'self_attn' in name or 'multihead_attn' in name:
torch.nn.init.xavier_uniform_(param) # Xavier for attention layers
else:
torch.nn.init.kaiming_uniform_(param, nonlinearity='relu') # He for ReLU-based layers
elif 'bias' in name:
torch.nn.init.zeros_(param) # Biases are usually initialized to zero
#nn.init.xavier_uniform_(self.projection[0].weight)
#nn.init.zeros_(self.projection[0].bias)
# for decoder only
def _shift_right(self, input_ids, start_token_id):
"""
Shift input_ids to the right by one position and prepend the start_token_id.
"""
shifted_input_ids = input_ids.new_zeros(input_ids.size())
shifted_input_ids[:, 0] = start_token_id
shifted_input_ids[:, 1:] = input_ids[:, :-1]
return shifted_input_ids
def forward(self, inputs, tgt=None, input_pad_mask=None, mlm_mask=None):
if isinstance(inputs, dict):
src = inputs['input_ids']
else:
src = inputs
# src: [batch_size, sequence_length]
# Embed input tokens
src = self.embedding(src.long()) # [batch_size, sequence_length, model_dim]
#print(f"After nn.embedding(), src.shape = {src.shape}")
# Saves memory
del inputs
# Add sequence length dimension
#src = src.unsqueeze(1)
if tgt is not None:
#tgt = tgt.unsqueeze(2)
# Determine the start token ID based on tokenizer and model
if USE_PRETRAINED_T5:
start_token_id = tokenizer.pad_token_id # T5 uses pad_token_id as start token
else:
start_token_id = tokenizer.cls_token_id # BERT uses cls_token_id as start token