File size: 9,502 Bytes
177457f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""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()