Download dev/train_bert.py from da24b002athreyaganesh/enzymeretrieval: direct link, hf CLI and curl.
- Browser
- Download file 9.5 kB
-
https://huggingface.co/da24b002athreyaganesh/enzymeretrieval/resolve/main/dev/train_bert.py
- Command line
-
hf download hf://da24b002athreyaganesh/enzymeretrieval/dev/train_bert.py
-
curl -L -o train_bert.py https://huggingface.co/da24b002athreyaganesh/enzymeretrieval/resolve/main/dev/train_bert.py
9.5 kB
| """Fine-tune the rxnfp reaction BERT to predict EC numbers; export numpy weights. | |
| A second model for the ensemble, not a replacement: it reads the SMILES | |
| tokens, so it sees details the hashed fingerprints blur, such as NAD versus | |
| NADP. Its probabilities are mixed with the fingerprint MLPs before the kNN | |
| blend. | |
| Run: python dev/train_bert.py --train dev/splits/matched_train.parquet \ | |
| --val dev/splits/matched_val.parquet --out dev/runs/b_matched | |
| python dev/train_bert.py --train ../data/train.parquet --val none --out weights | |
| Writes <out>/bert.npz, and with a validation split also <out>/bert_val.npy, | |
| the BERT probabilities for each unique validation input in build_truth order. | |
| Training always keeps the last epoch: the learning rate decays to zero over | |
| --epochs, and a full-data run has nothing to choose a best epoch with. | |
| """ | |
| import argparse | |
| import hashlib | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(1, str(ROOT)) | |
| from metric import build_truth, l4_credit # noqa: E402 | |
| from reaction_bert import reverse # noqa: E402 | |
| from rxnbert import Bert, batches, load_weights, tokenizer_from # noqa: E402 | |
| from train import build_vocab, soft_cross_entropy, soft_targets # noqa: E402 | |
| DEFAULT_BERT = ROOT.parent / 'rxnfp_dl' / 'x' / 'rxnfp-0.1.0' / 'rxnfp' / 'models' / 'transformers' / 'bert_ft' | |
| def tokenised(reactions, tokenizer, cache_dir): | |
| """Token ids of each reaction and of its reverse; canonicalising takes minutes, so cache them.""" | |
| digest = hashlib.sha1('\n'.join(reactions).encode()).hexdigest()[:12] | |
| cache = Path(cache_dir) / f'bert_tokens_{digest}.npz' | |
| if cache.exists(): | |
| stored = np.load(cache) | |
| print(f'loaded cached tokens from {cache}') | |
| return [np.split(stored[f'{d}_ids'], stored[f'{d}_cuts']) for d in ('forward', 'reverse')] | |
| print(f'tokenising {len(reactions)} reactions, both directions...', flush=True) | |
| directions = [[tokenizer.encode(r) for r in reactions], [tokenizer.encode(reverse(r)) for r in reactions]] | |
| cache.parent.mkdir(parents=True, exist_ok=True) | |
| np.savez(cache, **{f'{d}_{part}': value for d, encoded in zip(('forward', 'reverse'), directions) | |
| for part, value in (('ids', np.concatenate(encoded)), | |
| ('cuts', np.cumsum([len(e) for e in encoded])[:-1]))}) | |
| return directions | |
| class Classifier: | |
| """BERT, then an MLP on the [CLS] state and the token mean side by side.""" | |
| def __init__(self, weights, n_vocab, hidden, dropout, device): | |
| self.bert = Bert(weights).to(device) | |
| self.head = torch.nn.Sequential( | |
| torch.nn.Dropout(dropout), torch.nn.Linear(512, hidden), torch.nn.GELU(), | |
| torch.nn.Dropout(dropout), torch.nn.Linear(hidden, n_vocab)).to(device) | |
| self.dropout = dropout | |
| def logits(self, ids, real): | |
| hidden = self.bert(ids, real, dropout=self.dropout) | |
| mean = (hidden * real[..., None]).sum(1) / real.sum(1, keepdim=True) | |
| return self.head(torch.cat([hidden[:, 0], mean], dim=1)) | |
| def train(self, mode=True): | |
| self.bert.train(mode) | |
| self.head.train(mode) | |
| def export(self): | |
| out = {key.replace('__', '.'): value.detach().float().cpu().numpy() | |
| for key, value in self.bert.params.items()} | |
| out.update({f'head.{key}': value.detach().float().cpu().numpy() | |
| for key, value in self.head.state_dict().items()}) | |
| return out | |
| def probabilities(model, views, pad, device, batch=64): | |
| """Softmax averaged over the directions given.""" | |
| model.train(False) | |
| total = None | |
| with torch.no_grad(), torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == 'cuda'): | |
| for encoded in views: | |
| probs = np.zeros((len(encoded), model.head[-1].out_features), dtype=np.float32) | |
| for rows, ids, real in batches(encoded, batch, pad): | |
| logits = model.logits(ids.to(device), real.to(device)).float() | |
| probs[rows] = torch.softmax(logits, dim=1).cpu().numpy() | |
| total = probs if total is None else total + probs | |
| return total / len(views) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument('--train', default=str(ROOT / 'dev' / 'splits' / 'matched_train.parquet')) | |
| parser.add_argument('--val', default=str(ROOT / 'dev' / 'splits' / 'matched_val.parquet')) | |
| parser.add_argument('--vocabulary', default=str(ROOT / 'ec_vocabulary.json')) | |
| parser.add_argument('--bert', default=str(DEFAULT_BERT), help='rxnfp model directory to start from') | |
| parser.add_argument('--out', required=True) | |
| parser.add_argument('--cache', default=str(ROOT / 'dev' / 'cache')) | |
| parser.add_argument('--epochs', type=int, default=8) | |
| parser.add_argument('--batch', type=int, default=32) | |
| parser.add_argument('--lr', type=float, default=1e-4, help='peak learning rate of the BERT layers') | |
| parser.add_argument('--head-lr', type=float, default=1e-3) | |
| parser.add_argument('--warmup', type=float, default=0.05, help='share of steps the learning rate rises over') | |
| parser.add_argument('--hidden', type=int, default=1024) | |
| parser.add_argument('--dropout', type=float, default=0.1) | |
| parser.add_argument('--weight-decay', type=float, default=1e-2) | |
| parser.add_argument('--seed', type=int, default=0) | |
| args = parser.parse_args() | |
| torch.manual_seed(args.seed) | |
| rng = np.random.default_rng(args.seed) | |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
| train = pd.read_parquet(args.train) | |
| vocab = build_vocab(train, args.vocabulary) | |
| vocab_index = {ec: i for i, ec in enumerate(vocab)} | |
| reactions, targets = soft_targets(train, vocab_index) | |
| tokenizer = tokenizer_from(args.bert) | |
| forward, backward = tokenised(reactions, tokenizer, args.cache) | |
| # Every reaction is also seen written backwards, as the fingerprint MLPs are. | |
| encoded = forward + backward | |
| n = len(reactions) | |
| monitor = None | |
| if Path(args.val).exists(): | |
| truth, _ = build_truth(pd.read_parquet(args.val)) | |
| keys = list(truth) | |
| monitor = (tokenised(keys, tokenizer, args.cache), l4_credit(truth, keys, vocab_index)) | |
| model = Classifier(load_weights(args.bert), len(vocab), args.hidden, args.dropout, device) | |
| optimiser = torch.optim.AdamW([ | |
| {'params': model.bert.parameters(), 'lr': args.lr}, | |
| {'params': model.head.parameters(), 'lr': args.head_lr}, | |
| ], weight_decay=args.weight_decay) | |
| lengths = np.array([len(e) for e in encoded]) | |
| steps = args.epochs * -(-len(encoded) // args.batch) | |
| warmup = max(1, int(args.warmup * steps)) | |
| schedule = torch.optim.lr_scheduler.LambdaLR( | |
| optimiser, lambda step: min((step + 1) / warmup, max(0.0, (steps - step) / (steps - warmup)))) | |
| print(f'{n} unique training reactions, {len(vocab)} EC classes, {steps} steps on {device}', flush=True) | |
| for epoch in range(args.epochs): | |
| model.train() | |
| start, running = time.time(), 0.0 | |
| # Batches of similar length waste little on padding; jitter keeps them from repeating. | |
| order = np.argsort(lengths + rng.uniform(0, 8, len(lengths)), kind='stable') | |
| chunks = [order[i:i + args.batch] for i in range(0, len(order), args.batch)] | |
| for b in rng.permutation(len(chunks)): | |
| rows = chunks[b] | |
| length = lengths[rows].max() | |
| ids = np.full((len(rows), length), tokenizer.pad, dtype=np.int64) | |
| for j, r in enumerate(rows): | |
| ids[j, :lengths[r]] = encoded[r] | |
| ids = torch.from_numpy(ids).to(device) | |
| y = torch.from_numpy(targets[rows % n].toarray()).to(device) | |
| with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == 'cuda'): | |
| logits = model.logits(ids, ids != tokenizer.pad) | |
| loss = soft_cross_entropy(logits.float(), y) | |
| optimiser.zero_grad() | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(list(model.bert.parameters()) + list(model.head.parameters()), 1.0) | |
| optimiser.step() | |
| schedule.step() | |
| running += loss.item() * len(rows) | |
| line = f'epoch {epoch + 1:2d}/{args.epochs} loss {running / len(encoded):.4f} {time.time() - start:.0f}s' | |
| if monitor is not None: | |
| probs = probabilities(model, monitor[0], tokenizer.pad, device) | |
| l4 = np.mean([row.get(p, 0.0) for row, p in zip(monitor[1], probs.argmax(axis=1))]) | |
| line += f' val L4 {l4:.2%} (BERT alone, both directions)' | |
| print(line, flush=True) | |
| out = Path(args.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| # Token and EC vocabularies as newline-joined bytes, so loading needs no pickle. | |
| tokens = np.frombuffer('\n'.join(tokenizer.tokens).encode(), dtype=np.uint8) | |
| ecs = np.frombuffer('\n'.join(vocab).encode(), dtype=np.uint8) | |
| np.savez(out / 'bert.npz', vocab=tokens, ec_vocab=ecs, **model.export()) | |
| print(f'wrote {out}/bert.npz ({(out / "bert.npz").stat().st_size / 1e6:.1f} MB)') | |
| if monitor is not None: | |
| np.save(out / 'bert_val.npy', probs.astype(np.float16)) | |
| print(f'wrote {out}/bert_val.npy, BERT probabilities for the {len(probs)} validation inputs') | |
| if __name__ == '__main__': | |
| main() | |