-
Notifications
You must be signed in to change notification settings - Fork 552
/
test_attentions.py
362 lines (290 loc) · 11 KB
/
test_attentions.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import torch
from xformers.components import InProjContainer, InProjParams, MultiHeadDispatch
# Automatically test all the registered attentions
from xformers.components.attention import (
_DENSITY_THRESHOLD,
ATTENTION_REGISTRY,
build_attention,
)
DEVICES = (
[torch.device("cpu")] if not torch.cuda.is_available() else [torch.device("cuda")]
)
BATCH = 2
SEQ = 128 if torch.cuda.is_available() else 32
MODEL = 128 if torch.cuda.is_available() else 64
GLOBAL_ATTENTION_RATIO = (
_DENSITY_THRESHOLD * 0.9
) # Make sure that we test the sparse implementation, no matter the threshold
assert ATTENTION_REGISTRY.keys(), "Attention layers should have been registered"
def _get_multihead(
attention_name,
attn_dropout,
res_dropout,
causal,
heads,
device,
skip_output_projection=False,
):
test_config = {
"name": attention_name,
"dropout": attn_dropout,
"causal": causal,
"seq_len": SEQ,
"window_size": SEQ // 8 + 1, # local attention
"attention_query_mask": torch.rand((SEQ, 1)) < GLOBAL_ATTENTION_RATIO,
"num_heads": heads,
"dim_head": MODEL // heads,
"num_rules": 2, # Compositional Attention
}
if skip_output_projection:
def noop(x):
return x
test_config["out_proj"] = noop
# Add some blocksparse layout to test the corresponding attention
block_size = 16
test_config["layout"] = torch.eye(
SEQ // block_size, SEQ // block_size, dtype=torch.long
)
test_config["block_size"] = block_size
attention = build_attention(test_config)
# build a multi head dispatch to test this attention mechanism
multi_head = MultiHeadDispatch(
seq_len=SEQ,
dim_model=MODEL,
residual_dropout=res_dropout,
num_heads=heads,
attention=attention,
).to(device)
return multi_head
@pytest.mark.parametrize("attn_dropout", [0.0, 0.3])
@pytest.mark.parametrize("residual_dropout", [0.0, 0.1])
@pytest.mark.parametrize("causal", [True, False])
@pytest.mark.parametrize("heads", [1, 4])
@pytest.mark.parametrize("attention_name", ATTENTION_REGISTRY.keys())
@pytest.mark.parametrize("device", DEVICES)
def test_order_invariance(
attention_name: str,
heads: int,
attn_dropout: float,
residual_dropout: float,
causal: bool,
device: torch.device,
):
torch.manual_seed(42)
multi_head = _get_multihead(
attention_name, attn_dropout, residual_dropout, causal, heads, device
)
# Check that a shuffled input produces the same results
seqs = [SEQ, SEQ - 16] if (attention_name != "blocksparse") else [SEQ]
for seq in seqs:
# Check that we can pass a smaller sequence
inputs = torch.rand(BATCH, seq, MODEL, device=device)
shuffle = torch.randperm(inputs.shape[1])
inputs_shuffled = inputs[:, shuffle, :].clone()
results = multi_head(inputs, inputs, inputs)
results_shuffled = multi_head(inputs_shuffled, inputs_shuffled, inputs_shuffled)
torch.allclose(results[:, shuffle, :], results_shuffled)
# Test the non-self-attention codepath
att = multi_head(inputs, inputs_shuffled, inputs)
# Check that dropout actually drops some values
if attn_dropout > 0:
att_2 = multi_head(inputs, inputs_shuffled, inputs)
assert (att != att_2).any()
@pytest.mark.parametrize("heads", [1, 4])
@pytest.mark.parametrize("attention_name", ["scaled_dot_product"])
@pytest.mark.parametrize("device", DEVICES)
def test_kqv_ordering(
attention_name: str,
heads: int,
device: torch.device,
):
multi_head = _get_multihead(attention_name, 0.0, 0.0, False, heads, device)
# Check kqv are not flipped
# this will not catch all issues, but would catch a V being misplaced
# make k and q complimentary, so that QKt is all zero and attention is uniform
q = torch.cat(
(
torch.rand((1, MODEL // 2), device=device),
torch.zeros((1, MODEL // 2), device=device),
),
dim=1,
).expand((BATCH, SEQ, MODEL))
k = torch.cat(
(
torch.zeros((1, MODEL // 2), device=device),
torch.rand((1, MODEL // 2), device=device),
),
dim=1,
).expand((BATCH, SEQ, MODEL))
v = torch.rand(BATCH, SEQ, MODEL, device=device)
# Normal call
res = multi_head(query=q, key=k, value=v)
for i in range(BATCH):
assert torch.allclose(res[i, :, :], res[i, 0, :].unsqueeze(-2))
assert not torch.allclose(res[0, :, :], res[1, :, :])
# Flip qkv, and check that we invert the above check properly
res_false = multi_head(query=v, key=k, value=q)
assert torch.allclose(res_false[0, :, :], res_false[1, :, :])
@pytest.mark.parametrize("small_init", [False, True])
@pytest.mark.parametrize("proj_bias", [False, True])
@pytest.mark.parametrize("same_sizes", [False, True])
@pytest.mark.parametrize("same_settings", [False, True])
def test_inproj(
small_init: bool, proj_bias: bool, same_sizes: bool, same_settings: bool
):
test_config = {
"name": "scaled_dot_product",
"dropout": 0.1,
"causal": False,
"seq_len": SEQ,
"window_size": SEQ // 8 + 1,
"num_heads": 1,
"dim_head": MODEL,
}
attention = build_attention(test_config)
# Construct the initial projection, test different options
in_params = InProjParams(MODEL, MODEL, proj_bias, small_init)
if same_settings:
in_proj = InProjContainer(in_params, None, None)
else:
out_features = MODEL if same_sizes else MODEL - 16
in_params_flip = InProjParams(MODEL, out_features, not proj_bias, small_init)
in_proj = InProjContainer(in_params, in_params_flip, in_params_flip)
# build a multi head dispatch to test this attention mechanism
multi_head = MultiHeadDispatch(
seq_len=SEQ,
dim_model=MODEL,
residual_dropout=0.1,
num_heads=1,
attention=attention,
in_proj_container=in_proj,
)
# Check kqv are not flipped
# this will not catch all issues, but would catch a V being misplaced
# make k and q complimentary, so that QKt is all zero and attention is uniform
q = torch.cat(
(
torch.rand((1, MODEL // 2)),
torch.zeros((1, MODEL // 2)),
),
dim=1,
).expand((BATCH, SEQ, MODEL))
k = torch.cat(
(
torch.zeros((1, MODEL // 2)),
torch.rand((1, MODEL // 2)),
),
dim=1,
).expand((BATCH, SEQ, MODEL))
v = torch.rand(BATCH, SEQ, MODEL)
# just check that a FW does not assert out
_ = multi_head(query=q, key=k, value=v)
@pytest.mark.parametrize("heads", [1, 4])
@pytest.mark.parametrize("attention_name", ATTENTION_REGISTRY.keys())
@pytest.mark.parametrize("device", DEVICES)
def test_different_kq_dimensions(
attention_name: str,
heads: int,
device: torch.device,
):
multi_head = _get_multihead(attention_name, 0.0, 0.0, False, heads, device)
if multi_head.attention.requires_same_k_q_dimensions:
# pyre-fixme[29]: The library function `pytest.skip` is not supported by Pyre.
pytest.skip(f"{attention_name} does not support different k, q dimensions yet.")
seq_q = SEQ - 16
q = torch.rand((BATCH, seq_q, MODEL), device=device)
k = torch.rand((BATCH, SEQ, MODEL), device=device)
v = torch.rand((BATCH, SEQ, MODEL), device=device)
res = multi_head(query=q, key=k, value=v)
assert res.shape == torch.Size([BATCH, seq_q, MODEL])
@pytest.mark.parametrize("heads", [1, 4])
@pytest.mark.parametrize("attention_name", ["scaled_dot_product", "favor"])
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a CUDA gpu")
def test_causal(
attention_name: str,
heads: int,
):
"""
Make sure that the causal flag is respected.
The input data is orthogonal by design if causal is respected, but if the attention looks ahead this will fail
"""
torch.random.manual_seed(42)
device = torch.device("cuda")
multi_head = _get_multihead(
attention_name,
0.0,
0.0,
causal=True,
heads=heads,
device=device,
skip_output_projection=True,
)
k = (
torch.tril(torch.ones((SEQ, SEQ), device=device), diagonal=0)
.unsqueeze(0)
.expand(1, -1, -1)
)
q = (
torch.triu(torch.ones((SEQ, SEQ), device=device), diagonal=0)
.unsqueeze(0)
.expand(1, -1, -1)
)
v = (
torch.arange(SEQ, device=device)
.float()
.unsqueeze(0)
.unsqueeze(-1)
.expand(1, -1, SEQ)
)
# Make sure that we don´t project, to keep the embeddings orthogonal
multi_head.attention.requires_input_projection = False
res = multi_head(query=q, key=k, value=v).squeeze(0)
# Consolidate along the embedding, if causal was respected the amplitude should be sorted already
res_sum = torch.sum(res, dim=1).cpu()
assert torch.allclose(torch.sort(res_sum)[1], torch.arange(SEQ)) or torch.allclose(
torch.sort(res_sum, descending=True)[1], torch.arange(SEQ)
), res_sum
@pytest.mark.parametrize("attn_dropout", [0.0, 0.1])
@pytest.mark.parametrize("heads", [2])
@pytest.mark.parametrize("attention_name", ATTENTION_REGISTRY.keys())
@pytest.mark.skipif(torch.cuda.is_available(), reason="CUDA gpu not supported yet")
def test_torch_script_ability(
attention_name: str,
heads: int,
attn_dropout: float,
):
if attention_name in {
"favor",
"global",
"local",
"random",
}:
# pyre-fixme[29]: The library function `pytest.skip` is not supported by Pyre.
pytest.skip(f"{attention_name} does not support scripting yet.")
device = torch.device("cpu")
multi_head = _get_multihead(attention_name, attn_dropout, 0.0, False, heads, device)
# input for tracing the function
q = torch.rand((BATCH, SEQ, MODEL), device=device)
k = torch.rand((BATCH, SEQ, MODEL), device=device)
v = torch.rand((BATCH, SEQ, MODEL), device=device)
# to make sure dropout behaves deterministically
torch.random.manual_seed(42)
# tracing the attention module
traced_multi_head = torch.jit.trace(multi_head, (q, k, v))
# create new random inputs for testing the eager model and traced model
q = torch.rand((BATCH, SEQ, MODEL), device=device)
k = torch.rand((BATCH, SEQ, MODEL), device=device)
v = torch.rand((BATCH, SEQ, MODEL), device=device)
# to make sure dropout behaves deterministically need to set the seed again
torch.random.manual_seed(42)
res = multi_head(query=q, key=k, value=v)
# to make sure dropout behaves deterministically need to set the seed again
torch.random.manual_seed(42)
res_traced = traced_multi_head(query=q, key=k, value=v)
assert torch.allclose(res, res_traced)
# TODO: way more unit tests..