|
| 1 | +# Copyright (c) 2017-present, Facebook, Inc. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the license found in the LICENSE file in |
| 5 | +# the root directory of this source tree. An additional grant of patent rights |
| 6 | +# can be found in the PATENTS file in the same directory. |
| 7 | + |
| 8 | +import torch |
| 9 | +import unittest |
| 10 | +from fairseq.modules.sparse_multihead_attention import SparseMultiheadAttention |
| 11 | + |
| 12 | + |
| 13 | +class TestSparseMultiheadAttention(unittest.TestCase): |
| 14 | + def test_sparse_multihead_attention(self): |
| 15 | + attn_weights = torch.randn(1, 8, 8) |
| 16 | + bidirectional_sparse_mask = torch.tensor([ |
| 17 | + [0, 0, 0, 0, 0, float('-inf'), float('-inf'), 0], |
| 18 | + [0, 0, 0, 0, 0, float('-inf'), float('-inf'), 0], |
| 19 | + [0, 0, 0, 0, 0, float('-inf'), float('-inf'), 0], |
| 20 | + [0, 0, 0, 0, 0, float('-inf'), float('-inf'), 0], |
| 21 | + [float('-inf'), float('-inf'), float('-inf'), 0, 0, 0, 0, 0], |
| 22 | + [float('-inf'), float('-inf'), float('-inf'), 0, 0, 0, 0, 0], |
| 23 | + [float('-inf'), float('-inf'), float('-inf'), 0, 0, 0, 0, 0], |
| 24 | + [float('-inf'), float('-inf'), float('-inf'), 0, 0, 0, 0, 0] |
| 25 | + ]) |
| 26 | + |
| 27 | + bidirectional_attention = SparseMultiheadAttention(16, 1, stride=4, expressivity=1, is_bidirectional=True) |
| 28 | + bidirectional_attention_sparse_mask = bidirectional_attention.buffered_sparse_mask(attn_weights, 8, 8) |
| 29 | + torch.all(torch.eq(bidirectional_attention_sparse_mask, bidirectional_sparse_mask)) |
| 30 | + |
| 31 | + sparse_mask = torch.tensor([ |
| 32 | + [0, float('-inf'), float('-inf'), float('-inf'), float('-inf'), float('-inf'), |
| 33 | + float('-inf'), float('-inf')], |
| 34 | + [0, 0, float('-inf'), float('-inf'), float('-inf'), float('-inf'), float('-inf'), float('-inf')], |
| 35 | + [0, 0, 0, float('-inf'), float('-inf'), float('-inf'), float('-inf'), float('-inf')], |
| 36 | + [0, 0, 0, 0, float('-inf'), float('-inf'), float('-inf'), float('-inf')], |
| 37 | + [0, 0, 0, 0, 0, float('-inf'), float('-inf'), float('-inf')], |
| 38 | + [float('-inf'), float('-inf'), float('-inf'), 0, 0, 0, float('-inf'), float('-inf')], |
| 39 | + [float('-inf'), float('-inf'), float('-inf'), 0, 0, 0, 0, float('-inf')], |
| 40 | + [float('-inf'), float('-inf'), float('-inf'), 0, 0, 0, 0, 0], |
| 41 | + ]) |
| 42 | + |
| 43 | + attention = SparseMultiheadAttention(16, 1, stride=4, expressivity=1, is_bidirectional=False) |
| 44 | + attention_sparse_mask = attention.buffered_sparse_mask(attn_weights, 8, 8) |
| 45 | + |
| 46 | + torch.all(torch.eq(attention_sparse_mask, sparse_mask)) |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == '__main__': |
| 50 | + unittest.main() |
0 commit comments