enzymeretrieval / dev /train.py
da24b002athreyaganesh's picture
v5: v4 + fine-tuned rxnfp reaction BERT
177457f verified
Raw History Blame Contribute Delete
16.4 kB
"""Train the reaction -> EC model and export numpy weights for the container.
Trains in PyTorch on whatever device you have, then writes model.npz and
meta.json, which inference reads with numpy alone. The container therefore
never installs torch.
Run: python dev/split.py --mode random
python dev/train.py --out dev/runs/random --ensemble 5
python dev/tune.py --weights dev/runs/random
python dev/train.py --train ../data/train.parquet --val none \
--cache dev/cache/full_features.npy \
--ensemble 5 --epochs N <flags printed by tune.py>
With a validation split, each network keeps the weights of its best epoch. A
full-data run has nothing to validate on, so give it the epoch count that the
split run kept. Fingerprint flags (--bits, --radius, --chirality,
--difference) must match between the split run and the full-data run; each
combination is fingerprinted once and cached in its own file.
"""
import argparse
import json
import sys
from pathlib import Path
import numpy as np
import pandas as pd
from scipy import sparse
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from features import Featurizer, blocks, molecule_block, reverse_features # noqa: E402
from metric import build_truth, l4_credit, report, score # noqa: E402
def cached_features(reactions, cache, featurizer):
"""Fingerprinting the whole training set takes minutes, so keep the result."""
cache = Path(cache)
if featurizer.tag():
cache = cache.with_name(f'{cache.stem}.{featurizer.tag()}{cache.suffix}')
if cache.exists():
stored = np.load(cache)
if len(stored) == len(reactions):
print(f'loaded cached features from {cache}')
return stored
print('cache size does not match this split, rebuilding')
print(f'featurising {len(reactions)} reactions...', flush=True)
features = featurizer.featurize_many(reactions, verbose=True)
cache.parent.mkdir(parents=True, exist_ok=True)
np.save(cache, features)
return features
def soft_targets(frame, vocab_index):
"""One row per unique reaction, mass 1/n spread over its recorded ECs.
This mirrors the scorer, which awards 1/n credit per matching EC.
"""
grouped = {}
for rxn, ec in zip(frame.rxn_smiles, frame.ec_number):
ec = str(ec).strip()
if ec in vocab_index:
grouped.setdefault(rxn, set()).add(vocab_index[ec])
reactions = [rxn for rxn, ecs in grouped.items() if ecs]
rows, cols, values = [], [], []
for i, rxn in enumerate(reactions):
ecs = sorted(grouped[rxn])
for ec in ecs:
rows.append(i)
cols.append(ec)
values.append(1.0 / len(ecs))
targets = sparse.csr_matrix(
(np.array(values, dtype=np.float32), (np.array(rows), np.array(cols))),
shape=(len(reactions), len(vocab_index)),
)
return reactions, targets
def build_vocab(frame, vocabulary_file):
observed = sorted({str(e).strip() for e in frame.ec_number})
path = Path(vocabulary_file)
if path.exists():
raw = json.loads(path.read_text())
allowed = set(raw if isinstance(raw, list) else raw.keys())
kept = [ec for ec in observed if ec in allowed]
print(f'vocabulary: {len(kept)} of {len(observed)} training ECs are in {path.name}')
if kept:
return kept
print(f'vocabulary: {len(observed)} ECs taken from the training labels')
return observed
def level_maps(vocab):
"""For EC levels 1-3, a 0/1 matrix from each vocabulary EC to its prefix group."""
maps = []
for level in (1, 2, 3):
prefixes = ['.'.join(ec.split('.')[:level]) for ec in vocab]
groups = {prefix: i for i, prefix in enumerate(sorted(set(prefixes)))}
matrix = np.zeros((len(vocab), len(groups)), dtype=np.float32)
matrix[np.arange(len(vocab)), [groups[prefix] for prefix in prefixes]] = 1.0
maps.append(matrix)
return maps
def soft_cross_entropy(logits, target):
return -(logits.log_softmax(dim=1) * target).sum(dim=1).mean()
def validation_l4(model, monitor, device):
"""MLP-only L4 accuracy on the held-out split, scored the way the leaderboard does."""
import torch
views, credit = monitor
model.eval()
picks = []
with torch.no_grad():
for start in range(0, len(credit), 1024):
probs = 0
for view in views:
x = torch.from_numpy(view[start:start + 1024].astype(np.float32)).to(device)
probs = probs + torch.softmax(model['head'](model['trunk'](x)), dim=1)
picks.extend(probs.argmax(dim=1).tolist())
return sum(row.get(pick, 0.0) for row, pick in zip(credit, picks)) / len(credit)
def train_network(features, targets, args, seed, epochs, monitor=None, levels=()):
"""Features stay uint8 and targets stay sparse; each batch is widened alone.
With --reverse-augment every reaction is also seen written backwards. Only
the MLP learns from that: the difference block is the same in both directions.
With --hierarchy-weight, extra heads on the hidden layer also predict EC
levels 1-3. They only shape the hidden layer and are not exported.
"""
import torch
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
device = torch.device(args.device if torch.cuda.is_available() or args.device == 'cpu' else 'cpu')
print(f'training on {device}, seed {seed}')
n, n_vocab = targets.shape
maps = [torch.from_numpy(matrix).to(device) for matrix in levels] if args.hierarchy_weight else []
widths = [features.shape[1]] + [args.hidden] * args.layers
trunk = [torch.nn.Dropout(args.input_dropout)]
for fan_in, fan_out in zip(widths, widths[1:]):
trunk += [torch.nn.Linear(fan_in, fan_out), torch.nn.ReLU(), torch.nn.Dropout(args.dropout)]
model = torch.nn.ModuleDict({
'trunk': torch.nn.Sequential(*trunk),
'head': torch.nn.Linear(args.hidden, n_vocab),
'aux': torch.nn.ModuleList([torch.nn.Linear(args.hidden, mapping.shape[1]) for mapping in maps]),
}).to(device)
optimiser = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
rows = 2 * n if args.reverse_augment else n
schedule = None
if args.cosine:
# The learning rate falls to zero over all epochs, batch by batch.
schedule = torch.optim.lr_scheduler.CosineAnnealingLR(optimiser, epochs * -(-rows // args.batch))
best, best_epoch, best_state, stale = -1.0, 0, None, 0
for epoch in range(epochs):
model.train()
order = rng.permutation(rows)
running = 0.0
for start in range(0, rows, args.batch):
idx = order[start:start + args.batch]
batch = features[idx % n]
flipped = idx >= n
if flipped.any():
batch[flipped] = reverse_features(batch[flipped])
x = torch.from_numpy(batch.astype(np.float32)).to(device)
y = torch.from_numpy(targets[idx % n].toarray()).to(device)
hidden = model['trunk'](x)
loss = soft_cross_entropy(model['head'](hidden), y)
for layer, mapping in zip(model['aux'], maps):
loss = loss + args.hierarchy_weight * soft_cross_entropy(layer(hidden), y @ mapping)
optimiser.zero_grad()
loss.backward()
optimiser.step()
if schedule is not None:
schedule.step()
running += loss.item() * len(idx)
line = f'epoch {epoch + 1:3d}/{epochs} loss {running / rows:.4f}'
if monitor is not None:
l4 = validation_l4(model, monitor, device)
line += f' val L4 {l4:.2%}'
if l4 > best:
best, best_epoch, stale = l4, epoch + 1, 0
best_state = {key: value.detach().clone() for key, value in model.state_dict().items()}
else:
stale += 1
print(line, flush=True)
if monitor is not None and args.patience and stale >= args.patience:
print(f'no val improvement for {args.patience} epochs, stopping')
break
if best_state is not None:
model.load_state_dict(best_state)
print(f'kept epoch {best_epoch} (val L4 {best:.2%}, MLP alone)')
model.eval()
linears = [layer for layer in model['trunk'] if isinstance(layer, torch.nn.Linear)] + [model['head']]
return [(layer.weight.T.detach().cpu().numpy(), layer.bias.detach().cpu().numpy()) for layer in linears]
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--train', default=str(ROOT / 'dev' / 'splits' / 'random_train.parquet'))
parser.add_argument('--val', default=str(ROOT / 'dev' / 'splits' / 'random_val.parquet'))
parser.add_argument('--vocabulary', default=str(ROOT / 'ec_vocabulary.json'))
parser.add_argument('--out', default=str(ROOT / 'weights'))
parser.add_argument('--cache', default=str(ROOT / 'dev' / 'cache' / 'train_features.npy'))
parser.add_argument('--bits', type=int, default=2048, help='bits per fingerprint block')
parser.add_argument('--radius', type=int, default=3)
parser.add_argument('--chirality', action='store_true', help='include R/S stereo in the Morgan bits')
parser.add_argument('--difference', choices=['xor', 'drfp'], default='xor')
parser.add_argument('--hidden', type=int, default=1024)
parser.add_argument('--layers', type=int, default=1, help='hidden layers, each --hidden wide')
parser.add_argument('--dropout', type=float, default=0.1)
parser.add_argument('--input-dropout', type=float, default=0.0, help='dropout on the fingerprint bits')
parser.add_argument('--weight-decay', type=float, default=1e-2)
parser.add_argument('--hierarchy-weight', type=float, default=0.0,
help='loss weight of the extra EC level 1-3 heads; 0 trains none')
parser.add_argument('--epochs', type=int, default=20)
parser.add_argument('--patience', type=int, default=5,
help='stop after this many epochs without a val gain; 0 never stops early')
parser.add_argument('--batch', type=int, default=256)
parser.add_argument('--lr', type=float, default=1e-3)
parser.add_argument('--cosine', action='store_true', help='decay the learning rate to zero over --epochs')
parser.add_argument('--ensemble', type=int, default=1, help='networks trained from consecutive seeds')
parser.add_argument('--member-epochs', type=int, nargs='+',
help='one network per count, trained for that many epochs; replaces --epochs and --ensemble')
parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--reverse-augment', action='store_true', help='also train on every reaction backwards')
parser.add_argument('--reverse-tta', action='store_true', help='average the MLP over both directions')
parser.add_argument('--k', type=int, default=25)
parser.add_argument('--knn-labels', choices=['first', 'all'], default='first',
help='a neighbour votes for its first EC, or for all of them at 1/n each')
parser.add_argument('--knn-molecules', type=float, default=0.0,
help='weight of the all-molecule Tanimoto when ranking neighbours')
parser.add_argument('--knn-power', type=float, default=1.0, help='a neighbour votes with similarity ** power')
parser.add_argument('--alpha', type=float, default=0.5, help='MLP weight in the blend')
parser.add_argument('--alpha-far', type=float, help='MLP weight for queries below --gate; defaults to --alpha')
parser.add_argument('--gate', type=float, default=0.0,
help='nearest-neighbour similarity from which --alpha applies instead of --alpha-far')
parser.add_argument('--beta', type=float, default=0.0, help='scale each EC by its EC3 subclass total ** beta')
parser.add_argument('--device', default='cuda')
args = parser.parse_args()
featurizer = Featurizer(args.bits, args.radius, args.chirality, args.difference)
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)
print(f'{len(reactions)} unique training reactions, {len(vocab)} EC classes')
features = cached_features(reactions, args.cache, featurizer)
monitor, truth = None, None
if Path(args.val).exists():
truth, _ = build_truth(pd.read_parquet(args.val))
leaked = len(set(truth) & set(reactions))
if leaked:
print(f'warning: {leaked} validation reactions are also in the training data, so validation '
'is skipped; pass --val none for a full-data run')
truth = None
else:
keys = list(truth)
print(f'featurising {len(keys)} validation reactions...', flush=True)
val_features = featurizer.featurize_many(keys)
views = [val_features, reverse_features(val_features)] if args.reverse_tta else [val_features]
monitor = (views, l4_credit(truth, keys, vocab_index))
levels = level_maps(vocab) if args.hierarchy_weight else ()
# Networks stopped at different epochs disagree more, and so average better;
# on a split, early stopping spreads them, and --member-epochs does it without one.
schedule = args.member_epochs or [args.epochs] * args.ensemble
members = []
for member, epochs in enumerate(schedule):
print(f'network {member + 1}/{len(schedule)}')
members.append(train_network(features, targets, args, args.seed + member, epochs, monitor, levels))
# Per layer, weights and biases stacked over the ensemble.
(w1, b1), *hidden, (w2, b2) = [[np.stack(part).astype(np.float32) for part in zip(*layer)]
for layer in zip(*members)]
deeper = {'wh': np.stack([w for w, _ in hidden], axis=1),
'bh': np.stack([b for _, b in hidden], axis=1)} if hidden else {}
# Neighbours are found on the difference block, then optionally re-ranked
# on every molecule; both indexes ship so tune.py can try either.
_, _, change = blocks(features)
change = sparse.csr_matrix(change)
molecules = sparse.csr_matrix(molecule_block(features))
neighbour_label = np.asarray(targets.argmax(axis=1)).ravel().astype(np.int32)
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
np.savez_compressed(
out / 'model.npz',
w1=w1, b1=b1, w2=w2, b2=b2,
n_train=np.int64(len(reactions)),
indices=change.indices.astype(np.int32), indptr=change.indptr.astype(np.int32),
popcount=np.diff(change.indptr).astype(np.float32),
molecule_indices=molecules.indices.astype(np.int32), molecule_indptr=molecules.indptr.astype(np.int32),
molecule_popcount=np.diff(molecules.indptr).astype(np.float32),
train_labels=neighbour_label,
label_indices=targets.indices.astype(np.int32), label_indptr=targets.indptr.astype(np.int32),
label_values=targets.data.astype(np.float32),
**deeper,
)
alpha_far = args.alpha if args.alpha_far is None else args.alpha_far
(out / 'meta.json').write_text(json.dumps(
{'vocab': vocab, 'features': featurizer.config(), 'ensemble': len(schedule),
'k': args.k, 'knn_labels': args.knn_labels, 'knn_molecules': args.knn_molecules,
'knn_power': args.knn_power, 'alpha': args.alpha, 'alpha_far': alpha_far, 'gate': args.gate,
'beta': args.beta, 'reverse_tta': args.reverse_tta}, indent=1))
size = (out / 'model.npz').stat().st_size / 1e6
print(f'wrote {out}/model.npz ({size:.1f} MB) and {out}/meta.json')
if truth is not None:
from ecmodel import ECModel
keys = list(truth)
model = ECModel(out)
report(score(truth, dict(zip(keys, model.predict(keys)))), 'val as saved')
for alpha in (1.0, 0.0):
model.alpha = model.alpha_far = alpha
report(score(truth, dict(zip(keys, model.predict(keys)))), f'val alpha={alpha:.2f}')
if __name__ == '__main__':
main()