cyd0806 commited on
Commit
a952c62
·
verified ·
1 Parent(s): 8ad53b1

Upload apex-master/tests/L0/run_transformer/test_fused_softmax.py with huggingface_hub

Browse files
apex-master/tests/L0/run_transformer/test_fused_softmax.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test for fused softmax functions.
2
+
3
+ Ref: https://github.com/NVIDIA/Megatron-LM/blob/40becfc96c4144985458ac0e0fae45dbb111fbd2/megatron/fused_kernels/tests/test_fused_kernels.py
4
+ """ # NOQA
5
+ import itertools
6
+
7
+ import torch
8
+ from torch.testing._internal import common_utils
9
+
10
+ from apex.transformer import AttnMaskType
11
+ from apex.transformer.functional import FusedScaleMaskSoftmax
12
+
13
+
14
+ def attention_mask_func(attention_scores, attention_mask):
15
+ return attention_scores.masked_fill(attention_mask, -10000.0)
16
+
17
+ def forward_torch_softmax(input, mask, scale):
18
+ input = input * scale
19
+ mask_output = attention_mask_func(input, mask) if mask is not None else input
20
+ probs = torch.nn.Softmax(dim=-1)(mask_output)
21
+ all_k_masked = mask.all(axis=-1)
22
+ zero_attention_mask = (1.0 - all_k_masked.float())[:, :, :, None]
23
+ probs = probs * zero_attention_mask
24
+ return probs
25
+
26
+ autocast_dtypes = (
27
+ (torch.half, torch.bfloat16) if torch.cuda.is_bf16_supported() else (torch.half,)
28
+ )
29
+
30
+
31
+ class TestFusedScaleMaskSoftmax(common_utils.TestCase):
32
+ def _setup_fused_softmax(
33
+ self,
34
+ input_in_fp16,
35
+ input_in_bf16,
36
+ scale=None,
37
+ softmax_in_fp32=False,
38
+ attn_mask_type=AttnMaskType.padding,
39
+ ):
40
+ fused_fn = FusedScaleMaskSoftmax(
41
+ input_in_fp16=input_in_fp16,
42
+ input_in_bf16=input_in_bf16,
43
+ mask_func=attention_mask_func,
44
+ scale=scale,
45
+ softmax_in_fp32=softmax_in_fp32,
46
+ attn_mask_type=attn_mask_type,
47
+ scaled_masked_softmax_fusion=True,
48
+ )
49
+ torch_fn = FusedScaleMaskSoftmax(
50
+ input_in_fp16=input_in_fp16,
51
+ input_in_bf16=input_in_bf16,
52
+ mask_func=attention_mask_func,
53
+ scale=scale,
54
+ softmax_in_fp32=softmax_in_fp32,
55
+ attn_mask_type=attn_mask_type,
56
+ scaled_masked_softmax_fusion=False,
57
+ )
58
+ return fused_fn, torch_fn
59
+
60
+ def tearDown(self) -> None:
61
+ torch.cuda.empty_cache()
62
+ super().tearDown()
63
+
64
+ def test_fused_scale_mask_softmax(self):
65
+ """
66
+ attention_scores.shape = [4, 12, 24, 24]
67
+ mask.shape = [4, 1, 24, 24]
68
+ """
69
+ for (dtype, scale, softmax_in_fp32, shape) in itertools.product(
70
+ (torch.half, torch.bfloat16), (None, 2.0), (False, True), ((4, 12, 24, 24), (32, 12, 4, 214))
71
+ ):
72
+ msg = f"{dtype}-{scale}-{softmax_in_fp32}"
73
+ input_in_fp16 = dtype == torch.half
74
+ input_in_bf16 = dtype == torch.bfloat16
75
+ if not (scale is None or softmax_in_fp32):
76
+ with self.assertRaises(RuntimeError, msg=msg):
77
+ self._setup_fused_softmax(
78
+ input_in_fp16,
79
+ input_in_bf16,
80
+ scale,
81
+ softmax_in_fp32,
82
+ AttnMaskType.padding,
83
+ )
84
+ return
85
+ fused_fn, torch_fn = self._setup_fused_softmax(
86
+ input_in_fp16,
87
+ input_in_bf16,
88
+ scale,
89
+ softmax_in_fp32,
90
+ AttnMaskType.padding,
91
+ )
92
+
93
+ attention_scores_0 = (
94
+ torch.randn(shape)
95
+ .to(device="cuda", dtype=dtype)
96
+ .requires_grad_(True)
97
+ )
98
+ with torch.no_grad():
99
+ attention_scores_1 = attention_scores_0.clone().requires_grad_(True)
100
+ mask_shape = (shape[0],) + (1,) + shape[2:]
101
+ mask = torch.randint(0, 2, mask_shape, device="cuda").bool()
102
+ expected = fused_fn(attention_scores_0, mask)
103
+ actual = torch_fn(attention_scores_1, mask)
104
+ self.assertEqual(actual, expected, msg=msg)
105
+
106
+ g0 = torch.rand_like(actual)
107
+ with torch.no_grad():
108
+ g1 = g0.clone()
109
+ expected.backward(g0)
110
+ actual.backward(g1)
111
+
112
+ def test_autocast_fused_scale_mask_softmax(self):
113
+ for dtype in autocast_dtypes:
114
+ msg = f"dtype: {dtype}"
115
+ input_in_fp16 = dtype == torch.half
116
+ input_in_bf16 = dtype == torch.bfloat16
117
+ fused_fn, torch_fn = self._setup_fused_softmax(
118
+ input_in_fp16, input_in_bf16, attn_mask_type=AttnMaskType.padding
119
+ )
120
+
121
+ attention_scores_0 = (
122
+ torch.randn((4, 12, 24, 24)).cuda().requires_grad_(True)
123
+ )
124
+ with torch.no_grad():
125
+ attention_scores_1 = (
126
+ attention_scores_0.clone().to(dtype).requires_grad_(True)
127
+ )
128
+ mask = torch.randint(0, 2, (4, 1, 24, 24)).bool().cuda()
129
+
130
+ expected = torch_fn(attention_scores_1, mask)
131
+ with torch.amp.autocast('cuda', dtype=dtype):
132
+ actual = fused_fn(attention_scores_0, mask)
133
+ self.assertEqual(actual.dtype, dtype, msg=msg)
134
+ self.assertEqual(actual, expected, msg=msg)
135
+
136
+ g0 = torch.rand_like(actual)
137
+ with torch.no_grad():
138
+ g1 = g0.clone()
139
+ expected.backward(g0)
140
+ actual.backward(g1)
141
+
142
+ def test_fused_scale_softmax(self):
143
+ """
144
+ attention_scores.shape = [4, 12, 24, 24]
145
+ mask = None
146
+ """
147
+ for (dtype, scale, softmax_in_fp32, shape) in itertools.product(
148
+ (torch.half, torch.bfloat16), (None, 2.0), (False, True), ((4, 12, 24, 24), (32, 12, 4, 214))
149
+ ):
150
+ msg = f"{dtype}-{scale}-{softmax_in_fp32}"
151
+ input_in_fp16 = dtype == torch.half
152
+ input_in_bf16 = dtype == torch.bfloat16
153
+ if not (scale is None or softmax_in_fp32):
154
+ with self.assertRaises(RuntimeError, msg=msg):
155
+ self._setup_fused_softmax(
156
+ input_in_fp16,
157
+ input_in_bf16,
158
+ scale,
159
+ softmax_in_fp32,
160
+ AttnMaskType.padding,
161
+ )
162
+ return
163
+ fused_fn, torch_fn = self._setup_fused_softmax(
164
+ input_in_fp16,
165
+ input_in_bf16,
166
+ scale,
167
+ softmax_in_fp32,
168
+ AttnMaskType.padding,
169
+ )
170
+
171
+ attention_scores_0 = (
172
+ torch.randn(shape)
173
+ .to(device="cuda", dtype=dtype)
174
+ .requires_grad_(True)
175
+ )
176
+ with torch.no_grad():
177
+ attention_scores_1 = attention_scores_0.clone().requires_grad_(True)
178
+ mask = None
179
+
180
+ expected = fused_fn(attention_scores_0, mask)
181
+ actual = torch_fn(attention_scores_1, mask)
182
+ self.assertEqual(actual, expected, msg=msg)
183
+
184
+ g0 = torch.rand_like(actual)
185
+ with torch.no_grad():
186
+ g1 = g0.clone()
187
+ expected.backward(g0)
188
+ actual.backward(g1)
189
+
190
+ def test_autocast_fused_scale_softmax(self):
191
+ for dtype in autocast_dtypes:
192
+ msg = f"dtype: {dtype}"
193
+ input_in_fp16 = dtype == torch.half
194
+ input_in_bf16 = dtype == torch.bfloat16
195
+ fused_fn, torch_fn = self._setup_fused_softmax(
196
+ input_in_fp16, input_in_bf16, attn_mask_type=AttnMaskType.padding
197
+ )
198
+
199
+ attention_scores_0 = (
200
+ torch.randn((4, 12, 24, 24)).cuda().requires_grad_(True)
201
+ )
202
+ with torch.no_grad():
203
+ attention_scores_1 = (
204
+ attention_scores_0.clone().to(dtype).requires_grad_(True)
205
+ )
206
+ mask = None
207
+
208
+ expected = torch_fn(attention_scores_1, mask)
209
+ with torch.amp.autocast('cuda', dtype=dtype):
210
+ actual = fused_fn(attention_scores_0, mask)
211
+ self.assertEqual(actual.dtype, dtype, msg=msg)
212
+ self.assertEqual(actual, expected, msg=msg)
213
+
214
+ g0 = torch.rand_like(actual)
215
+ with torch.no_grad():
216
+ g1 = g0.clone()
217
+ expected.backward(g0)
218
+ actual.backward(g1)
219
+
220
+ def test_fused_upper_triangle_mask_softmax(self):
221
+ """
222
+ attn_weights.shape: [4, 12, 24, 24]
223
+ total_mask.shape: [4, 1, 24, 24]
224
+
225
+ total_mask[0, 0], a 24x24 matrix is like a lower triangular matrix, but
226
+ upper elements are True and lower elements and diagonal are False.
227
+ """
228
+ for (dtype, scale, softmax_in_fp32) in itertools.product(
229
+ (torch.half, torch.bfloat16), (None, 2.0), (False, True),
230
+ ):
231
+ msg = f"{dtype}-{scale}-{softmax_in_fp32}"
232
+ input_in_fp16 = dtype == torch.half
233
+ input_in_bf16 = dtype == torch.bfloat16
234
+ if not (scale is None or softmax_in_fp32):
235
+ with self.assertRaises(RuntimeError, msg=msg):
236
+ self._setup_fused_softmax(
237
+ input_in_fp16,
238
+ input_in_bf16,
239
+ scale,
240
+ softmax_in_fp32,
241
+ AttnMaskType.causal,
242
+ )
243
+ return
244
+ fused_fn, torch_fn = self._setup_fused_softmax(
245
+ input_in_fp16,
246
+ input_in_bf16,
247
+ scale,
248
+ softmax_in_fp32,
249
+ AttnMaskType.causal,
250
+ )
251
+
252
+ attn_weights_0 = (
253
+ torch.randn((4, 12, 24, 24))
254
+ .to(device="cuda", dtype=dtype)
255
+ .requires_grad_(True)
256
+ )
257
+ with torch.no_grad():
258
+ attn_weights_1 = attn_weights_0.clone().requires_grad_(True)
259
+ total_mask = (
260
+ ~(torch.tril(torch.randn((24, 24), device="cuda")).bool())
261
+ .unsqueeze(0)
262
+ .unsqueeze(0)
263
+ )
264
+ total_mask = total_mask.repeat((4, 1, 1, 1))
265
+ expected = fused_fn(attn_weights_0, total_mask)
266
+ actual = torch_fn(attn_weights_1, total_mask)
267
+ self.assertEqual(actual, expected, msg=msg)
268
+
269
+ g0 = torch.randn_like(actual)
270
+ with torch.no_grad():
271
+ g1 = g0.clone()
272
+ actual.backward(g0)
273
+ expected.backward(g1)
274
+
275
+ def test_autocast_fused_upper_triangle_mask_softmax(self):
276
+ for dtype in autocast_dtypes:
277
+ msg = f"dtype: {dtype}"
278
+ input_in_fp16 = dtype == torch.half
279
+ input_in_bf16 = dtype == torch.bfloat16
280
+ fused_fn, torch_fn = self._setup_fused_softmax(
281
+ input_in_fp16, input_in_bf16, attn_mask_type=AttnMaskType.causal
282
+ )
283
+
284
+ attn_weights_0 = (
285
+ torch.randn((4, 12, 24, 24)).cuda().requires_grad_(True)
286
+ )
287
+ with torch.no_grad():
288
+ attn_weights_1 = (
289
+ attn_weights_0.clone().to(dtype).requires_grad_(True)
290
+ )
291
+ total_mask = (
292
+ ~(torch.tril(torch.randn((24, 24), device="cuda")).bool())
293
+ .unsqueeze(0)
294
+ .unsqueeze(0)
295
+ )
296
+
297
+ with torch.amp.autocast('cuda', dtype=dtype):
298
+ actual = fused_fn(attn_weights_0, total_mask)
299
+ self.assertEqual(actual.dtype, dtype, msg=msg)
300
+ expected = torch_fn(attn_weights_1, total_mask)
301
+ self.assertEqual(actual, expected, msg=msg)
302
+
303
+ g0 = torch.randn_like(actual)
304
+ with torch.no_grad():
305
+ g1 = g0.clone()
306
+ actual.backward(g0)
307
+ expected.backward(g1)
308
+
309
+
310
+ class TestGenericFusedSoftmaxKernel(common_utils.TestCase):
311
+
312
+ def setUp(self):
313
+ super().setUp()
314
+ self.batch = 2
315
+ self.attn = 16
316
+ self.scale_t = 1.0
317
+ self.dtype = torch.float16
318
+ self.device = torch.cuda.current_device()
319
+ self.thresh = {"atol": 1e-3, "rtol": 1e-3}
320
+
321
+ qlen = [1, 2]
322
+ klen = [1, 2, 3, 4, 5, 8, 10, 11, 13, 128, 256, 1200, 1234]
323
+ available_cuda_mem = torch.cuda.memory.mem_get_info(self.device)[0] / (1024 ** 3)
324
+ if available_cuda_mem > 40:
325
+ qlen.extend([1234, 2322, 2348])
326
+ klen.extend([2048, 3123, 4096, 4128, 7234, 8192])
327
+
328
+ self.q_k_lens = itertools.product(qlen, klen)
329
+
330
+ def tearDown(self) -> None:
331
+ torch.cuda.empty_cache()
332
+ super().tearDown()
333
+
334
+ def test_forward(self, allmasked: bool=False):
335
+ import generic_scaled_masked_softmax_cuda
336
+ for qlen, klen in self.q_k_lens:
337
+ inputs = torch.normal(0, 2, (self.batch, self.attn, qlen, klen), dtype=self.dtype, device=self.device)
338
+ masks = (
339
+ torch.randint(0, 2, (self.batch, 1, qlen, klen), dtype=torch.bool, device=self.device)
340
+ if not allmasked else torch.ones((self.batch, 1, qlen, klen), dtype=torch.bool, device=self.device)
341
+ )
342
+ softmax_results = generic_scaled_masked_softmax_cuda.forward(inputs, masks, self.scale_t)
343
+ softmax_results_torch = forward_torch_softmax(inputs, masks, self.scale_t)
344
+ self.assertEqual(
345
+ softmax_results_torch.to(self.dtype), softmax_results, **self.thresh, msg=f"(q, k) = ({qlen, klen})")
346
+
347
+ def test_backward(self, allmasked: bool=False):
348
+ import generic_scaled_masked_softmax_cuda
349
+ prev_thresh = self.thresh
350
+ self.thresh = {"atol": 1.5e-1, "rtol": 5e-3}
351
+ for qlen, klen in self.q_k_lens:
352
+ inputs = torch.normal(0, 2, (self.batch, self.attn, qlen, klen), dtype=self.dtype, device=self.device)
353
+ backward = torch.rand_like(inputs, dtype=torch.float16, device=self.device)
354
+ masks = (
355
+ torch.randint(0, 2, (self.batch, 1, qlen, klen), dtype=torch.bool, device=self.device)
356
+ if not allmasked else torch.ones((self.batch, 1, qlen, klen), dtype=torch.bool, device=self.device)
357
+ )
358
+ softmax_results = generic_scaled_masked_softmax_cuda.forward(inputs, masks, self.scale_t)
359
+ back_grad = generic_scaled_masked_softmax_cuda.backward(backward, softmax_results, self.scale_t)
360
+ inputs.requires_grad = True
361
+ softmax_results_torch = forward_torch_softmax(inputs, masks, self.scale_t)
362
+ softmax_results_torch.backward(backward)
363
+ self.assertEqual(back_grad, inputs.grad, **self.thresh, msg=f"(q, k) = ({qlen, klen})")
364
+ self.thresh = prev_thresh
365
+
366
+ def test_allmasked(self):
367
+ self.test_forward(True)
368
+
369
+ def test_allmask_backward(self):
370
+ self.test_backward(True)
371
+
372
+
373
+ if __name__ == "__main__":
374
+ common_utils.run_tests()