enzyme-retrieval-bert / predict.py
sanrathi's picture
Reaction BERT classifier (8 epochs, full train data)
4c1f0fd verified
Raw History Blame Contribute Delete
2.78 kB
"""Offline CPU inference: fine-tuned reaction BERT -> EC. Top-5 distinct ECs per unique input."""
import argparse
import json
import re
from pathlib import Path
import pandas as pd
import torch
import torch.nn as nn
from transformers import BertConfig, BertModel
from inputs import prepare_inputs
SMI_RE = re.compile(r"(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\|/|:|~|@|\?|>>?|\*|\$|%[0-9]{2}|[0-9])")
MAX_LEN = 256
TOP = 5
class Net(nn.Module):
def __init__(self, config, n_cls, n_l3):
super().__init__()
self.bert = BertModel(config, add_pooling_layer=False)
self.head = nn.Linear(config.hidden_size, n_cls)
self.head_l3 = nn.Linear(config.hidden_size, n_l3)
def forward(self, ids, mask):
x = self.bert(input_ids=ids, attention_mask=mask).last_hidden_state
m = mask.unsqueeze(-1).to(x.dtype)
return self.head((x * m).sum(1) / m.sum(1))
def predict_file(input_path, output_path):
torch.set_num_threads(2)
root = Path(__file__).parent
w = root / 'weights'
frame = prepare_inputs(pd.read_parquet(input_path))
classes = json.loads((w / 'classes.json').read_text())
valid = set(json.loads((root / 'ec_vocabulary.json').read_text()))
tokens = (w / 'vocab.txt').read_text().splitlines()
idx = {t: i for i, t in enumerate(tokens)}
state = torch.load(w / 'best.pt', map_location='cpu', weights_only=True)
net = Net(BertConfig.from_pretrained(w), len(classes), state['head_l3.weight'].shape[0])
net.load_state_dict(state)
net.eval()
enc = [[idx['[CLS]']] + [idx.get(t, 1) for t in SMI_RE.findall(r)][:MAX_LEN - 2] + [idx['[SEP]']] for r in frame.rxn_smiles]
order = sorted(range(len(enc)), key=lambda i: len(enc[i]))
preds = [None] * len(enc)
with torch.inference_mode():
for a in range(0, len(order), 64):
b = order[a:a + 64]
n = max(len(enc[i]) for i in b)
ids = torch.zeros(len(b), n, dtype=torch.long)
mask = torch.zeros(len(b), n, dtype=torch.long)
for j, i in enumerate(b):
ids[j, :len(enc[i])] = torch.tensor(enc[i]); mask[j, :len(enc[i])] = 1
top = net(ids, mask).topk(TOP, dim=-1).indices.tolist()
for j, i in enumerate(b):
preds[i] = [classes[t] for t in top[j] if classes[t] in valid]
with Path(output_path).open('w') as out:
for key, p in zip(frame.id, preds):
out.write(json.dumps({'id': key, 'prediction': p or [classes[0]]}) + '\n')
if __name__ == '__main__':
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--input', required=True)
ap.add_argument('--output', required=True)
a = ap.parse_args()
predict_file(a.input, a.output)