test_structure_module.py 10.9 KB
Newer Older
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Copyright 2021 AlQuraishi Laboratory
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch
import numpy as np
import unittest

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
19
from openfold.data.data_transforms import make_atom14_masks_np
20
from openfold.np.residue_constants import (
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
21
    restype_atom14_mask,
22
    restype_atom37_mask,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
23
)
24
from openfold.model.structure_module import (
25
26
27
28
    StructureModule,
    StructureModuleTransition,
    AngleResnet,
    InvariantPointAttention,
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
29
)
30
from openfold.utils.rigid_utils import Rotation, Rigid
31
32
33
from openfold.utils.geometry.rigid_matrix_vector import Rigid3Array
from openfold.utils.geometry.rotation_matrix import Rot3Array
from openfold.utils.geometry.vector import Vec3Array
34
35
36
37
38
39
import tests.compare_utils as compare_utils
from tests.config import consts
from tests.data_utils import (
    random_affines_4x4,
)

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
40
if compare_utils.alphafold_is_installed():
41
42
43
    alphafold = compare_utils.import_alphafold()
    import jax
    import haiku as hk
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
44
45
46


class TestStructureModule(unittest.TestCase):
47
48
49
50
51
52
53
54
55
56
57
58
59
    @classmethod
    def setUpClass(cls):
        if consts.is_multimer:
            cls.am_atom = alphafold.model.all_atom_multimer
            cls.am_fold = alphafold.model.folding_multimer
            cls.am_modules = alphafold.model.modules_multimer
            cls.am_rigid = alphafold.model.geometry
        else:
            cls.am_atom = alphafold.model.all_atom
            cls.am_fold = alphafold.model.folding
            cls.am_modules = alphafold.model.modules
            cls.am_rigid = alphafold.model.r3

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
60
    def test_structure_module_shape(self):
61
62
63
64
        batch_size = consts.batch_size
        n = consts.n_res
        c_s = consts.c_s
        c_z = consts.c_z
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
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
        c_ipa = 13
        c_resnet = 17
        no_heads_ipa = 6
        no_query_points = 4
        no_value_points = 4
        dropout_rate = 0.1
        no_layers = 3
        no_transition_layers = 3
        no_resnet_layers = 3
        ar_epsilon = 1e-6
        no_angles = 7
        trans_scale_factor = 10
        inf = 1e5

        sm = StructureModule(
            c_s,
            c_z,
            c_ipa,
            c_resnet,
            no_heads_ipa,
            no_query_points,
            no_value_points,
            dropout_rate,
            no_layers,
            no_transition_layers,
            no_resnet_layers,
            no_angles,
            trans_scale_factor,
            ar_epsilon,
            inf,
95
            is_multimer=consts.is_multimer
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
96
97
98
99
100
101
102
103
        )

        s = torch.rand((batch_size, n, c_s))
        z = torch.rand((batch_size, n, n, c_z))
        f = torch.randint(low=0, high=21, size=(batch_size, n)).long()

        out = sm(s, z, f)

104
105
106
107
108
        if consts.is_multimer:
            self.assertTrue(out["frames"].shape == (no_layers, batch_size, n, 4, 4))
        else:
            self.assertTrue(out["frames"].shape == (no_layers, batch_size, n, 7))

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        self.assertTrue(
            out["angles"].shape == (no_layers, batch_size, n, no_angles, 2)
        )
        self.assertTrue(
            out["positions"].shape == (no_layers, batch_size, n, 14, 3)
        )

    def test_structure_module_transition_shape(self):
        batch_size = 2
        n = 5
        c = 7
        num_layers = 3
        dropout = 0.1

        smt = StructureModuleTransition(c, num_layers, dropout)

        s = torch.rand((batch_size, n, c))

        shape_before = s.shape
        s = smt(s)
        shape_after = s.shape

        self.assertTrue(shape_before == shape_after)

133
134
135
136
137
    @compare_utils.skip_unless_alphafold_installed()
    def test_structure_module_compare(self):
        config = compare_utils.get_alphafold_config()
        c_sm = config.model.heads.structure_module
        c_global = config.model.global_config
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
138

139
        def run_sm(representations, batch):
140
            sm = self.am_fold.StructureModule(c_sm, c_global)
141
            representations = {
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
142
                k: jax.lax.stop_gradient(v) for k, v in representations.items()
143
            }
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
144
            batch = {k: jax.lax.stop_gradient(v) for k, v in batch.items()}
145
146
147

            if consts.is_multimer:
                return sm(representations, batch, is_training=False, compute_loss=True)
148
            return sm(representations, batch, is_training=False)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
149

150
        f = hk.transform(run_sm)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
151

152
        n_res = 200
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
153

154
        representations = {
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
155
156
            "single": np.random.rand(n_res, consts.c_s).astype(np.float32),
            "pair": np.random.rand(n_res, n_res, consts.c_z).astype(np.float32),
157
        }
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
158

159
        batch = {
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
160
161
            "seq_mask": np.random.randint(0, 2, (n_res,)).astype(np.float32),
            "aatype": np.random.randint(0, 21, (n_res,)),
162
        }
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
163
164
165

        batch["atom14_atom_exists"] = np.take(
            restype_atom14_mask, batch["aatype"], axis=0
166
        )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
167
168
169

        batch["atom37_atom_exists"] = np.take(
            restype_atom37_mask, batch["aatype"], axis=0
170
        )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
171

172
        batch.update(make_atom14_masks_np(batch))
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
173

174
175
176
        params = compare_utils.fetch_alphafold_module_weights(
            "alphafold/alphafold_iteration/structure_module"
        )
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
177

178
        key = jax.random.PRNGKey(42)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
179
        out_gt = f.apply(params, key, representations, batch)
180
181
        out_gt = torch.as_tensor(
            np.array(out_gt["final_atom14_positions"].block_until_ready())
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
182
183
        )

184
185
        model = compare_utils.get_global_pretrained_openfold()
        out_repro = model.structure_module(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
186
187
188
            torch.as_tensor(representations["single"]).cuda(),
            torch.as_tensor(representations["pair"]).cuda(),
            torch.as_tensor(batch["aatype"]).cuda(),
189
190
191
            mask=torch.as_tensor(batch["seq_mask"]).cuda(),
        )
        out_repro = out_repro["positions"][-1].cpu()
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
192

193
        # The structure module, thanks to angle normalization, is very volatile
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
194
        # We only assess the mean here. Heuristically speaking, it seems to
195
        # have lower error in general on real rather than synthetic data.
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
196
        self.assertTrue(torch.mean(torch.abs(out_gt - out_repro)) < 0.05)
197

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
198
199

class TestInvariantPointAttention(unittest.TestCase):
200
201
202
203
204
205
206
207
208
209
210
211
212
    @classmethod
    def setUpClass(cls):
        if consts.is_multimer:
            cls.am_atom = alphafold.model.all_atom_multimer
            cls.am_fold = alphafold.model.folding_multimer
            cls.am_modules = alphafold.model.modules_multimer
            cls.am_rigid = alphafold.model.geometry
        else:
            cls.am_atom = alphafold.model.all_atom
            cls.am_fold = alphafold.model.folding
            cls.am_modules = alphafold.model.modules
            cls.am_rigid = alphafold.model.r3

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    def test_shape(self):
        c_m = 13
        c_z = 17
        c_hidden = 19
        no_heads = 5
        no_qp = 7
        no_vp = 11

        batch_size = 2
        n_res = 23

        s = torch.rand((batch_size, n_res, c_m))
        z = torch.rand((batch_size, n_res, n_res, c_z))
        mask = torch.ones((batch_size, n_res))

228
        rot_mats = torch.rand((batch_size, n_res, 3, 3))
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
229
230
        trans = torch.rand((batch_size, n_res, 3))

231
232
233
234
235
236
237
        if consts.is_multimer:
            rotation = Rot3Array.from_array(rot_mats)
            translation = Vec3Array.from_array(trans)
            r = Rigid3Array(rotation, translation)
        else:
            rots = Rotation(rot_mats=rot_mats, quats=None)
            r = Rigid(rots, trans)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
238
239

        ipa = InvariantPointAttention(
240
            c_m, c_z, c_hidden, no_heads, no_qp, no_vp, is_multimer=consts.is_multimer
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
241
242
243
        )

        shape_before = s.shape
244
        s = ipa(s, z, r, mask)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
245
246
247

        self.assertTrue(s.shape == shape_before)

248
249
250
    @compare_utils.skip_unless_alphafold_installed()
    def test_ipa_compare(self):
        def run_ipa(act, static_feat_2d, mask, affine):
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
251
            config = compare_utils.get_alphafold_config()
252
            ipa = self.am_fold.InvariantPointAttention(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
253
254
                config.model.heads.structure_module,
                config.model.global_config,
255
            )
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271

            if consts.is_multimer:
                attn = ipa(
                    inputs_1d=act,
                    inputs_2d=static_feat_2d,
                    mask=mask,
                    rigid=affine
                )
            else:
                attn = ipa(
                    inputs_1d=act,
                    inputs_2d=static_feat_2d,
                    mask=mask,
                    affine=affine
                )

272
            return attn
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
273

274
        f = hk.transform(run_ipa)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
275

276
277
278
        n_res = consts.n_res
        c_s = consts.c_s
        c_z = consts.c_z
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
279

280
281
282
283
284
        sample_act = np.random.rand(n_res, c_s)
        sample_2d = np.random.rand(n_res, n_res, c_z)
        sample_mask = np.ones((n_res, 1))

        affines = random_affines_4x4((n_res,))
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
285

286
287
288
289
290
291
292
293
294
295
296
297
298
        if consts.is_multimer:
            rigids = self.am_rigid.Rigid3Array.from_array4x4(affines)
            transformations = Rigid3Array.from_tensor_4x4(
                torch.as_tensor(affines).float()
            )
            sample_affine = rigids
        else:
            rigids = self.am_rigid.rigids_from_tensor4x4(affines)
            quats = self.am_rigid.rigids_to_quataffine(rigids)
            transformations = Rigid.from_tensor_4x4(
                torch.as_tensor(affines).float().cuda()
            )
            sample_affine = quats
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
299

300
        ipa_params = compare_utils.fetch_alphafold_module_weights(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
301
302
            "alphafold/alphafold_iteration/structure_module/"
            + "fold_iteration/invariant_point_attention"
303
304
305
306
307
308
309
310
311
312
        )

        out_gt = f.apply(
            ipa_params, None, sample_act, sample_2d, sample_mask, sample_affine
        ).block_until_ready()
        out_gt = torch.as_tensor(np.array(out_gt))

        with torch.no_grad():
            model = compare_utils.get_global_pretrained_openfold()
            out_repro = model.structure_module.ipa(
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
313
314
315
                torch.as_tensor(sample_act).float().cuda(),
                torch.as_tensor(sample_2d).float().cuda(),
                transformations,
316
317
                torch.as_tensor(sample_mask.squeeze(-1)).float().cuda(),
            ).cpu()
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
318

319
320
        self.assertTrue(torch.max(torch.abs(out_gt - out_repro)) < consts.eps)

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
321
322

class TestAngleResnet(unittest.TestCase):
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
323
    def test_shape(self):
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
324
325
326
327
328
329
330
        batch_size = 2
        n = 3
        c_s = 13
        c_hidden = 11
        no_layers = 5
        no_angles = 7
        epsilon = 1e-12
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
331

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
332
333
334
335
        ar = AngleResnet(c_s, c_hidden, no_layers, no_angles, epsilon)
        a = torch.rand((batch_size, n, c_s))
        a_initial = torch.rand((batch_size, n, c_s))

Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
336
        _, a = ar(a, a_initial)
Gustaf Ahdritz's avatar
Gustaf Ahdritz committed
337
338
339
340
341
342

        self.assertTrue(a.shape == (batch_size, n, no_angles, 2))


if __name__ == "__main__":
    unittest.main()