enzymeretrieval / dev /rxnbert.py
da24b002athreyaganesh's picture
v5: v4 + fine-tuned rxnfp reaction BERT
177457f verified
Raw History Blame Contribute Delete
7.26 kB
"""The rxnfp reaction BERT (Schwaller et al. 2021) in plain torch, without transformers.
rxnfp was pretrained on about a million USPTO patent reactions and carries no
EC labels. Its weights ship inside the rxnfp source package; unpack them with
tar xzf rxnfp-0.1.0.tar.gz -C x rxnfp-0.1.0/rxnfp/models/transformers
and point --bert at x/rxnfp-0.1.0/rxnfp/models/transformers/bert_ft (or
bert_pretrained, which also holds the masked-token head used by --check).
Run: python dev/rxnbert.py --bert DIR --check
"""
import argparse
import sys
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
sys.path.insert(1, str(Path(__file__).resolve().parents[1]))
# The container's tokeniser, so training and inference cannot drift apart.
from reaction_bert import Tokenizer # noqa: E402
def tokenizer_from(directory):
return Tokenizer((Path(directory) / 'vocab.txt').read_text().split('\n'))
def load_weights(directory):
"""Encoder weights with any 'bert.' prefix removed; the MLM head keeps its 'cls.' names."""
state = torch.load(Path(directory) / 'pytorch_model.bin', map_location='cpu', weights_only=True)
return {key.removeprefix('bert.'): value.float() for key, value in state.items()}
class Bert(torch.nn.Module):
"""BERT encoder: 12 layers, 256 wide, 4 heads, GELU, post-LayerNorm."""
def __init__(self, weights, layers=12, heads=4):
super().__init__()
self.heads = heads
self.params = torch.nn.ParameterDict({
key.replace('.', '__'): torch.nn.Parameter(value.clone())
for key, value in weights.items() if not key.startswith('cls.')})
self.layers = layers
def p(self, name):
return self.params[name.replace('.', '__')]
def linear(self, x, name):
return F.linear(x, self.p(name + '.weight'), self.p(name + '.bias'))
def norm(self, x, name):
return F.layer_norm(x, x.shape[-1:], self.p(name + '.weight'), self.p(name + '.bias'), eps=1e-12)
def forward(self, ids, mask, dropout=0.0):
"""Hidden states (batch, length, 256); mask is True on real tokens."""
batch, length = ids.shape
positions = torch.arange(length, device=ids.device)
x = (F.embedding(ids, self.p('embeddings.word_embeddings.weight'))
+ self.p('embeddings.position_embeddings.weight')[positions]
+ self.p('embeddings.token_type_embeddings.weight')[0])
x = F.dropout(self.norm(x, 'embeddings.LayerNorm'), dropout, self.training)
attend = mask[:, None, None, :]
for i in range(self.layers):
layer = f'encoder.layer.{i}'
q, k, v = (self.linear(x, f'{layer}.attention.self.{name}')
.view(batch, length, self.heads, -1).transpose(1, 2) for name in ('query', 'key', 'value'))
context = F.scaled_dot_product_attention(q, k, v, attn_mask=attend,
dropout_p=dropout if self.training else 0.0)
context = context.transpose(1, 2).reshape(batch, length, -1)
attended = F.dropout(self.linear(context, f'{layer}.attention.output.dense'), dropout, self.training)
x = self.norm(x + attended, f'{layer}.attention.output.LayerNorm')
hidden = F.gelu(self.linear(x, f'{layer}.intermediate.dense'))
out = F.dropout(self.linear(hidden, f'{layer}.output.dense'), dropout, self.training)
x = self.norm(x + out, f'{layer}.output.LayerNorm')
return x
def batches(encoded, size, pad):
"""Index arrays and padded (ids, mask) batches, shortest reactions first to limit padding."""
order = np.argsort([len(e) for e in encoded], kind='stable')
for start in range(0, len(order), size):
rows = order[start:start + size]
length = max(len(encoded[r]) for r in rows)
ids = np.full((len(rows), length), pad, dtype=np.int64)
for j, r in enumerate(rows):
ids[j, :len(encoded[r])] = encoded[r]
ids = torch.from_numpy(ids)
yield rows, ids, ids != pad
def embed(model, encoded, pad, device, size=64):
"""Per reaction, the [CLS] state and the mean over real tokens of the last layer, side by side."""
out = np.zeros((len(encoded), 512), dtype=np.float32)
model.eval()
with torch.no_grad(), torch.autocast(device.type, dtype=torch.float16, enabled=device.type == 'cuda'):
for rows, ids, real in batches(encoded, size, pad):
real = real.to(device)
hidden = model(ids.to(device), real).float()
mean = (hidden * real[..., None]).sum(1) / real.sum(1, keepdim=True)
out[rows] = torch.cat([hidden[:, 0], mean], dim=1).cpu().numpy()
return out
def check(directory, reactions, device):
"""Masked-token accuracy of the pretrained MLM head on held-out reactions; a broken encoder scores near 0."""
weights = load_weights(directory)
if 'cls.predictions.decoder.weight' not in weights:
raise SystemExit(f'{directory} has no masked-token head; use bert_pretrained for --check')
tokenizer = tokenizer_from(directory)
model = Bert(weights).to(device).eval()
head = {k: v.to(device) for k, v in weights.items() if k.startswith('cls.')}
rng = np.random.default_rng(0)
right = total = 0
mask_id = tokenizer.index['[MASK]']
with torch.no_grad():
for rows, ids, real in batches([tokenizer.encode(r) for r in reactions], 32, tokenizer.pad):
target = ids.clone()
chosen = (torch.from_numpy(rng.random(ids.shape) < 0.15) & real
& (ids != tokenizer.cls) & (ids != tokenizer.sep))
ids[chosen] = mask_id
hidden = model(ids.to(device), real.to(device))[chosen.to(device)]
h = F.linear(hidden, head['cls.predictions.transform.dense.weight'],
head['cls.predictions.transform.dense.bias'])
h = F.layer_norm(F.gelu(h), h.shape[-1:], head['cls.predictions.transform.LayerNorm.weight'],
head['cls.predictions.transform.LayerNorm.bias'], eps=1e-12)
logits = F.linear(h, head['cls.predictions.decoder.weight'], head['cls.predictions.bias'])
right += (logits.argmax(-1).cpu() == target[chosen]).sum().item()
total += chosen.sum().item()
print(f'masked-token accuracy {right / total:.1%} over {total} masked tokens')
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--bert', required=True, help='directory with config.json, vocab.txt, pytorch_model.bin')
parser.add_argument('--check', action='store_true', help='masked-token accuracy on 500 training reactions')
parser.add_argument('--train', default=str(Path(__file__).resolve().parents[2] / 'data' / 'train.parquet'))
args = parser.parse_args()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if args.check:
import pandas as pd
reactions = pd.read_parquet(args.train).rxn_smiles.drop_duplicates().sample(500, random_state=1).tolist()
check(args.bert, reactions, device)
if __name__ == '__main__':
main()