-
Notifications
You must be signed in to change notification settings - Fork 9
/
fatt_transfer.py
173 lines (145 loc) · 5.05 KB
/
fatt_transfer.py
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
from argparse import ArgumentParser
import os
from pathlib import Path
import random
import string
import io
import matplotlib.pyplot as plt
import pytorch_lightning as pl
import torch
import wandb
from mogwai.data_loading import MSADataModule
from mogwai.metrics import contact_auc
from mogwai.models import FactoredAttention
from mogwai.parsing import read_contacts
from mogwai.plotting import (
plot_colored_preds_on_trues,
plot_precision_vs_length,
)
from mogwai.utils.functional import apc
from mogwai.vocab import FastaVocab
from loggers import WandbLoggerFrozenVal
def train():
# Initialize parser
parser = ArgumentParser()
parser.add_argument(
"--freeze_random_value",
action="store_true",
help="Whether to freeze values at init.",
)
parser.add_argument(
"--weight_save_path", type=str, default=None, help="Where to store state dict."
)
parser.add_argument(
"--load_values_from",
type=str,
default=None,
help="Path to state dict for saved values. Freezes values.",
)
parser.add_argument(
"--wandb_project",
type=str,
default="iclr2021-rebuttal",
help="W&B project used for logging.",
)
parser.add_argument(
"--pdb",
type=str,
help="PDB id for training",
)
parser = MSADataModule.add_args(parser)
parser = pl.Trainer.add_argparse_args(parser)
parser.set_defaults(
gpus=1,
min_steps=50,
max_steps=1000,
log_every_n_steps=10,
)
parser = FactoredAttention.add_args(parser)
args = parser.parse_args()
# Modify name
pdb = args.pdb
args.data = "data/npz/" + pdb + ".npz"
# Load msa
msa_dm = MSADataModule.from_args(args)
msa_dm.setup()
# Load contacts
true_contacts = torch.from_numpy(read_contacts(args.data))
# Initialize model
num_seqs, msa_length, msa_counts = msa_dm.get_stats()
model = FactoredAttention.from_args(
args,
num_seqs=num_seqs,
msa_length=msa_length,
msa_counts=msa_counts,
vocab_size=len(FastaVocab),
pad_idx=FastaVocab.pad_idx,
true_contacts=true_contacts,
)
cached_val = None
if args.freeze_random_value:
model.value.requires_grad = False
cached_val = model.value.data.clone().cpu()
if args.load_values_from:
saved_state = torch.load(args.load_values_from)
model.value.requires_grad = False
model.value.data = saved_state["value"]
cached_val = model.value.data.clone().cpu()
kwargs = {}
randstring = "".join(random.choice(string.ascii_lowercase) for i in range(6))
run_name = "_".join(["fatt", pdb, randstring])
logger = WandbLoggerFrozenVal(project=args.wandb_project, name=run_name)
logger.log_hyperparams(args)
logger.log_hyperparams(
{
"pdb": pdb,
"num_seqs": num_seqs,
"msa_length": msa_length,
}
)
kwargs["logger"] = logger
# Initialize Trainer
trainer = pl.Trainer.from_argparse_args(args, **kwargs)
trainer.fit(model, msa_dm)
if args.load_values_from or args.freeze_random_value:
if torch.all(cached_val.eq(model.value.data.clone().cpu())):
print("Values unchanged!")
else:
raise ValueError(
"Value matrix changed during training but was supposed to be frozen."
)
# Log and print some metrics after training.
contacts = model.get_contacts()
apc_contacts = apc(contacts)
auc = contact_auc(contacts, true_contacts).item()
auc_apc = contact_auc(apc_contacts, true_contacts).item()
print(f"AUC: {auc:0.3f}, AUC_APC: {auc_apc:0.3f}")
filename = "top_L_contacts.png"
plot_colored_preds_on_trues(contacts, true_contacts, point_size=5, cutoff=1)
plt.title(f"Top L no APC {model.get_precision(do_apc=False)}")
logger.log_metrics({filename: wandb.Image(plt)})
plt.close()
filename = "top_L_contacts_apc.png"
plot_colored_preds_on_trues(apc_contacts, true_contacts, point_size=5, cutoff=1)
plt.title(f"Top L APC {model.get_precision(do_apc=True)}")
logger.log_metrics({filename: wandb.Image(plt)})
plt.close()
filename = "top_L_5_contacts.png"
plot_colored_preds_on_trues(contacts, true_contacts, point_size=5, cutoff=5)
plt.title(f"Top L/5 no APC {model.get_precision(do_apc=False, cutoff=5)}")
logger.log_metrics({filename: wandb.Image(plt)})
plt.close()
filename = "top_L_5_contacts_apc.png"
plot_colored_preds_on_trues(apc_contacts, true_contacts, point_size=5, cutoff=5)
plt.title(f"Top L/5 APC {model.get_precision(do_apc=True, cutoff=5)}")
logger.log_metrics({filename: wandb.Image(plt)})
plt.close()
filename = "precision_vs_L.png"
plot_precision_vs_length(apc_contacts, true_contacts)
logger.log_metrics({filename: wandb.Image(plt)})
plt.close()
if args.weight_save_path:
weight_save_path = Path(args.weight_save_path)
torch.save(model.state_dict(), weight_save_path)
if __name__ == "__main__":
train()