cyd0806 commited on
Commit
5169fd4
·
verified ·
1 Parent(s): bc3ded4

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

Browse files
apex-master/tests/L0/run_transformer/test_layers.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import unittest
3
+ import typing
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.testing._internal import common_utils
8
+
9
+ from apex.transformer import parallel_state
10
+ from apex.transformer.tensor_parallel import layers
11
+ from apex.transformer.testing.commons import set_random_seed
12
+ from apex.transformer.testing.distributed_test_base import NcclDistributedTestBase
13
+ from apex.transformer.testing.distributed_test_base import UccDistributedTestBase
14
+
15
+
16
+ logging.getLogger("torch").setLevel(logging.WARNING)
17
+ logging.getLogger("apex").setLevel(logging.WARNING)
18
+
19
+
20
+ # N.B.(mkozuki): Disable TF32 matrix multiply.
21
+ # Matrices used in this test are so small that TF32 matmul
22
+ # can be less precise so that `self.assertEqual` raises.
23
+ torch.backends.cuda.matmul.allow_tf32 = False
24
+
25
+
26
+ class TensorParallelLayerTestBase:
27
+
28
+ BATCH_SIZE: int = 8
29
+ SEQUENCE_LENGTH: int = 128
30
+ VOCAB_SIZE: int = 1024
31
+ HIDDEN_SIZE: int = 256
32
+ INPUT_SIZE_COEFF: int = 256
33
+ OUTPUT_SIZE_COEFF: int = 256
34
+ SEED: int = 123456
35
+
36
+ @property
37
+ def tensor_shape(self) -> typing.Sequence[int]:
38
+ return [self.SEQUENCE_LENGTH, self.BATCH_SIZE, self.HIDDEN_SIZE]
39
+
40
+ @torch.no_grad()
41
+ @unittest.skipIf(torch.cuda.device_count() < 2, "Requires >=2 GPUs")
42
+ def test_all_gather_parity(self) -> None:
43
+ if self.DISTRIBUTED_BACKEND == "ucc":
44
+ self.skipTest("torch_ucc does NOT support `torch.distributed._all_gather_base` as of 2022/06/15")
45
+ from torch.distributed.distributed_c10d import all_gather, _all_gather_base # NOQA
46
+
47
+ for tensor_model_parallel_world_size in range(1, self.world_size + 1):
48
+ if self.world_size % tensor_model_parallel_world_size:
49
+ continue
50
+ parallel_state.initialize_model_parallel(
51
+ tensor_model_parallel_size_=tensor_model_parallel_world_size,
52
+ )
53
+ tensor_model_parallel_rank = parallel_state.get_tensor_model_parallel_rank()
54
+ cur_tensor_model_device = torch.device(f"cuda:{tensor_model_parallel_rank}")
55
+ with torch.no_grad():
56
+ tensor = tensor_model_parallel_rank * torch.ones(
57
+ self.tensor_shape, dtype=torch.float32, device=cur_tensor_model_device)
58
+ numel = tensor.numel()
59
+ numel_gathered = tensor_model_parallel_world_size * numel
60
+ gathered = torch.empty(
61
+ torch.Size((numel_gathered,)),
62
+ device=cur_tensor_model_device,
63
+ dtype=torch.float32,
64
+ requires_grad=False,
65
+ )
66
+ chunks = [
67
+ gathered[i * numel : (i + 1) * numel]
68
+ for i in range(tensor_model_parallel_world_size)
69
+ ]
70
+ all_gather(chunks, tensor, group=parallel_state.get_tensor_model_parallel_group())
71
+
72
+ gathered_for_base = torch.empty(
73
+ torch.Size((numel_gathered,)),
74
+ device=cur_tensor_model_device,
75
+ dtype=torch.float32,
76
+ requires_grad=False,
77
+ )
78
+ _all_gather_base(
79
+ gathered_for_base,
80
+ tensor,
81
+ group=parallel_state.get_tensor_model_parallel_group(),
82
+ )
83
+
84
+ msg = f"tensor_model_parallel_world_size: {tensor_model_parallel_world_size}"
85
+ self.assertEqual(gathered, gathered_for_base, msg=msg)
86
+ parallel_state.destroy_model_parallel()
87
+
88
+ @torch.no_grad()
89
+ @unittest.skipIf(torch.cuda.device_count() < 2, "Requires >=2 GPUs")
90
+ def test_reduce_scatter_parity(self) -> None:
91
+ if self.DISTRIBUTED_BACKEND == "ucc":
92
+ self.skipTest("torch_ucc does NOT support `torch.distributed._reduce_scatter_base` as of 2022/06/15")
93
+ from torch.distributed.distributed_c10d import reduce_scatter, _reduce_scatter_base # NOQA
94
+
95
+ for tensor_model_parallel_world_size in range(2, self.world_size + 1):
96
+ if self.world_size % tensor_model_parallel_world_size:
97
+ continue
98
+ parallel_state.initialize_model_parallel(
99
+ tensor_model_parallel_size_=tensor_model_parallel_world_size,
100
+ )
101
+ tensor_model_parallel_rank = parallel_state.get_tensor_model_parallel_rank()
102
+ cur_tensor_model_device = torch.device(f"cuda:{tensor_model_parallel_rank}")
103
+ with torch.no_grad():
104
+ input = torch.cat([
105
+ i * torch.ones(self.tensor_shape, dtype=torch.float32, device=cur_tensor_model_device)
106
+ for i in range(tensor_model_parallel_world_size)
107
+ ])
108
+ input_list = [t.clone() for t in input.chunk(tensor_model_parallel_world_size)]
109
+ output = torch.empty(
110
+ self.tensor_shape,
111
+ device=cur_tensor_model_device,
112
+ dtype=torch.float32,
113
+ requires_grad=False,
114
+ )
115
+ reduce_scatter(
116
+ output, input_list,
117
+ group=parallel_state.get_tensor_model_parallel_group(),
118
+ )
119
+
120
+ output_for_base = torch.empty(
121
+ self.tensor_shape,
122
+ device=cur_tensor_model_device,
123
+ dtype=torch.float32,
124
+ requires_grad=False,
125
+ )
126
+ _reduce_scatter_base(
127
+ output_for_base,
128
+ input,
129
+ group=parallel_state.get_tensor_model_parallel_group(),
130
+ )
131
+
132
+ msg = f"tensor_model_parallel_world_size: {tensor_model_parallel_world_size}"
133
+ self.assertEqual(output, output_for_base, msg=msg)
134
+ self.assertEqual(input, torch.cat(input_list), msg=msg)
135
+ parallel_state.destroy_model_parallel()
136
+
137
+ def test_parallel_embedding(self) -> None:
138
+ for tensor_model_parallel_world_size in range(1, self.world_size + 1):
139
+ if self.world_size % tensor_model_parallel_world_size:
140
+ continue
141
+ parallel_state.initialize_model_parallel(
142
+ tensor_model_parallel_size_=tensor_model_parallel_world_size,
143
+ )
144
+ set_random_seed(self.SEED + 1)
145
+ input_tensor = torch.randint(
146
+ 0,
147
+ self.VOCAB_SIZE,
148
+ (
149
+ self.BATCH_SIZE,
150
+ self.SEQUENCE_LENGTH,
151
+ ),
152
+ device="cuda",
153
+ )
154
+ loss_weight = torch.randn(
155
+ (
156
+ self.BATCH_SIZE,
157
+ self.SEQUENCE_LENGTH,
158
+ self.HIDDEN_SIZE,
159
+ ),
160
+ device="cuda",
161
+ )
162
+
163
+ set_random_seed(self.SEED)
164
+ embedding_torch = nn.Embedding(
165
+ self.VOCAB_SIZE,
166
+ self.HIDDEN_SIZE,
167
+ ).cuda()
168
+ output_torch = embedding_torch(input_tensor)
169
+ loss_torch = torch.mul(output_torch, loss_weight).sum()
170
+ loss_torch.backward()
171
+
172
+ # N.B.(mkozuki): With affine weight initialization on GPU,
173
+ # it's super difficult to keep the consistency with nn.Embedding.
174
+ # Thus, turning on `use_cpu_initialization`.
175
+ set_random_seed(self.SEED)
176
+ embedding_vocab_parallel = layers.VocabParallelEmbedding(
177
+ self.VOCAB_SIZE,
178
+ self.HIDDEN_SIZE,
179
+ init_method=nn.init.normal_,
180
+ use_cpu_initialization=True,
181
+ ).cuda()
182
+ output_vocab_parallel = embedding_vocab_parallel(input_tensor)
183
+ loss_vocab_parallel = torch.mul(
184
+ output_vocab_parallel, loss_weight
185
+ ).sum()
186
+ loss_vocab_parallel.backward()
187
+
188
+ msg = f"tensor_model_parallel_world_size: {tensor_model_parallel_world_size}"
189
+ self.assertEqual(output_torch, output_vocab_parallel, msg=msg)
190
+ self.assertEqual(loss_torch, loss_vocab_parallel, msg=msg)
191
+
192
+ splitted_weight_torch = torch.split(
193
+ embedding_torch.weight.grad,
194
+ self.VOCAB_SIZE
195
+ // tensor_model_parallel_world_size,
196
+ 0,
197
+ )[parallel_state.get_tensor_model_parallel_rank()]
198
+ self.assertEqual(
199
+ splitted_weight_torch, embedding_vocab_parallel.weight.grad, msg=msg,
200
+ )
201
+
202
+ parallel_state.destroy_model_parallel()
203
+
204
+ def _affine_weight_init_test_impl(
205
+ self, init_device: str, is_column_parallel: bool
206
+ ) -> None:
207
+ dim = int(not is_column_parallel)
208
+ for tensor_model_parallel_world_size in range(1, self.world_size + 1):
209
+ if self.world_size % tensor_model_parallel_world_size:
210
+ continue
211
+ parallel_state.initialize_model_parallel(
212
+ tensor_model_parallel_size_=tensor_model_parallel_world_size
213
+ )
214
+ input_size: int = self.INPUT_SIZE_COEFF * tensor_model_parallel_world_size
215
+ output_size: int = self.OUTPUT_SIZE_COEFF * tensor_model_parallel_world_size
216
+
217
+ weight_shape = (
218
+ (self.OUTPUT_SIZE_COEFF, input_size)
219
+ if is_column_parallel
220
+ else (output_size, self.INPUT_SIZE_COEFF)
221
+ )
222
+ weight = torch.empty(weight_shape)
223
+ set_random_seed(self.SEED)
224
+
225
+ sharding_dim_size = (
226
+ self.OUTPUT_SIZE_COEFF
227
+ if is_column_parallel
228
+ else self.INPUT_SIZE_COEFF
229
+ )
230
+
231
+ if init_device == "cpu":
232
+ layers._initialize_affine_weight_cpu(
233
+ weight,
234
+ output_size,
235
+ input_size,
236
+ sharding_dim_size,
237
+ dim,
238
+ nn.init.normal_,
239
+ params_dtype=torch.float32,
240
+ )
241
+ else:
242
+ layers._initialize_affine_weight_gpu(
243
+ weight, torch.nn.init.normal_, dim
244
+ )
245
+ # Target
246
+ set_random_seed(self.SEED)
247
+ if init_device == "cpu":
248
+ main_weight = torch.empty(output_size, input_size)
249
+ nn.init.normal_(main_weight)
250
+ curr_weight = torch.split(main_weight, sharding_dim_size, dim=dim)[
251
+ parallel_state.get_tensor_model_parallel_rank()
252
+ ]
253
+ else:
254
+ curr_weight = torch.empty(*weight_shape)
255
+ nn.init.normal_(curr_weight)
256
+
257
+ self.assertEqual(
258
+ curr_weight, weight, msg=f"tensor_model_parallel_world_size: {tensor_model_parallel_world_size}")
259
+ parallel_state.destroy_model_parallel()
260
+
261
+ def test_affine_weight_init_column_parallel_cpu(self) -> None:
262
+ self._affine_weight_init_test_impl(init_device="cpu", is_column_parallel=True)
263
+
264
+ def test_affine_weight_init_column_parallel_gpu(self) -> None:
265
+ self._affine_weight_init_test_impl(init_device="gpu", is_column_parallel=True)
266
+
267
+ def test_affine_weight_init_row_parallel_cpu(self) -> None:
268
+ self._affine_weight_init_test_impl(init_device="cpu", is_column_parallel=False)
269
+
270
+ def test_affine_weight_init_row_parallel_gpu(self) -> None:
271
+ self._affine_weight_init_test_impl(init_device="gpu", is_column_parallel=False)
272
+
273
+ def test_row_parallel_linear(self) -> None:
274
+ self._row_parallel_linear_test_impl(False, False, False)
275
+
276
+ def test_row_parallel_linear_gradient_accumulation_fusion(self) -> None:
277
+ self._row_parallel_linear_test_impl(True, False, False)
278
+
279
+ def test_row_parallel_linear_gradient_accumulation_fusion_in_fp16(self) -> None:
280
+ self._row_parallel_linear_test_impl(True, True, False)
281
+
282
+ # fails on native ucc and torch ucc: ucc does not support reduce scatter
283
+ @unittest.skipIf(torch.cuda.device_count() < 2, "Sequence Parallel requires >=2 GPUs")
284
+ def test_row_parallel_linear_sequence_parallel(self) -> None:
285
+ self._row_parallel_linear_test_impl(False, False, True)
286
+
287
+ # TODO(mkozuki): Merge this with `_column_parallel_linear_test_impl`
288
+ # Note that `input_is_parallel` is unique to `RowParallelLinear` which could make the merge complicated.
289
+ def _row_parallel_linear_test_impl(
290
+ self,
291
+ gradient_accumulation_fusion: bool,
292
+ accumulation_in_fp16: bool,
293
+ sequence_parallel_enabled: bool,
294
+ ) -> None:
295
+ tensor_shape = (
296
+ self.SEQUENCE_LENGTH,
297
+ self.BATCH_SIZE,
298
+ self.HIDDEN_SIZE,
299
+ )
300
+ for tensor_model_parallel_world_size in range(
301
+ 1 + int(sequence_parallel_enabled), self.world_size + 1
302
+ ):
303
+ if self.world_size % tensor_model_parallel_world_size:
304
+ continue
305
+ parallel_state.initialize_model_parallel(
306
+ tensor_model_parallel_size_=tensor_model_parallel_world_size,
307
+ )
308
+ set_random_seed(self.SEED)
309
+
310
+ linear = layers.RowParallelLinear(
311
+ self.HIDDEN_SIZE,
312
+ self.HIDDEN_SIZE,
313
+ keep_master_weight_for_test=True,
314
+ params_dtype=torch.float32,
315
+ use_cpu_initialization=True,
316
+ gradient_accumulation_fusion=gradient_accumulation_fusion,
317
+ accumulation_in_fp16=accumulation_in_fp16,
318
+ sequence_parallel_enabled=sequence_parallel_enabled,
319
+ # n.b.(mkozuki): RowParallelLinear is constructed with `input_is_parallel=True`
320
+ # by default, e.g. https://github.com/NVIDIA/NeMo/blob/782b4e1652aaa43c8be390d9\
321
+ # db0dc89544afa080/nemo/collections/nlp/modules/common/megatron/transformer.py#L204
322
+ input_is_parallel=True,
323
+ ).cuda()
324
+ if accumulation_in_fp16:
325
+ linear = linear.half()
326
+ # Simulate the situation where fusion of weight grad calculation and gradient accumulation is enabled.
327
+ if gradient_accumulation_fusion:
328
+ with torch.no_grad():
329
+ linear.weight.main_grad = torch.zeros_like(linear.weight)
330
+
331
+ msg = f"tensor_model_parallel_world_size: {tensor_model_parallel_world_size}"
332
+
333
+ with torch.no_grad():
334
+ orig_input_tensor = torch.randn(tensor_shape, requires_grad=True, device="cuda")
335
+ orig_loss_weight = torch.randn(tensor_shape, device="cuda")
336
+ input_tensor = orig_input_tensor.chunk(
337
+ chunks=tensor_model_parallel_world_size,
338
+ dim=2,
339
+ )[parallel_state.get_tensor_model_parallel_rank()].contiguous()
340
+ if sequence_parallel_enabled:
341
+ loss_weight = orig_loss_weight.chunk(
342
+ chunks=tensor_model_parallel_world_size,
343
+ dim=0,
344
+ )[parallel_state.get_tensor_model_parallel_rank()]
345
+ else:
346
+ loss_weight = orig_loss_weight
347
+ if accumulation_in_fp16:
348
+ orig_input_tensor = orig_input_tensor.half()
349
+ input_tensor = input_tensor.half()
350
+ loss_weight = loss_weight.half()
351
+ input_tensor.requires_grad_()
352
+ output, _ = linear(input_tensor)
353
+ loss = torch.mul(output, loss_weight).sum()
354
+ loss.backward()
355
+ self.assertIsNotNone(input_tensor.grad, msg=msg)
356
+
357
+ ref_linear = nn.Linear(
358
+ in_features=self.HIDDEN_SIZE,
359
+ out_features=self.HIDDEN_SIZE,
360
+ bias=False,
361
+ device="cuda",
362
+ )
363
+ with torch.no_grad():
364
+ dldy = orig_loss_weight.clone()
365
+ x = orig_input_tensor.clone()
366
+ ref_linear.weight.copy_(linear.master_weight)
367
+ if accumulation_in_fp16:
368
+ ref_linear = ref_linear.half()
369
+ x.requires_grad_()
370
+ expected_output = ref_linear(x)
371
+ expected_loss = torch.mul(expected_output, dldy).sum()
372
+ expected_loss.backward()
373
+
374
+ if not accumulation_in_fp16:
375
+ if sequence_parallel_enabled:
376
+ self.assertEqual(
377
+ x=output,
378
+ y=expected_output.chunk(
379
+ chunks=tensor_model_parallel_world_size,
380
+ dim=0,
381
+ )[parallel_state.get_tensor_model_parallel_rank()],
382
+ msg=msg,
383
+ )
384
+ else:
385
+ self.assertEqual(
386
+ x=output,
387
+ y=expected_output,
388
+ msg=msg,
389
+ )
390
+
391
+ grad_attr_name = "main_grad" if gradient_accumulation_fusion else "grad"
392
+ # NOTE(mkozuki): Numerical errors seems to be enlarged by tensor model parallel.
393
+ if tensor_model_parallel_world_size == 1:
394
+ self.assertEqual(
395
+ x=getattr(linear.weight, grad_attr_name),
396
+ y=ref_linear.weight.grad.chunk(
397
+ chunks=tensor_model_parallel_world_size,
398
+ dim=0,
399
+ )[parallel_state.get_tensor_model_parallel_rank()],
400
+ msg=msg,
401
+ )
402
+
403
+ parallel_state.destroy_model_parallel()
404
+
405
+ def test_column_parallel_linear(self):
406
+ self._column_parallel_linear_test_impl(False, False, False, False)
407
+
408
+ def test_column_parallel_linear_async(self):
409
+ self._column_parallel_linear_test_impl(True, False, False, False)
410
+
411
+ def test_column_parallel_linear_gradient_accumulation_fusion(self):
412
+ self._column_parallel_linear_test_impl(False, True, False, False)
413
+
414
+ def test_column_parallel_linear_gradient_accumulation_fusion_in_fp16(self):
415
+ self._column_parallel_linear_test_impl(False, True, True, False)
416
+
417
+ def test_column_parallel_linear_sequence_parallel(self):
418
+ if self.DISTRIBUTED_BACKEND == "ucc":
419
+ self.skipTest("Backward's reduce_scatter fails. as of 2022/06/15")
420
+ self._column_parallel_linear_test_impl(False, False, False, True)
421
+
422
+ @unittest.skipIf(torch.cuda.device_count() < 2, "Sequence Parallel requires >= 2 GPUs")
423
+ def test_column_parallel_linear_exception(self):
424
+ with self.assertRaisesRegex(
425
+ RuntimeError,
426
+ "`async_tensor_model_parallel_allreduce` and `sequence_parallel_enabled` cannot be enabled at the same time.",
427
+ ):
428
+ self._column_parallel_linear_test_impl(True, False, False, True)
429
+
430
+ def _column_parallel_linear_test_impl(
431
+ self,
432
+ async_tensor_model_parallel_allreduce: bool,
433
+ gradient_accumulation_fusion: bool,
434
+ accumulation_in_fp16: bool,
435
+ sequence_parallel_enabled: bool,
436
+ ):
437
+ for tensor_model_parallel_world_size in range(1, self.world_size + 1):
438
+ if async_tensor_model_parallel_allreduce and sequence_parallel_enabled:
439
+ if tensor_model_parallel_world_size == 1:
440
+ continue
441
+ if self.world_size % tensor_model_parallel_world_size:
442
+ continue
443
+ msg = f"tensor_model_parallel_world_size: {tensor_model_parallel_world_size}"
444
+ parallel_state.initialize_model_parallel(
445
+ tensor_model_parallel_size_=tensor_model_parallel_world_size,
446
+ )
447
+
448
+ input_tensor_shape = self.tensor_shape
449
+ expected_output_shape = self.tensor_shape
450
+ # When sequence parallel, `gather_output` is disabled, i.e.,
451
+ # output of matmul isn't gathered in dimension of feature/hidden (last dim).
452
+ if sequence_parallel_enabled:
453
+ expected_output_shape[-1] //= tensor_model_parallel_world_size
454
+
455
+ # tensor's shape is [sequence length, batch size, hidden size]
456
+ set_random_seed(self.SEED)
457
+ linear = layers.ColumnParallelLinear(
458
+ self.HIDDEN_SIZE,
459
+ self.HIDDEN_SIZE,
460
+ bias=False,
461
+ keep_master_weight_for_test=True,
462
+ params_dtype=torch.float32,
463
+ use_cpu_initialization=True,
464
+ gather_output=not sequence_parallel_enabled,
465
+ no_async_tensor_model_parallel_allreduce=not async_tensor_model_parallel_allreduce,
466
+ gradient_accumulation_fusion=gradient_accumulation_fusion,
467
+ accumulation_in_fp16=accumulation_in_fp16,
468
+ sequence_parallel_enabled=sequence_parallel_enabled,
469
+ ).cuda()
470
+ if accumulation_in_fp16:
471
+ linear = linear.half()
472
+
473
+ # Simulate the situation where fusion of weight grad calculation and gradient accumulation happens.
474
+ if gradient_accumulation_fusion:
475
+ with torch.no_grad():
476
+ linear.weight.main_grad = torch.zeros_like(linear.weight)
477
+
478
+ orig_input_tensor = torch.randn(input_tensor_shape, device="cuda", requires_grad=True)
479
+ if accumulation_in_fp16:
480
+ orig_input_tensor = orig_input_tensor.half()
481
+ if sequence_parallel_enabled:
482
+ input_tensor = list(
483
+ orig_input_tensor.chunk(tensor_model_parallel_world_size, dim=0)
484
+ )[parallel_state.get_tensor_model_parallel_rank()]
485
+ else:
486
+ input_tensor = orig_input_tensor
487
+ output, _ = linear(input_tensor)
488
+ # The order of dimension is expected to be (sequence, batch, hidden)
489
+ self.assertEqual(output.shape, expected_output_shape, msg=msg)
490
+
491
+ orig_loss_weight = torch.randn(input_tensor_shape, device="cuda")
492
+ if accumulation_in_fp16:
493
+ orig_loss_weight = orig_loss_weight.half()
494
+ if sequence_parallel_enabled:
495
+ loss_weight = orig_loss_weight.chunk(
496
+ tensor_model_parallel_world_size, dim=2,
497
+ )[parallel_state.get_tensor_model_parallel_rank()]
498
+ else:
499
+ loss_weight = orig_loss_weight
500
+ loss = torch.mul(output, loss_weight).sum()
501
+ loss.backward()
502
+
503
+ with torch.no_grad():
504
+ dldy = orig_loss_weight.clone()
505
+ x = orig_input_tensor.clone()
506
+ ref_linear = nn.Linear(
507
+ in_features=self.HIDDEN_SIZE,
508
+ out_features=self.HIDDEN_SIZE,
509
+ bias=False,
510
+ device="cuda",
511
+ )
512
+ if accumulation_in_fp16:
513
+ ref_linear = ref_linear.half()
514
+ # NOTE(mkozuki): `master_weight` is available because `keep_master_weight_for_test` is set.
515
+ ref_linear.weight.copy_(linear.master_weight)
516
+ x.requires_grad_()
517
+ expected_output = ref_linear(x)
518
+ if sequence_parallel_enabled:
519
+ chunk = expected_output.chunk(
520
+ tensor_model_parallel_world_size,
521
+ dim=2,
522
+ )[parallel_state.get_tensor_model_parallel_rank()]
523
+ self.assertEqual(
524
+ x=output,
525
+ y=chunk,
526
+ msg=msg,
527
+ )
528
+ else:
529
+ self.assertEqual(
530
+ x=output,
531
+ y=expected_output,
532
+ msg=msg,
533
+ )
534
+
535
+ expected_loss = torch.mul(expected_output, dldy).sum()
536
+ expected_loss.backward()
537
+ grad_attr_name = "main_grad" if gradient_accumulation_fusion else "grad"
538
+ # NOTE(mkozuki): Numerical errors seems to be enlarged by tensor model parallel.
539
+ if tensor_model_parallel_world_size == 1:
540
+ self.assertEqual(
541
+ x=getattr(linear.weight, grad_attr_name),
542
+ y=ref_linear.weight.grad.chunk(
543
+ chunks=tensor_model_parallel_world_size,
544
+ dim=0,
545
+ )[parallel_state.get_tensor_model_parallel_rank()],
546
+ msg=msg,
547
+ )
548
+
549
+ parallel_state.destroy_model_parallel()
550
+
551
+
552
+ class NcclTensorParallelLayerTest(TensorParallelLayerTestBase, NcclDistributedTestBase):
553
+ pass
554
+
555
+
556
+ class UccTensorParallelLayerTest(TensorParallelLayerTestBase, UccDistributedTestBase):
557
+ pass
558
+
559
+
560
+ if __name__ == "__main__":
561
+ common_utils.run_tests()