sgoel30 commited on
Commit
fedcb95
·
verified ·
1 Parent(s): bce7ea6

Upload 4 files

Browse files
scripts/diffusion.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import math
3
+ import torch
4
+ import torch.nn as nn
5
+ import numpy as np
6
+ import pytorch_lightning as L
7
+ import torchmetrics
8
+ from dataclasses import dataclass
9
+ from esm_utils import load_esm2_model
10
+ from transformers import AutoModelForMaskedLM, AutoModel, AutoTokenizer
11
+ import dit, ema
12
+ import sys
13
+ import config
14
+ import wandb
15
+ import noise_schedule # Assuming this is part of the MDLM repository
16
+
17
+ wandb_key = "2b76a2fa2c1cdfddc5f443602c17b011fefb0a8f"
18
+ wandb.login(key=wandb_key)
19
+ wandb.init(project=config.Wandb.PROJECT, group=config.Wandb.GROUP)
20
+
21
+ LOG2 = math.log(2)
22
+
23
+ # Goal is to build an MDLM head using pre-existing ESM LM head
24
+ # Wrap the ESM model to obtain logits and ignore sigma to work with MDLM codebase
25
+ class WrapESM(nn.Module):
26
+ def __init__(self, esm_model_path=config.MODEL_NAME):
27
+ super(WrapESM, self).__init__()
28
+ self.model = AutoModelForMaskedLM.from_pretrained(esm_model_path)
29
+ self.tokenizer = AutoTokenizer.from_pretrained(esm_model_path)
30
+
31
+ # def __getattr__(self, name):
32
+ # return getattr(self.model, name)
33
+
34
+ def __call__(self, *args, **kwargs):
35
+ return self.model(*args, **kwargs)
36
+
37
+ def freeze_model(self):
38
+ # Disable parameter updates for all layers
39
+ for param in self.model.parameters():
40
+ param.requires_grad = False
41
+
42
+ def unfreeze_n_layers(self):
43
+ # Count number of encoder layers
44
+ model_layers = len(self.model.esm.encoder.layer)
45
+
46
+ # Enable parameter updates for the last 3 encoder layers
47
+ for i, layer in enumerate(self.model.esm.encoder.layer):
48
+ if i >= model_layers-config.ESM_LAYERS:
49
+ for module in layer.attention.self.key.modules():
50
+ for param in module.parameters():
51
+ param.requires_grad = True
52
+ for module in layer.attention.self.query.modules():
53
+ for param in module.parameters():
54
+ param.requires_grad = True
55
+ for module in layer.attention.self.value.modules():
56
+ for param in module.parameters():
57
+ param.requires_grad = True
58
+
59
+ def forward(self, sigma, **inputs):
60
+ return self.model(**inputs)
61
+
62
+ def save_model(self, save_dir):
63
+ self.model.save_pretrained(save_dir)
64
+ self.tokenizer.save_pretrained(save_dir)
65
+
66
+ def load_model(self, load_dir):
67
+ self.model = AutoModel.from_pretrained(load_dir)
68
+ self.tokenizer = AutoTokenizer.from_pretrained(load_dir)
69
+
70
+ @dataclass
71
+ class Loss:
72
+ loss: torch.FloatTensor
73
+ nlls: torch.FloatTensor
74
+ token_mask: torch.FloatTensor
75
+
76
+ class NLL(torchmetrics.MeanMetric):
77
+ pass
78
+
79
+ class BPD(NLL):
80
+ def compute(self) -> torch.Tensor:
81
+ """Computes the bits per dimension.
82
+ Returns:
83
+ bpd
84
+ """
85
+ return self.mean_value / self.weight / LOG2
86
+
87
+ class Perplexity(NLL):
88
+ def compute(self) -> torch.Tensor:
89
+ """Computes the Perplexity.
90
+ Returns:
91
+ Perplexity
92
+ """
93
+ return torch.exp(self.mean_value / self.weight)
94
+
95
+
96
+ # Based on MDLM repo
97
+ class Diffusion(L.LightningModule):
98
+ def __init__(self, config, tokenizer):
99
+ super().__init__()
100
+ self.config = config
101
+ self.tokenizer = tokenizer
102
+
103
+ self.softplus = torch.nn.Softplus()
104
+ metrics = torchmetrics.MetricCollection({
105
+ 'nll': NLL(),
106
+ 'bpd': BPD(),
107
+ 'ppl': Perplexity(),
108
+ })
109
+ metrics.set_dtype(torch.float64)
110
+ self.train_metrics = metrics.clone(prefix='train/')
111
+ self.valid_metrics = metrics.clone(prefix='val/')
112
+ self.test_metrics = metrics.clone(prefix='test/')
113
+
114
+ self.T = self.config.T
115
+ self.lr = self.config.Optim.LR
116
+ self.backbone = WrapESM(self.config.MODEL_NAME)
117
+ self.noise = noise_schedule.get_noise(self.config, dtype=self.dtype)
118
+ self.time_conditioning = self.config.TIME_CONDITIONING
119
+ self.subs_masking = self.config.SUBS_MASKING
120
+ self.mask_index = self.tokenizer.mask_token_id
121
+ self.antithetic_sampling = self.config.Training.ANTITHETIC_SAMPLING
122
+ self.sampling_eps = self.config.Training.SAMPLING_EPS
123
+ self.neg_infinity = -1000000.0
124
+
125
+
126
+ ############ FORWARD DIFFUSION #########
127
+ def compute_loss(self, latents, attention_mask, val):
128
+ """"Average of MLM losses to stabilize training"""
129
+ self.noise.eval() if val else self.noise.train()
130
+ loss = self.forward_diffusion(latents)
131
+
132
+ nlls = loss * attention_mask
133
+ count = attention_mask.sum()
134
+ batch_nll = nlls.sum()
135
+ token_nll = batch_nll / count
136
+
137
+ return Loss(loss=token_nll, nlls=nlls, token_mask=attention_mask)
138
+
139
+ def forward_diffusion(self, x0):
140
+ """Forward diffusion process, adds noise to the latents."""
141
+ t = self.sample_timestep(x0.shape[0], x0.device)
142
+
143
+ sigma, dsigma = self.noise(t)
144
+ unet_conditioning = sigma[:, None]
145
+ move_chance = 1 - torch.exp(-sigma[:, None])
146
+
147
+ xt = self.q_xt(x0, move_chance)
148
+ model_output = self.forward(xt, unet_conditioning)
149
+
150
+ # SUBS parameterization, continuous time.
151
+ log_p_theta = torch.gather(input=model_output, dim=-1, index=x0[:, :, None]).squeeze(-1)
152
+ scale = (dsigma / torch.expm1(sigma))[:, None]
153
+ loss = - log_p_theta * scale
154
+ return loss
155
+
156
+ def sample_timestep(self, n, device):
157
+ _eps_t = torch.rand(n, device=device)
158
+ if self.antithetic_sampling:
159
+ offset = torch.arange(n, device=device) / n
160
+ _eps_t = (_eps_t / n + offset) % 1
161
+ t = (1 - self.sampling_eps) * _eps_t + self.sampling_eps
162
+ return t
163
+
164
+ def q_xt(self, x, move_chance):
165
+ """
166
+ Computes the noisy sample xt.
167
+ Args:
168
+ x: int torch.Tensor with shape (batch_size, diffusion_model_input_length), input.
169
+ move_chance: float torch.Tensor with shape (batch_size, 1).
170
+ """
171
+ move_indices = torch.rand(* x.shape, device=x.device) < move_chance
172
+ xt = torch.where(move_indices, self.mask_index, x) # Use variable masking rate to mask tokens (introduce noise)
173
+ return xt
174
+
175
+ def forward(self, latents, sigma):
176
+ esm_outputs = self.backbone(latents, sigma)
177
+ optimized_logits = self.subs_parameterization(esm_outputs.logits, latents)
178
+ return optimized_logits
179
+
180
+ def subs_parameterization(self, logits, xt):
181
+ logits[:, :, self.mask_index] += self.neg_infinity
182
+ logits = logits - torch.logsumexp(logits, dim=-1, keepdim=True)
183
+
184
+ unmasked_indices = (xt != self.mask_index)
185
+ logits[unmasked_indices] = self.neg_infinity
186
+ logits[unmasked_indices, xt[unmasked_indices]] = 0
187
+ return logits
188
+
189
+
190
+ ######### GENERATION #########
191
+ def sample_prior(self, *batch_dims):
192
+ return self.mask_index * torch.ones(* batch_dims, dtype=torch.int64)
193
+
194
+ def sample_categorical(categorical_probs):
195
+ gumbel_norm = (1e-10 - (torch.rand_like(categorical_probs) + 1e-10).log())
196
+ return (categorical_probs / gumbel_norm).argmax(dim=-1)
197
+
198
+ def ddpm_caching_update(self, x, t, dt, p_x0=None):
199
+ sigma_t, _ = self.noise(t)
200
+ if t.ndim > 1:
201
+ t = t.squeeze(-1)
202
+ assert t.ndim == 1
203
+ move_chance_t = t[:, None, None]
204
+ move_chance_s = (t - dt)[:, None, None]
205
+ assert move_chance_t.ndim == 3, move_chance_t.shape
206
+ if p_x0 is None:
207
+ p_x0 = self.forward(x, sigma_t).exp()
208
+
209
+ assert move_chance_t.ndim == p_x0.ndim
210
+ q_xs = p_x0 * (move_chance_t - move_chance_s)
211
+ q_xs[:, :, self.mask_index] = move_chance_s[:, :, 0]
212
+ _x = self.sample_categorical(q_xs)
213
+
214
+ copy_flag = (x != self.mask_index).to(x.dtype)
215
+ return p_x0, copy_flag * x + (1 - copy_flag) * _x
216
+
217
+
218
+ @torch.no_grad()
219
+ def sample_subs_guidance(self, n_samples, stride_length, num_strides, dt=0.001):
220
+ ones = torch.ones(n_samples, dtype=self.dtype,device=self.device)
221
+ num_steps = int(1 / dt)
222
+ sampling_steps = 0
223
+ intermediate_tokens = []
224
+ target = None
225
+
226
+ for _ in range(num_strides + 1):
227
+ p_x0_cache = None
228
+ x = self.sample_prior(n_samples,self.config.model.length).to(self.device)
229
+
230
+ if target is not None:
231
+ x[:, : -stride_length] = target
232
+
233
+ for i in range(num_steps + 1):
234
+ p_x0_cache, x_next = self.ddpm_caching_update(x=x, t=(1 - i * dt) * ones, dt=dt, p_x0=p_x0_cache)
235
+ if (not torch.allclose(x_next, x) or self.time_conditioning):
236
+ p_x0_cache = None
237
+ sampling_steps += 1
238
+ x = x_next
239
+ x = self.forward(x, 0 * ones).argmax(dim=-1)
240
+ intermediate_tokens.append(x[:, :stride_length].cpu().numpy())
241
+ target = x[:, stride_length:]
242
+
243
+ intermediate_tokens.append(target.cpu().numpy())
244
+ intermediate_text_samples = []
245
+ sequence_lengths = ((np.concatenate(intermediate_tokens, axis=1)[:, 1:]
246
+ == self.tokenizer.eos_token_id).cumsum(-1) == 0).sum(-1)
247
+
248
+ for i in range(2, len(intermediate_tokens) + 1):
249
+ intermediate_text_samples.append(self.tokenizer.decode(np.concatenate(intermediate_tokens[:i], axis=1)))
250
+
251
+ return (sampling_steps, intermediate_text_samples,
252
+ sequence_lengths)
253
+
254
+ def restore_model_and_semi_ar_sample(self, stride_length, num_strides, dt=0.001):
255
+ """Generate samples from the model."""
256
+ # Lightning auto-casting is not working in this method for some reason
257
+ self.backbone.eval()
258
+ self.noise.eval()
259
+
260
+ (sampling_steps, samples, sequence_lengths) = self.sample_subs_guidance(n_samples=self.config.Loader.BATCH_SIZE,stride_length=stride_length,num_strides=num_strides,dt=dt)
261
+
262
+ self.backbone.train()
263
+ self.noise.train()
264
+ return sampling_steps, samples, sequence_lengths
scripts/generate.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from transformers import AutoTokenizer, AutoModel
4
+ from diffusion import Diffusion
5
+ import config
6
+ from esm_utils import load_esm2_model, get_latents
7
+
8
+ def mask_sequence(sequence, mask_char='X'):
9
+ """Masks parts of the sequence based on the mask_char."""
10
+ mask_indices = [i for i, char in enumerate(sequence) if char == mask_char]
11
+ masked_sequence = sequence.replace(mask_char, '[MASK]')
12
+ return masked_sequence, mask_indices
13
+
14
+ def generate_filled_sequence(model, tokenizer, esm_model, masked_sequence, mask_indices):
15
+ """Generates the filled sequence for the masked regions."""
16
+ inputs = tokenizer(masked_sequence, return_tensors="pt")
17
+ with torch.no_grad():
18
+ outputs = esm_model(**inputs)
19
+ latents = outputs.last_hidden_state.squeeze(0)
20
+
21
+ sigma = torch.rand(1, device=latents.device)
22
+ noisy_latents = model.forward(latents, sigma)
23
+ denoised_latents = model.reverse_diffusion(noisy_latents, sigma)
24
+
25
+ filled_sequence = list(masked_sequence)
26
+ for idx in mask_indices:
27
+ token_id = torch.argmax(denoised_latents[idx]).item()
28
+ filled_sequence[idx] = tokenizer.decode([token_id])
29
+
30
+ return ''.join(filled_sequence)
31
+
32
+ def generate_scaffold_sequence(model, tokenizer, esm_model, peptides, final_length):
33
+ """Generates a scaffold sequence to connect multiple peptides."""
34
+ total_peptide_length = sum(len(peptide) for peptide in peptides)
35
+ scaffold_length = final_length - total_peptide_length
36
+ if scaffold_length <= 0:
37
+ raise ValueError("Final length must be greater than the combined length of the peptides.")
38
+
39
+ scaffold = "[MASK]" * scaffold_length
40
+ masked_sequence = "".join(peptides[:1] + [scaffold] + peptides[1:])
41
+
42
+ inputs = tokenizer(masked_sequence, return_tensors="pt")
43
+ with torch.no_grad():
44
+ outputs = esm_model(**inputs)
45
+ latents = outputs.last_hidden_state.squeeze(0)
46
+
47
+ sigma = torch.rand(1, device=latents.device)
48
+ noisy_latents = model.forward(latents, sigma)
49
+ denoised_latents = model.reverse_diffusion(noisy_latents, sigma)
50
+
51
+ filled_sequence = list(masked_sequence)
52
+ scaffold_start = len(peptides[0])
53
+ scaffold_end = scaffold_start + scaffold_length
54
+ for idx in range(scaffold_start, scaffold_end):
55
+ token_id = torch.argmax(denoised_latents[idx]).item()
56
+ filled_sequence[idx] = tokenizer.decode([token_id])
57
+
58
+ return ''.join(filled_sequence)
59
+
60
+ def generate_de_novo_sequence(model, tokenizer, esm_model, sequence_length):
61
+ """Generates a de novo protein sequence of the specified length."""
62
+ scaffold = "[MASK]" * sequence_length
63
+ masked_sequence = scaffold
64
+
65
+ inputs = tokenizer(masked_sequence, return_tensors="pt")
66
+ with torch.no_grad():
67
+ outputs = esm_model(**inputs)
68
+ latents = outputs.last_hidden_state.squeeze(0)
69
+
70
+ sigma = torch.rand(1, device=latents.device)
71
+ noisy_latents = model.forward(latents, sigma)
72
+ denoised_latents = model.reverse_diffusion(noisy_latents, sigma)
73
+
74
+ filled_sequence = list(masked_sequence)
75
+ for idx in range(sequence_length):
76
+ token_id = torch.argmax(denoised_latents[idx]).item()
77
+ filled_sequence[idx] = tokenizer.decode([token_id])
78
+
79
+ return ''.join(filled_sequence)
80
+
81
+ if __name__ == "__main__":
82
+ import argparse
83
+
84
+ # Argument parsing
85
+ parser = argparse.ArgumentParser(description="Generate protein sequences using latent diffusion model.")
86
+ subparsers = parser.add_subparsers(dest="mode")
87
+
88
+ # Subparser for the first strategy (multiple peptides to scaffold)
89
+ parser_scaffold = subparsers.add_parser("scaffold", help="Generate scaffold to connect multiple peptides.")
90
+ parser_scaffold.add_argument("peptides", nargs='+', help="Peptides to connect.")
91
+ parser_scaffold.add_argument("final_length", type=int, help="Final length of the protein sequence.")
92
+
93
+ # Subparser for the second strategy (fill in regions)
94
+ parser_fill = subparsers.add_parser("fill", help="Fill in specified regions in a given protein sequence.")
95
+ parser_fill.add_argument("sequence", help="Protein sequence with regions to fill specified by 'X'.")
96
+
97
+ # Subparser for the third strategy (de novo generation)
98
+ parser_de_novo = subparsers.add_parser("de_novo", help="Generate a de novo protein sequence.")
99
+ parser_de_novo.add_argument("sequence_length", type=int, help="Length of the de novo generated protein sequence.")
100
+
101
+ args = parser.parse_args()
102
+
103
+ # Load models
104
+ tokenizer, esm_model = load_esm2_model(config.MODEL_NAME)
105
+ diffusion_model = Diffusion.load_from_checkpoint(config.Training.SAVE_DIR + "best_model.ckpt", config=config, latent_dim=config.LATENT_DIM)
106
+ diffusion_model.eval()
107
+
108
+ if args.mode == "scaffold":
109
+ peptides = args.peptides
110
+ final_length = args.final_length
111
+ filled_sequence = generate_scaffold_sequence(diffusion_model, tokenizer, esm_model, peptides, final_length)
112
+ print(f"Peptides: {' '.join(peptides)}")
113
+ print(f"Final Length: {final_length}")
114
+ print(f"Generated Protein: {filled_sequence}")
115
+
116
+ elif args.mode == "fill":
117
+ sequence = args.sequence
118
+ masked_sequence, mask_indices = mask_sequence(sequence)
119
+ filled_sequence = generate_filled_sequence(diffusion_model, tokenizer, esm_model, masked_sequence, mask_indices)
120
+ print(f"Original Sequence: {sequence}")
121
+ print(f"Masked Sequence: {masked_sequence}")
122
+ print(f"Filled Sequence: {filled_sequence}")
123
+
124
+ elif args.mode == "de_novo":
125
+ sequence_length = args.sequence_length
126
+ filled_sequence = generate_de_novo_sequence(diffusion_model, tokenizer, esm_model, sequence_length)
127
+ print(f"De Novo Sequence Length: {sequence_length}")
128
+ print(f"Generated Protein: {filled_sequence}")
129
+
scripts/noise_schedule.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ # Flags required to enable jit fusion kernels
7
+ torch._C._jit_set_profiling_mode(False)
8
+ torch._C._jit_set_profiling_executor(False)
9
+ torch._C._jit_override_can_fuse_on_cpu(True)
10
+ torch._C._jit_override_can_fuse_on_gpu(True)
11
+
12
+
13
+ def get_noise(config, dtype=torch.float32):
14
+ return LogLinearNoise()
15
+
16
+ if config.noise.type == 'geometric':
17
+ return GeometricNoise(config.noise.sigma_min,
18
+ config.noise.sigma_max)
19
+ elif config.noise.type == 'loglinear':
20
+ return LogLinearNoise()
21
+ elif config.noise.type == 'cosine':
22
+ return CosineNoise()
23
+ elif config.noise.type == 'cosinesqr':
24
+ return CosineSqrNoise()
25
+ elif config.noise.type == 'linear':
26
+ return Linear(config.noise.sigma_min,
27
+ config.noise.sigma_max,
28
+ dtype)
29
+ else:
30
+ raise ValueError(f'{config.noise.type} is not a valid noise')
31
+
32
+
33
+ def binary_discretization(z):
34
+ z_hard = torch.sign(z)
35
+ z_soft = z / torch.norm(z, dim=-1, keepdim=True)
36
+ return z_soft + (z_hard - z_soft).detach()
37
+
38
+
39
+ class Noise(abc.ABC, nn.Module):
40
+ """
41
+ Baseline forward method to get the total + rate of noise at a timestep
42
+ """
43
+ def forward(self, t):
44
+ # Assume time goes from 0 to 1
45
+ return self.total_noise(t), self.rate_noise(t)
46
+
47
+ @abc.abstractmethod
48
+ def rate_noise(self, t):
49
+ """
50
+ Rate of change of noise ie g(t)
51
+ """
52
+ pass
53
+
54
+ @abc.abstractmethod
55
+ def total_noise(self, t):
56
+ """
57
+ Total noise ie \int_0^t g(t) dt + g(0)
58
+ """
59
+ pass
60
+
61
+
62
+ class CosineNoise(Noise):
63
+ def __init__(self, eps=1e-3):
64
+ super().__init__()
65
+ self.eps = eps
66
+
67
+ def rate_noise(self, t):
68
+ cos = (1 - self.eps) * torch.cos(t * torch.pi / 2)
69
+ sin = (1 - self.eps) * torch.sin(t * torch.pi / 2)
70
+ scale = torch.pi / 2
71
+ return scale * sin / (cos + self.eps)
72
+
73
+ def total_noise(self, t):
74
+ cos = torch.cos(t * torch.pi / 2)
75
+ return - torch.log(self.eps + (1 - self.eps) * cos)
76
+
77
+
78
+ class CosineSqrNoise(Noise):
79
+ def __init__(self, eps=1e-3):
80
+ super().__init__()
81
+ self.eps = eps
82
+
83
+ def rate_noise(self, t):
84
+ cos = (1 - self.eps) * (
85
+ torch.cos(t * torch.pi / 2) ** 2)
86
+ sin = (1 - self.eps) * torch.sin(t * torch.pi)
87
+ scale = torch.pi / 2
88
+ return scale * sin / (cos + self.eps)
89
+
90
+ def total_noise(self, t):
91
+ cos = torch.cos(t * torch.pi / 2) ** 2
92
+ return - torch.log(self.eps + (1 - self.eps) * cos)
93
+
94
+
95
+ class Linear(Noise):
96
+ def __init__(self, sigma_min=0, sigma_max=10, dtype=torch.float32):
97
+ super().__init__()
98
+ self.sigma_min = torch.tensor(sigma_min, dtype=dtype)
99
+ self.sigma_max = torch.tensor(sigma_max, dtype=dtype)
100
+
101
+ def rate_noise(self, t):
102
+ return self.sigma_max - self.sigma_min
103
+
104
+ def total_noise(self, t):
105
+ return self.sigma_min + t * (self.sigma_max - self.sigma_min)
106
+
107
+ def importance_sampling_transformation(self, t):
108
+ f_T = torch.log1p(- torch.exp(- self.sigma_max))
109
+ f_0 = torch.log1p(- torch.exp(- self.sigma_min))
110
+ sigma_t = - torch.log1p(- torch.exp(t * f_T + (1 - t) * f_0))
111
+ return (sigma_t - self.sigma_min) / (
112
+ self.sigma_max - self.sigma_min)
113
+
114
+
115
+ class GeometricNoise(Noise):
116
+ def __init__(self, sigma_min=1e-3, sigma_max=1):
117
+ super().__init__()
118
+ self.sigmas = 1.0 * torch.tensor([sigma_min, sigma_max])
119
+
120
+ def rate_noise(self, t):
121
+ return self.sigmas[0] ** (1 - t) * self.sigmas[1] ** t * (
122
+ self.sigmas[1].log() - self.sigmas[0].log())
123
+
124
+ def total_noise(self, t):
125
+ return self.sigmas[0] ** (1 - t) * self.sigmas[1] ** t
126
+
127
+
128
+ class LogLinearNoise(Noise):
129
+ """Log Linear noise schedule.
130
+
131
+ Built such that 1 - 1/e^(n(t)) interpolates between 0 and
132
+ ~1 when t varies from 0 to 1. Total noise is
133
+ -log(1 - (1 - eps) * t), so the sigma will be
134
+ (1 - eps) * t.
135
+ """
136
+ def __init__(self, eps=1e-3):
137
+ super().__init__()
138
+ self.eps = eps
139
+ self.sigma_max = self.total_noise(torch.tensor(1.0))
140
+ self.sigma_min = self.eps + self.total_noise(torch.tensor(0.0))
141
+
142
+ def rate_noise(self, t):
143
+ return (1 - self.eps) / (1 - (1 - self.eps) * t)
144
+
145
+ def total_noise(self, t):
146
+ return -torch.log1p(-(1 - self.eps) * t)
147
+
148
+ def importance_sampling_transformation(self, t):
149
+ f_T = torch.log1p(- torch.exp(- self.sigma_max))
150
+ f_0 = torch.log1p(- torch.exp(- self.sigma_min))
151
+ sigma_t = - torch.log1p(- torch.exp(t * f_T + (1 - t) * f_0))
152
+ t = - torch.expm1(- sigma_t) / (1 - self.eps)
153
+ return t
scripts/train_pytorch.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import config
3
+ import math
4
+ import sys
5
+ import os
6
+ from tqdm import tqdm
7
+ from torch.optim import AdamW
8
+ from transformers import AutoTokenizer
9
+ from diffusion import WrapESM, Diffusion
10
+ from data_loader import get_dataloaders
11
+
12
+ def save_hyperparams(ckpt_dir):
13
+ hyperparms_txt_file = os.path.join(ckpt_dir, "hyperparameters.txt")
14
+ with open(hyperparms_txt_file, 'w') as f:
15
+ for k, v in vars(config).items():
16
+ if k.isupper():
17
+ f.write(f"{k}: {v}\n")
18
+
19
+ def train_and_validate(model, optimizer, device, train_loader, val_loader, num_epochs, ckpt_dir):
20
+ best_val_loss = float('inf')
21
+
22
+ for epoch in range(num_epochs):
23
+ model.train()
24
+
25
+ print(f"EPOCH {epoch+1}/{num_epochs}")
26
+ sys.stderr.flush()
27
+ total_loss = 0.0
28
+ train_tokens = 0
29
+ weighted_total_train_loss = 0.0
30
+
31
+ train_update_interval = len(train_loader) // 4
32
+
33
+ with tqdm(enumerate(train_loader), desc="Training batch", total=len(train_loader), leave=True, position=0, ncols=100) as trainbar:
34
+ for step, inputs in trainbar:
35
+ inputs = {k: v.to(device) for k, v in inputs.items()}
36
+ optimizer.zero_grad()
37
+ outputs = model(**inputs)
38
+ train_loss = diffusion_model.compute_loss(inputs["input_ids"], inputs['attention_mask'],
39
+ val=False).loss
40
+ train_loss.backward()
41
+ optimizer.step()
42
+
43
+ total_loss += train_loss.item()
44
+ weighted_total_train_loss += train_loss.item() * inputs['input_ids'].shape[1] # Loss * sequence length
45
+ train_tokens += inputs['input_ids'].shape[1]
46
+
47
+ if (step+1) % train_update_interval == 0:
48
+ trainbar.update(train_update_interval)
49
+
50
+ avg_train_loss = total_loss / len(train_loader)
51
+ avg_train_neg_log_likelihood = weighted_total_train_loss / train_tokens
52
+ train_perplexity = math.exp(avg_train_neg_log_likelihood)
53
+
54
+ # Save model every epoch
55
+ train_ckpt_path = os.path.join(config.Eval.CHECKPOINT_PATH, f'epoch{epoch+1}')
56
+ model.save_model(train_ckpt_path)
57
+ save_hyperparams(train_ckpt_path)
58
+
59
+ # Validate model
60
+ if val_loader:
61
+ model.eval()
62
+ total_val_loss = 0.0
63
+ weighted_total_val_loss = 0.0
64
+ val_tokens = 0
65
+
66
+ with torch.no_grad():
67
+ val_update_interval = len(val_loader) // 4
68
+
69
+ with tqdm(enumerate(val_loader), desc='Validiation batch', total=len(val_loader), leave=True, position=0) as valbar:
70
+ for step, inputs in valbar:
71
+ inputs = {k: v.to(device) for k, v in inputs.items()}
72
+ outputs = model(**inputs)
73
+ val_loss = diffusion_model.compute_loss(inputs['input_ids'], inputs['attention_mask'],
74
+ val=True).loss.item()
75
+
76
+ total_val_loss += val_loss
77
+ weighted_total_val_loss += val_loss * inputs['input_ids'].shape[1] # Loss * sequence length
78
+ val_tokens += inputs['input_ids'].shape[1]
79
+
80
+ if (step+1) % val_update_interval == 0:
81
+ valbar.update(val_update_interval)
82
+
83
+ avg_val_loss = total_val_loss / len(val_loader)
84
+ avg_val_log_likelihood = weighted_total_val_loss / val_tokens
85
+ val_perplexity = math.exp(avg_val_log_likelihood)
86
+
87
+ # Save the best model based on validation loss
88
+ if avg_val_loss < best_val_loss:
89
+ best_val_loss = avg_val_loss
90
+ val_ckpt_path = os.path.join(config.Eval.CHECKPOINT_PATH, "best_model_epoch")
91
+ model.save_model(val_ckpt_path)
92
+ save_hyperparams(val_ckpt_path)
93
+
94
+
95
+ print(f"Average train loss: {avg_train_loss}")
96
+ print(f"Average train perplexity: {train_perplexity}\n")
97
+ sys.stdout.flush()
98
+
99
+ print(f"Average validation loss: {avg_val_loss}")
100
+ print(f"Average validation perplexity: {val_perplexity}\n")
101
+ sys.stdout.flush()
102
+
103
+
104
+ return avg_train_loss, train_perplexity, avg_val_loss, val_perplexity
105
+
106
+
107
+ def test(model, test_loader, device):
108
+ model.to(device).eval()
109
+ total_test_loss = 0.0
110
+ weighted_total_test_loss = 0.0
111
+ test_tokens = 0
112
+
113
+ with torch.no_grad():
114
+ for step, inputs in enumerate(test_loader):
115
+ inputs = {k: v.to(device) for k, v in inputs.items()}
116
+ outputs = model(**inputs)
117
+ test_loss = diffusion_model.compute_loss(inputs['input_ids'], inputs['attention_mask'],
118
+ val=True).loss.item()
119
+
120
+ total_test_loss += test_loss
121
+ weighted_total_test_loss += test_loss * inputs['input_ids'].shape[1] # loss * sequence length
122
+ test_tokens += inputs['input_ids'].shape[1]
123
+
124
+ avg_test_loss = total_test_loss / len(test_loader)
125
+ avg_test_log_likelihood = weighted_total_test_loss / test_tokens
126
+ test_perplexity = math.exp(avg_test_log_likelihood)
127
+
128
+ return avg_test_loss, test_perplexity
129
+
130
+
131
+ if __name__ == "__main__":
132
+ device = torch.device('cuda' if torch.cuda.is_available() else "cpu")
133
+ tokenizer = AutoTokenizer.from_pretrained(config.MODEL_NAME)
134
+
135
+ esm_model = WrapESM()
136
+ diffusion_model = Diffusion(config, tokenizer=tokenizer)
137
+
138
+ print(f'Trainable params before unfreezing: {sum(p.numel() for p in esm_model.parameters() if p.requires_grad)}')
139
+
140
+ esm_model.to(device)
141
+ diffusion_model.to(device)
142
+
143
+ esm_model.freeze_model()
144
+ esm_model.unfreeze_n_layers()
145
+
146
+ print(f'Trainable params after unfreezing: {sum(p.numel() for p in esm_model.parameters() if p.requires_grad)}')
147
+
148
+ train_loader, val_loader, test_loader = get_dataloaders(config)
149
+ optimizer = AdamW(filter(lambda p: p.requires_grad, esm_model.parameters()), lr=config.Optim.LR)
150
+
151
+ # Train and test the model
152
+ avg_train_loss, train_ppl, avg_val_loss, val_ppl = train_and_validate(esm_model, optimizer, device, train_loader, val_loader, config.Training.NUM_EPOCHS, config.Eval.CHECKPOINT_PATH)
153
+ avg_test_loss, test_ppl = test(esm_model, test_loader, device)
154
+
155
+ results_dict = {"Average train loss": avg_train_loss,
156
+ "Average train perplexity": train_ppl,
157
+ "Average val loss": avg_val_loss,
158
+ "Average val perplexity": val_ppl,
159
+ "Average test loss": avg_test_loss,
160
+ "Average test perplexity": test_ppl,
161
+ }
162
+
163
+ print("TRAIN AND TEST RESULTS")
164
+ for k, v in results_dict.items():
165
+ print(f"{k}: {v}\n")