forked from idiap/fast-transformers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_transformer_encoder.py
101 lines (90 loc) · 2.92 KB
/
test_transformer_encoder.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
#
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>,
# Apoorv Vyas <avyas@idiap.ch>
#
import unittest
import torch
from fast_transformers.attention import AttentionLayer, FullAttention, \
ClusteredAttention, ImprovedClusteredAttention, ReformerAttention
from fast_transformers.masking import FullMask
from fast_transformers.transformers import TransformerEncoderLayer, TransformerEncoder
class TestTransformerEncoder(unittest.TestCase):
def test_full_attention_forward(self):
d_model = 128
n_heads = 4
transformer = TransformerEncoder([
TransformerEncoderLayer(
AttentionLayer(FullAttention(), d_model, n_heads),
d_model,
n_heads
)
for i in range(6)
])
x = transformer(torch.rand(10, 7, d_model))
self.assertEqual(x.shape, (10, 7, d_model))
def test_clustered_attention_forward(self):
d_model = 128
n_heads = 4
transformer = TransformerEncoder([
TransformerEncoderLayer(
AttentionLayer(
ClusteredAttention(
clusters = 10
),
d_model,
n_heads
),
d_model,
n_heads
)
for i in range(6)
])
x = transformer(torch.rand(100, 20, d_model))
self.assertEqual(x.shape, (100, 20, d_model))
def test_improved_clustered_attention_forward(self):
d_model = 128
n_heads = 4
transformer = TransformerEncoder([
TransformerEncoderLayer(
AttentionLayer(
ImprovedClusteredAttention(
clusters=10,
topk=5
),
d_model,
n_heads
),
d_model,
n_heads
)
for i in range(6)
])
x = torch.rand(100, 20, d_model)
y = transformer(x)
self.assertEqual(y.shape, (100, 20, d_model))
def test_improved_clustered_attention_forward(self):
d_model = 128
n_heads = 4
transformer = TransformerEncoder([
TransformerEncoderLayer(
AttentionLayer(
ReformerAttention(
chunk_size=32,
rounds=4,
bits=8,
masked=False,
),
d_model,
n_heads
),
d_model,
n_heads
)
for i in range(6)
])
x = torch.rand(12, 128, d_model)
y = transformer(x)
self.assertEqual(y.shape, (12, 128, d_model))
if __name__ == "__main__":
unittest.main()