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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import time
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
|
| 5 |
+
import lightning as pl
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import wandb
|
| 9 |
+
|
| 10 |
+
from ..model.esm2 import ESM2
|
| 11 |
+
from .utils.logging import get_logger
|
| 12 |
+
|
| 13 |
+
logger = get_logger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def gather_log(log, world_size):
|
| 17 |
+
if world_size == 1:
|
| 18 |
+
return log
|
| 19 |
+
log_list = [None] * world_size
|
| 20 |
+
torch.distributed.all_gather_object(log_list, log)
|
| 21 |
+
log = {key: sum([l[key] for l in log_list], []) for key in log}
|
| 22 |
+
return log
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_log_mean(log):
|
| 26 |
+
out = {}
|
| 27 |
+
for key in log:
|
| 28 |
+
try:
|
| 29 |
+
out[key] = np.mean(log[key])
|
| 30 |
+
except:
|
| 31 |
+
pass
|
| 32 |
+
if log:
|
| 33 |
+
out["entries"] = len(log[key])
|
| 34 |
+
return out
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class ESMWrapper(pl.LightningModule):
|
| 38 |
+
def __init__(self, cfg, args):
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.save_hyperparameters()
|
| 41 |
+
self.cfg = cfg
|
| 42 |
+
self.args = args
|
| 43 |
+
self.model = ESM2(
|
| 44 |
+
num_layers=cfg.encoder_layers,
|
| 45 |
+
embed_dim=cfg.encoder_embed_dim,
|
| 46 |
+
attention_heads=cfg.encoder_attention_heads,
|
| 47 |
+
token_dropout=cfg.token_dropout,
|
| 48 |
+
use_multimer=not args.no_multimer,
|
| 49 |
+
)
|
| 50 |
+
self.iter_step = -1
|
| 51 |
+
self._log = defaultdict(list)
|
| 52 |
+
self.last_log_time = time.time()
|
| 53 |
+
|
| 54 |
+
def training_step(self, batch, batch_idx):
|
| 55 |
+
self.stage = "train"
|
| 56 |
+
loss = self.forward(batch)
|
| 57 |
+
# Manual checkpointing
|
| 58 |
+
# if self.iter_step % 15000 == 0:
|
| 59 |
+
# if self.trainer.is_global_zero:
|
| 60 |
+
# torch.save(self.model.state_dict(), f'./workdir/3B_nofreeze/checkpoint_iter_{self.iter_step}.pt')
|
| 61 |
+
return loss
|
| 62 |
+
|
| 63 |
+
def validation_step(self, batch, batch_idx):
|
| 64 |
+
self.stage = "val"
|
| 65 |
+
self.forward(batch)
|
| 66 |
+
if self.args.validate:
|
| 67 |
+
self.try_print_log()
|
| 68 |
+
|
| 69 |
+
def forward(self, batch):
|
| 70 |
+
self.iter_step += 1
|
| 71 |
+
# 15% of tokens randomly sampled from the sequence. For those 15% of tokens, we change the input token to a special “masking”
|
| 72 |
+
# token with 80% probability, a randomly-chosen alternate amino acid token with 10% probability, and the original input token
|
| 73 |
+
# (i.e. no change) with 10% probability. We take the loss to be the whole batch average cross entropy loss between the model’s
|
| 74 |
+
# predictions and the true token for these 15% of amino acid tokens.
|
| 75 |
+
|
| 76 |
+
tokens, chain_ids = batch
|
| 77 |
+
mask = (
|
| 78 |
+
(~tokens.eq(self.model.cls_idx))
|
| 79 |
+
& (~tokens.eq(self.model.eos_idx))
|
| 80 |
+
& (~tokens.eq(self.model.padding_idx))
|
| 81 |
+
)
|
| 82 |
+
mask = (torch.rand(tokens.shape, device=tokens.device) < 0.15) & mask
|
| 83 |
+
|
| 84 |
+
rand = torch.rand(tokens.shape, device=tokens.device)
|
| 85 |
+
randaa = torch.randint(4, 24, tokens.shape, device=tokens.device)
|
| 86 |
+
|
| 87 |
+
inp = tokens
|
| 88 |
+
inp = torch.where((rand < 0.8) & mask, self.model.mask_idx, inp)
|
| 89 |
+
inp = torch.where((rand > 0.9) & mask, randaa, inp)
|
| 90 |
+
|
| 91 |
+
out = self.model(inp, chain_ids)["logits"]
|
| 92 |
+
loss = torch.nn.functional.cross_entropy(out.transpose(1, 2), tokens, reduction="none")
|
| 93 |
+
loss = (loss * mask).sum() / mask.sum()
|
| 94 |
+
|
| 95 |
+
self.log("tokens", mask.sum())
|
| 96 |
+
self.log("loss", loss)
|
| 97 |
+
self.log("perplexity", torch.exp(loss))
|
| 98 |
+
self.log("dur", time.time() - self.last_log_time)
|
| 99 |
+
self.last_log_time = time.time()
|
| 100 |
+
return loss
|
| 101 |
+
|
| 102 |
+
def try_print_log(self):
|
| 103 |
+
step = self.iter_step if self.args.validate else self.trainer.global_step
|
| 104 |
+
if (step + 1) % self.args.print_freq == 0:
|
| 105 |
+
log = self._log
|
| 106 |
+
log = {key: log[key] for key in log if "iter_" in key}
|
| 107 |
+
|
| 108 |
+
log = gather_log(log, self.trainer.world_size)
|
| 109 |
+
mean_log = get_log_mean(log)
|
| 110 |
+
mean_log.update(
|
| 111 |
+
{
|
| 112 |
+
"epoch": self.trainer.current_epoch,
|
| 113 |
+
"step": self.trainer.global_step,
|
| 114 |
+
"iter_step": self.iter_step,
|
| 115 |
+
}
|
| 116 |
+
)
|
| 117 |
+
if self.trainer.is_global_zero:
|
| 118 |
+
logger.info(str(mean_log))
|
| 119 |
+
if self.args.wandb:
|
| 120 |
+
wandb.log(mean_log)
|
| 121 |
+
for key in list(log.keys()):
|
| 122 |
+
if "iter_" in key:
|
| 123 |
+
del self._log[key]
|
| 124 |
+
|
| 125 |
+
def log(self, key, data):
|
| 126 |
+
if isinstance(data, torch.Tensor):
|
| 127 |
+
data = data.detach().cpu().item()
|
| 128 |
+
log = self._log
|
| 129 |
+
log["iter_" + key].append(data)
|
| 130 |
+
log[self.stage + "_" + key].append(data)
|
| 131 |
+
|
| 132 |
+
def on_train_epoch_end(self):
|
| 133 |
+
log = self._log
|
| 134 |
+
log = {key: log[key] for key in log if "train_" in key}
|
| 135 |
+
log = gather_log(log, self.trainer.world_size)
|
| 136 |
+
mean_log = get_log_mean(log)
|
| 137 |
+
mean_log.update(
|
| 138 |
+
{
|
| 139 |
+
"epoch": self.trainer.current_epoch,
|
| 140 |
+
"step": self.trainer.global_step,
|
| 141 |
+
"iter_step": self.iter_step,
|
| 142 |
+
}
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
if self.trainer.is_global_zero:
|
| 146 |
+
logger.info(str(mean_log))
|
| 147 |
+
if self.args.wandb:
|
| 148 |
+
wandb.log(mean_log)
|
| 149 |
+
|
| 150 |
+
# path = os.path.join(
|
| 151 |
+
# os.environ["MODEL_DIR"], f"train_{self.trainer.current_epoch}.csv"
|
| 152 |
+
# )
|
| 153 |
+
# pd.DataFrame(log).to_csv(path)
|
| 154 |
+
for key in list(log.keys()):
|
| 155 |
+
if "train_" in key:
|
| 156 |
+
del self._log[key]
|
| 157 |
+
|
| 158 |
+
def on_validation_epoch_end(self):
|
| 159 |
+
log = self._log
|
| 160 |
+
log = {key: log[key] for key in log if "val_" in key}
|
| 161 |
+
log = gather_log(log, self.trainer.world_size)
|
| 162 |
+
if self.trainer.is_global_zero:
|
| 163 |
+
logger.info(str(get_log_mean(log)))
|
| 164 |
+
if self.args.wandb:
|
| 165 |
+
wandb.log(get_log_mean(log))
|
| 166 |
+
|
| 167 |
+
for key in list(log.keys()):
|
| 168 |
+
if "val_" in key:
|
| 169 |
+
del self._log[key]
|
| 170 |
+
|
| 171 |
+
def on_before_optimizer_step(self, optimizer, x):
|
| 172 |
+
self.try_print_log()
|
| 173 |
+
if self.args.check_grad:
|
| 174 |
+
for name, p in self.model.named_parameters():
|
| 175 |
+
if p.requires_grad and p.grad is None:
|
| 176 |
+
print(name)
|
| 177 |
+
|
| 178 |
+
def configure_optimizers(self):
|
| 179 |
+
# For model training optimization, we used Adam with 𝛽𝛽1 = 0.9, 𝛽𝛽2 = 0.98, 𝜖𝜖 = 10−8 and 𝐿𝐿2 weight decay of
|
| 180 |
+
# 0.01 for all models except the 15 billion parameter model, where we used a weight decay of 0.1. The learning rate is
|
| 181 |
+
# warmed up over the first 2,000 steps to a peak value of 4e-4 (1.6e-4 for the 15B parameter model), and then linearly
|
| 182 |
+
# decayed to one tenth of its peak value over the 90% of training duration
|
| 183 |
+
if self.args.freeze_self_attn:
|
| 184 |
+
self.model.requires_grad_(False)
|
| 185 |
+
for name, p in self.model.named_parameters():
|
| 186 |
+
if "multimer_attn" in name:
|
| 187 |
+
p.requires_grad = True
|
| 188 |
+
|
| 189 |
+
optimizer = torch.optim.AdamW(
|
| 190 |
+
filter(lambda p: p.requires_grad, self.model.parameters()),
|
| 191 |
+
lr=self.cfg.lr[0],
|
| 192 |
+
betas=json.loads(self.cfg.adam_betas),
|
| 193 |
+
eps=self.cfg.adam_eps,
|
| 194 |
+
weight_decay=self.cfg.weight_decay,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
warmup = torch.optim.lr_scheduler.LinearLR(
|
| 198 |
+
optimizer, start_factor=1e-12, end_factor=1.0, total_iters=self.cfg.warmup_updates
|
| 199 |
+
)
|
| 200 |
+
decay = torch.optim.lr_scheduler.LinearLR(
|
| 201 |
+
optimizer,
|
| 202 |
+
start_factor=1.0,
|
| 203 |
+
end_factor=self.cfg.end_learning_rate / self.cfg.lr[0],
|
| 204 |
+
total_iters=int(0.9 * int(self.cfg.total_num_update)),
|
| 205 |
+
)
|
| 206 |
+
scheduler = torch.optim.lr_scheduler.SequentialLR(
|
| 207 |
+
optimizer, schedulers=[warmup, decay], milestones=[self.cfg.warmup_updates]
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
return {
|
| 211 |
+
"optimizer": optimizer,
|
| 212 |
+
"lr_scheduler": {"scheduler": scheduler, "interval": "step"},
|
| 213 |
+
}
|