test_primitives.py 1.81 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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

from openfold.model.primitives import (
20
21
22
23
    _lma,
    _attention,
    DEFAULT_LMA_Q_CHUNK_SIZE,
    DEFAULT_LMA_KV_CHUNK_SIZE
24
25
26
27
28
29
30
31
32
)
from tests.config import consts


class TestLMA(unittest.TestCase):
    def test_lma_vs_attention(self):
        batch_size = consts.batch_size
        c_hidden = 32 
        n = 2**12
33
        n_seq = 12
34
35
        no_heads = 4

36
37
38
        q = torch.rand(batch_size, n_seq, no_heads, n, c_hidden).cuda()
        k = torch.rand(batch_size, n_seq, no_heads, n, c_hidden).cuda()
        v = torch.rand(batch_size, n_seq, no_heads, n, c_hidden).cuda()
39

40
41
        bias = [torch.rand(batch_size, n_seq, 1, 1, n), torch.rand(batch_size, 1, no_heads, n, n)]
        biases = [b.cuda() for b in bias]
42
43
        
        with torch.no_grad():
44
45
46
47
48
49
50
51
52
            lma_biases = [
                b.expand(b.shape[:-2] + (q.shape[-2],) + (k.shape[-2],))
                for b in biases
            ]
            l = _lma(q, k, v, lma_biases, DEFAULT_LMA_Q_CHUNK_SIZE, DEFAULT_LMA_KV_CHUNK_SIZE).cpu()
            real = _attention(q, k, v, biases).cpu()
       
        err = torch.max(torch.abs(l - real))
        self.assertTrue(err < consts.eps, f'Error: {err}')
53
54
55
56

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