forked from microsoft/SuperScaler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_diff.patch
5445 lines (5445 loc) · 233 KB
/
base_diff.patch
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --color -r runtime/megatron/arguments.py ../Megatron-LM-base/megatron/arguments.py
2,9d1
< # Copyright (c) Microsoft Corporation.
< # Licensed under the MIT License.
<
< # The file has been adapted from the following Megatron-LM file:
< # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/arguments.py
< # Git commit hash: 42c1cf4279acea5a554500dcb552211f44cbec45
< # We retain the following copyright from the original files:
<
27,28d18
< import torch
< import json
30c20,21
< DEBUG_FIX_WEIGHT = os.environ.get("DEBUG_FIX_WEIGHT", '0') == '1'
---
>
> import torch
54,57d44
< # Aceso arguments
< parser = _add_flexpipe_args(parser)
< parser = _add_profiler_args(parser)
<
71,128c58,75
<
< if args.prof_tp_size is not None:
< args.global_batch_size = 1
< args.micro_batch_size = 1
< args.num_ops_in_each_stage = [1]
< args.virtual_pipeline_model_parallel_size = 1
< args.model_parallel_size_of_each_op = [[args.prof_tp_size]]
< args.data_parallel_size_of_each_op = [[1]]
< args.model_name = ""
< args.resharding_stages = [True]
<
< if len(args.prof_repeat_times) > 1:
< assert args.prof_repeat_threshold is not None, "when args.prof_repeat_times is a list, a threshold is required."
< _print_args(args)
< return args
< else:
< assert args.flexpipe_config is not None, "An Aceso config should be provided."
< args.log_name = args.flexpipe_config.split("/")[-1].split(".json")[0]
<
< with open(args.flexpipe_config, "r") as f:
< config_dict = json.load(f)
<
< args.model_name = config_dict["model_name"]
< args.global_batch_size = config_dict["global_batch_size"]
< args.micro_batch_size = config_dict["micro_batch_size"]
< args.num_layers = config_dict["num_layers"]
<
< if args.model_name in ["gpt"]:
< args.num_attention_heads = config_dict["num_attention_heads"]
< args.hidden_size = config_dict["hidden_size"]
< args.max_position_embeddings = config_dict["max_position_embeddings"]
< args.seq_length = config_dict["seq_length"]
< elif args.model_name in ["resnet"]:
< args.in_channels = config_dict["in_channels"]
< args.width_factor = config_dict["width_factor"]
< elif args.model_name in ["t5"]:
< args.encoder_seq_length = config_dict["encoder_seq_length"]
< args.decoder_seq_length = config_dict["decoder_seq_length"]
< args.seq_length = config_dict["encoder_seq_length"]
< args.max_position_embeddings = config_dict["max_position_embeddings"]
< args.num_attention_heads = config_dict["num_attention_heads"]
< args.kv_channels = config_dict["kv_channels"]
< args.hidden_size = config_dict["hidden_size"]
< args.ffn_hidden_size = config_dict["ffn_hidden_size"]
<
< args.num_ops_in_each_stage = config_dict["num_ops_in_each_stage"]
< args.num_gpus = config_dict["num_gpus"]
< args.num_stages = config_dict["num_stages"]
< args.algo_of_each_op = config_dict["algo_of_each_op"]
< args.model_parallel_size_of_each_op = config_dict["model_parallel_size_of_each_op"]
< args.data_parallel_size_of_each_op = config_dict["data_parallel_size_of_each_op"]
< args.recompute_ops = config_dict["recompute_ops"]
< args.resharding_stages = config_dict["resharding_stages"]
< args.checkpoint_activations = config_dict["checkpoint_activations"]
<
< assert args.world_size == sum(args.num_gpus), \
< 'number of GPUs should be equal to sum(mp_size * dp_size)'
<
---
> # Tensor model parallel size.
> args.tensor_model_parallel_size = min(
> args.tensor_model_parallel_size, args.world_size)
> assert args.world_size % args.tensor_model_parallel_size == 0, 'world size'\
> ' ({}) is not divisible by tensor model parallel size ({})'.format(
> args.world_size, args.tensor_model_parallel_size)
> # Pipeline model parallel size.
> args.pipeline_model_parallel_size = min(
> args.pipeline_model_parallel_size,
> (args.world_size // args.tensor_model_parallel_size))
> # Checks.
> model_parallel_size = args.pipeline_model_parallel_size * \
> args.tensor_model_parallel_size
> assert args.world_size % model_parallel_size == 0, 'world size is not'\
> ' divisible by tensor parallel size ({}) times pipeline parallel ' \
> 'size ({})'.format(args.world_size, args.tensor_model_parallel_size,
> args.pipeline_model_parallel_size)
> args.data_parallel_size = args.world_size // model_parallel_size
130,137c77,93
< print('[FlexPipe] using world size: {}, data-parallel-size: {}, '
< 'tensor-model-parallel size: {}, '
< 'pipeline-model-parallel size: {} '
< 'interleave-factor: {}'.format(
< args.world_size, args.data_parallel_size_of_each_op,
< args.model_parallel_size_of_each_op,
< args.pipeline_model_parallel_size,
< args.interleave_factor), flush=True)
---
> print('using world size: {}, data-parallel-size: {}, '
> 'tensor-model-parallel size: {}, '
> 'pipeline-model-parallel size: {} '.format(
> args.world_size, args.data_parallel_size,
> args.tensor_model_parallel_size,
> args.pipeline_model_parallel_size), flush=True)
>
> # Deprecated arguments
> assert args.batch_size is None, '--batch-size argument is no longer ' \
> 'valid, use --micro-batch-size instead'
> del args.batch_size
> assert args.warmup is None, '--warmup argument is no longer valid, use ' \
> '--lr-warmup-fraction instead'
> del args.warmup
> assert args.model_parallel_size is None, '--model-parallel-size is no ' \
> 'longer valid, use --tensor-model-parallel-size instead'
> del args.model_parallel_size
153a110
> assert args.micro_batch_size is not None
155,162c112,129
< dp_size_list = []
< for i in range(args.num_stages):
< dp_size_list += args.data_parallel_size_of_each_op[i]
< for i in range(len(dp_size_list)):
< assert args.micro_batch_size % dp_size_list[i] == 0
< assert args.global_batch_size % args.micro_batch_size == 0
<
< args.virtual_pipeline_model_parallel_size = args.interleave_factor
---
> if args.global_batch_size is None:
> args.global_batch_size = args.micro_batch_size * args.data_parallel_size
> if args.rank == 0:
> print('setting global batch size to {}'.format(
> args.global_batch_size), flush=True)
> assert args.global_batch_size > 0
> if args.num_layers_per_virtual_pipeline_stage is not None:
> assert args.pipeline_model_parallel_size > 2, \
> 'pipeline-model-parallel size should be greater than 2 with ' \
> 'interleaved schedule'
> assert args.num_layers % args.num_layers_per_virtual_pipeline_stage == 0, \
> 'number of layers is not divisible by number of layers per virtual ' \
> 'pipeline stage'
> args.virtual_pipeline_model_parallel_size = \
> (args.num_layers // args.pipeline_model_parallel_size) // \
> args.num_layers_per_virtual_pipeline_stage
> else:
> args.virtual_pipeline_model_parallel_size = None
227a195,200
> # Check required arguments.
> required_args = ['num_layers', 'hidden_size', 'num_attention_heads',
> 'max_position_embeddings']
> for req_arg in required_args:
> _check_arg_is_not_none(args, req_arg)
>
229,242c202,214
< if args.model_name in ["gpt"]:
< if args.ffn_hidden_size is None:
< args.ffn_hidden_size = 4 * args.hidden_size
<
< if args.kv_channels is None:
< assert args.hidden_size % args.num_attention_heads == 0
< args.kv_channels = args.hidden_size // args.num_attention_heads
<
< if args.seq_length is not None:
< assert args.encoder_seq_length is None
< args.encoder_seq_length = args.seq_length
< else:
< assert args.encoder_seq_length is not None
< args.seq_length = args.encoder_seq_length
---
> if args.ffn_hidden_size is None:
> args.ffn_hidden_size = 4 * args.hidden_size
>
> if args.kv_channels is None:
> assert args.hidden_size % args.num_attention_heads == 0
> args.kv_channels = args.hidden_size // args.num_attention_heads
>
> if args.seq_length is not None:
> assert args.encoder_seq_length is None
> args.encoder_seq_length = args.seq_length
> else:
> assert args.encoder_seq_length is not None
> args.seq_length = args.encoder_seq_length
244,247c216,219
< if args.seq_length is not None:
< assert args.max_position_embeddings >= args.seq_length
< if args.decoder_seq_length is not None:
< assert args.max_position_embeddings >= args.decoder_seq_length
---
> if args.seq_length is not None:
> assert args.max_position_embeddings >= args.seq_length
> if args.decoder_seq_length is not None:
> assert args.max_position_embeddings >= args.decoder_seq_length
264,268d235
< # set dropout = 0 when DEBUG_FIX_WEIGHT
< if DEBUG_FIX_WEIGHT:
< args.attention_dropout = 0
< args.hidden_dropout = 0
<
294a262,265
> group.add_argument('--num-layers', type=int, default=None,
> help='Number of transformer layers.')
> group.add_argument('--hidden-size', type=int, default=None,
> help='Tansformer hidden size.')
297a269,270
> group.add_argument('--num-attention-heads', type=int, default=None,
> help='Number of transformer attention heads.')
302a276,278
> group.add_argument('--max-position-embeddings', type=int, default=None,
> help='Maximum number of position embeddings to use. '
> 'This is the size of position embedding.')
387a364,367
> group.add_argument('--micro-batch-size', type=int, default=None,
> help='Batch size per model instance (local batch size). '
> 'Global batch size is local batch size times data '
> 'parallel size times number of micro batches.')
390a371,377
> group.add_argument('--global-batch-size', type=int, default=None,
> help='Training batch size. If set, it should be a '
> 'multiple of micro-batch-size times data-parallel-size. '
> 'If this value is None, then '
> 'use micro-batch-size * data-parallel-size as the '
> 'global batch size. This choice will result in 1 for '
> 'number of micro-batches.')
609,615d595
<
< group.add_argument('--empty-unused-memory-level', default=0, type=int,
< choices=[0, 1, 2],
< help='Call torch.cuda.empty_cache() each iteration '
< '(training and eval), to reduce fragmentation.'
< '0=off, 1=moderate, 2=aggressive.')
<
651a632,633
> group.add_argument('--seq-length', type=int, default=None,
> help='Maximum sequence length to process.')
773,805d754
<
< def _add_flexpipe_args(parser):
< group = parser.add_argument_group(title='flexpipe')
< group.add_argument('--flexpipe-config', type=str, default=None,
< help='Path to flexpipe configuration.')
< group.add_argument('--interleave-factor', type=int, default=1,
< help='# of interleaved virtual stages in one physical stage.')
< group.add_argument('--checkpoint-stages', nargs='+', default=[],
< help="An array of 1/0 to indicate if this stage will be activation checkpointed.")
< group.add_argument('--log-path', type=str, default="./", help='')
< return parser
<
< def _add_profiler_args(parser):
< group = parser.add_argument_group(title='flexpipe_profiler')
<
< group.add_argument('--prof-tp-size', type=int, default=None, help='Profiler tp size.')
< group.add_argument('--prof-path', type=str, default=None, help='')
< group.add_argument('--prof-cache-file', type=str, default=None, help='')
< group.add_argument('--prof-model-name', type=str, default='all', help='')
< group.add_argument('--prof-model-size', type=str, default='all', help='')
< group.add_argument('--prof-time-only', action='store_true', help='')
< group.add_argument('--prof-memory-only', action='store_true', help='')
< group.add_argument('--prof-warmup-times', type=int, default=20, help='')
< group.add_argument('--prof-repeat-times', nargs='+', type=int, default=[50], help='')
< group.add_argument('--prof-warmup-threshold', type=int, default=None, help='')
< group.add_argument('--prof-repeat-threshold', type=int, default=None, help='')
< group.add_argument('--prof-skip-running', action='store_true', help='')
< group.add_argument('--prof-num-nodes', type=int, default=None, help='')
< group.add_argument('--prof-node-rank', type=int, default=None, help='')
< group.add_argument('--prof-ref-data', type=str, default=None, help='')
< group.add_argument('--prof-mbs-list', nargs='+', type=int, default=None, help='')
<
< return parser
\ No newline at end of file
diff --color -r runtime/megatron/data/dataset_utils.py ../Megatron-LM-base/megatron/data/dataset_utils.py
705,709c705,707
<
< ## Temporarily bypass the check in Aceso
< # assert counts[0].item() == (
< # torch.distributed.get_world_size() //
< # torch.distributed.get_world_size(group=mpu.get_tensor_model_parallel_group()))
---
> assert counts[0].item() == (
> torch.distributed.get_world_size() //
> torch.distributed.get_world_size(group=mpu.get_tensor_model_parallel_group()))
diff --color -r runtime/megatron/data/gpt_dataset.py ../Megatron-LM-base/megatron/data/gpt_dataset.py
302,306c302,304
<
< ## Temporarily bypass the check in Aceso
< # assert counts[0].item() == (
< # torch.distributed.get_world_size() //
< # torch.distributed.get_world_size(group=mpu.get_tensor_model_parallel_group()))
---
> assert counts[0].item() == (
> torch.distributed.get_world_size() //
> torch.distributed.get_world_size(group=mpu.get_tensor_model_parallel_group()))
diff --color -r runtime/megatron/fused_kernels/__init__.py ../Megatron-LM-base/megatron/fused_kernels/__init__.py
81,86d80
< # Softmax
< sources=[srcpath / 'scaled_softmax.cpp',
< srcpath / 'scaled_softmax_cuda.cu']
< scaled_softmax_cuda = _cpp_extention_load_helper(
< "scaled_softmax_cuda", sources, extra_cuda_flags)
<
diff --color -r runtime/megatron/fused_kernels/layer_norm_cuda_kernel.cu ../Megatron-LM-base/megatron/fused_kernels/layer_norm_cuda_kernel.cu
24c24
< #include "ATen/cuda/DeviceUtils.cuh"
---
> #include <THC/THCDeviceUtils.cuh>
332d331
< __syncthreads();
648,649d646
< // prevent race where buf is written again before reads are done
< __syncthreads();
diff --color -r runtime/megatron/fused_kernels/scaled_masked_softmax.cpp ../Megatron-LM-base/megatron/fused_kernels/scaled_masked_softmax.cpp
35,40d34
< int get_batch_per_block_cuda(
< int query_seq_len,
< int key_seq_len,
< int batches,
< int attn_heads);
<
72,79d65
< int get_batch_per_block(
< int query_seq_len,
< int key_seq_len,
< int batches,
< int attn_heads) {
< return get_batch_per_block_cuda(query_seq_len, key_seq_len, batches, attn_heads);
< }
<
88,89c74
<
< m.def("backward",
---
> m.def("backward",
92,96d76
<
< m.def("get_batch_per_block",
< &multihead_attn::fused_softmax::scaled_masked_softmax::get_batch_per_block,
< "Return Batch per block size."
< );
diff --color -r runtime/megatron/fused_kernels/scaled_masked_softmax_cuda.cu ../Megatron-LM-base/megatron/fused_kernels/scaled_masked_softmax_cuda.cu
31,35d30
< int get_batch_per_block_cuda(int query_seq_len, int key_seq_len, int batches, int attn_heads){
< return get_batch_per_block(query_seq_len, key_seq_len, batches, attn_heads);
< }
<
<
47c42
< TORCH_INTERNAL_ASSERT(key_seq_len <= 4096);
---
> TORCH_INTERNAL_ASSERT(key_seq_len <= 2048);
diff --color -r runtime/megatron/fused_kernels/scaled_masked_softmax.h ../Megatron-LM-base/megatron/fused_kernels/scaled_masked_softmax.h
93,203d92
<
< /*
< * Extended softmax (from native aten pytorch) with following additional features
< * 1) input scaling
< */
< template <typename input_t, typename output_t, typename acc_t, int log2_elements>
< __global__ void scaled_softmax_warp_forward(
< output_t *dst,
< const input_t *src,
< const acc_t scale,
< int micro_batch_size,
< int element_count)
< {
< // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and
< // warp_size of method warp_softmax_forward_kernel.
< constexpr int next_power_of_two = 1 << log2_elements;
< constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE;
< constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE;
< constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1;
< constexpr int ELEMENTS_PER_LDG_STG = (WARP_ITERATIONS < 4) ? 1 : 4;
<
< // blockDim/threadIdx = (WARP_SIZE, WARPS_PER_BLOCK, )
< // gridDim/blockIdx = (seq_len, attn_heads, batches)
< int first_batch = (blockDim.y * (blockIdx.x + gridDim.x * (blockIdx.y + gridDim.y * blockIdx.z))+ threadIdx.y) * WARP_BATCH;
<
< // micro_batch_size might not be a multiple of WARP_BATCH. Check how
< // many batches have to computed within this WARP.
< int local_batches = micro_batch_size - first_batch;
< if (local_batches > WARP_BATCH)
< local_batches = WARP_BATCH;
<
< // there might be multiple batches per warp. compute the index within the batch
< int local_idx = threadIdx.x;
<
< src += first_batch * element_count + ELEMENTS_PER_LDG_STG * local_idx;
< dst += first_batch * element_count + ELEMENTS_PER_LDG_STG * local_idx;
<
< // load data from global memory
< acc_t elements[WARP_BATCH][WARP_ITERATIONS];
< input_t temp_data[ELEMENTS_PER_LDG_STG];
< #pragma unroll
< for (int i = 0; i < WARP_BATCH; ++i) {
< int batch_element_count = (i >= local_batches) ? 0 : element_count;
<
< #pragma unroll
< for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) {
< int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE;
<
< if (element_index < batch_element_count) {
< int itr_idx = i*element_count+it*WARP_SIZE;
< copy_vector<input_t, ELEMENTS_PER_LDG_STG>(temp_data, src + itr_idx);
<
< #pragma unroll
< for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) {
< elements[i][it + element] = (acc_t)temp_data[element] * scale;
< }
< } else {
< #pragma unroll
< for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) {
< elements[i][it + element] = -std::numeric_limits<acc_t>::infinity();
< }
< }
< }
< }
<
< // compute max_value
< acc_t max_value[WARP_BATCH];
< #pragma unroll
< for (int i = 0; i < WARP_BATCH; ++i) {
< max_value[i] = elements[i][0];
< #pragma unroll
< for (int it = 1; it < WARP_ITERATIONS; ++it) {
< max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it];
< }
< }
< warp_reduce<acc_t, WARP_BATCH, WARP_SIZE, Max>(max_value);
<
< acc_t sum[WARP_BATCH] { 0.0f };
< #pragma unroll
< for (int i = 0; i < WARP_BATCH; ++i) {
< #pragma unroll
< for (int it = 0; it < WARP_ITERATIONS; ++it) {
< elements[i][it] = std::exp((elements[i][it] - max_value[i]));
< sum[i] += elements[i][it];
< }
< }
< warp_reduce<acc_t, WARP_BATCH, WARP_SIZE, Add>(sum);
<
< // store result
< output_t out[ELEMENTS_PER_LDG_STG];
< #pragma unroll
< for (int i = 0; i < WARP_BATCH; ++i) {
< if (i >= local_batches)
< break;
< #pragma unroll
< for (int it = 0; it < WARP_ITERATIONS; it+=ELEMENTS_PER_LDG_STG) {
< int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE;
< if (element_index < element_count) {
< #pragma unroll
< for (int element = 0; element < ELEMENTS_PER_LDG_STG; ++element) {
< out[element] = elements[i][it + element] / sum[i];
< }
< copy_vector<output_t, ELEMENTS_PER_LDG_STG>(dst + i * element_count + it * WARP_SIZE, out);
< } else {
< break;
< }
< }
< }
< }
<
<
225c114
< constexpr int ELEMENTS_PER_LDG_STG = (WARP_ITERATIONS < 4) ? 1 : 4;
---
> constexpr int ELEMENTS_PER_LDG_STG = 4;
344c233
< constexpr int ELEMENTS_PER_LDG_STG = (WARP_ITERATIONS < 4) ? 1 : 4;
---
> constexpr int ELEMENTS_PER_LDG_STG = 4;
424,465d312
< } // end of anonymous namespace
<
< int get_batch_per_block(int query_seq_len, int key_seq_len, int batches, int attn_heads){
< int log2_elements = log2_ceil(key_seq_len);
< const int next_power_of_two = 1 << log2_elements;
<
< int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE;
< int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1;
<
< constexpr int threads_per_block = 128;
< int warps_per_block = (threads_per_block / warp_size);
< int batches_per_block = warps_per_block * batches_per_warp;
<
< return batches_per_block;
< }
<
< template<typename input_t, typename output_t, typename acc_t>
< void dispatch_scaled_softmax_forward(
< output_t *dst,
< const input_t *src,
< const input_t scale,
< int query_seq_len,
< int key_seq_len,
< int batches,
< int attn_heads)
< {
< TORCH_INTERNAL_ASSERT(key_seq_len >= 0 && key_seq_len <= 4096 );
< if (key_seq_len == 0) {
< return;
< } else {
< int log2_elements = log2_ceil(key_seq_len);
< const int next_power_of_two = 1 << log2_elements;
< int batch_count = batches * attn_heads * query_seq_len;
<
< // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_forward.
< int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE;
<
< // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_forward.
< int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1;
<
< // use 128 threads per block to maximimize gpu utilization
< constexpr int threads_per_block = 128;
467,530c314
< int warps_per_block = (threads_per_block / warp_size);
< int batches_per_block = warps_per_block * batches_per_warp;
< TORCH_INTERNAL_ASSERT(query_seq_len%batches_per_block == 0);
< dim3 blocks(query_seq_len/batches_per_block, attn_heads, batches);
< dim3 threads(warp_size, warps_per_block, 1);
< // Launch code would be more elegant if C++ supported FOR CONSTEXPR
< switch (log2_elements) {
< case 0: // 1
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 0>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 1: // 2
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 1>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 2: // 4
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 2>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 3: // 8
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 3>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 4: // 16
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 4>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 5: // 32
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 5>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 6: // 64
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 6>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 7: // 128
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 7>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 8: // 256
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 8>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 9: // 512
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 9>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 10: // 1024
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 10>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 11: // 2048
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 11>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< case 12: // 4096
< scaled_softmax_warp_forward<input_t, output_t, acc_t, 12>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, scale, batch_count, key_seq_len);
< break;
< default:
< break;
< }
< }
< }
---
> } // end of anonymous namespace
544c328
< TORCH_INTERNAL_ASSERT(key_seq_len >= 0 && key_seq_len <= 4096 );
---
> TORCH_INTERNAL_ASSERT(key_seq_len >= 0 && key_seq_len <= 2048 );
616,619d399
< case 12: // 4096
< scaled_masked_softmax_warp_forward<input_t, output_t, acc_t, 12>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(dst, src, mask, scale, batch_count, key_seq_len, pad_batches);
< break;
637c417
< TORCH_INTERNAL_ASSERT( key_seq_len >= 0 && key_seq_len <= 4096 );
---
> TORCH_INTERNAL_ASSERT( key_seq_len >= 0 && key_seq_len <= 2048 );
708,712d487
< case 12: // 4096
< scaled_masked_softmax_warp_backward<input_t, output_t, acc_t, 12>
< <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(grad_input, grad, output, scale, batch_count, key_seq_len);
< break;
<
Only in runtime/megatron/fused_kernels: scaled_softmax.cpp
Only in runtime/megatron/fused_kernels: scaled_softmax_cuda.cu
diff --color -r runtime/megatron/fused_kernels/scaled_upper_triang_masked_softmax.h ../Megatron-LM-base/megatron/fused_kernels/scaled_upper_triang_masked_softmax.h
128c128
< constexpr int ELEMENTS_PER_LDG_STG = (WARP_ITERATIONS < 4) ? 1 : 4;
---
> constexpr int ELEMENTS_PER_LDG_STG = 4;
248c248
< constexpr int ELEMENTS_PER_LDG_STG = (WARP_ITERATIONS < 4) ? 1 : 4;
---
> constexpr int ELEMENTS_PER_LDG_STG = 4;
364d363
<
455d453
<
Only in runtime/megatron/fused_kernels: tests
diff --color -r runtime/megatron/global_vars.py ../Megatron-LM-base/megatron/global_vars.py
2,9d1
< # Copyright (c) Microsoft Corporation.
< # Licensed under the MIT License.
<
< # The file has been adapted from the following Megatron-LM file:
< # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/global_vars.py
< # Git commit hash: 42c1cf4279acea5a554500dcb552211f44cbec45
< # We retain the following copyright from the original files:
<
43d34
< PROFILING = os.environ.get("PROFILING", '1') == '1'
190a182
>
199d190
< self.logged_times = 0
203,219c194
< if PROFILING:
< assert not self.started_, f"{self.name_} timer has already been started"
< torch.cuda.synchronize()
< self.start_time = time.time()
< self.started_ = True
<
< def stop(self):
< """Stop the timer."""
< if PROFILING:
< assert self.started_, 'timer is not started'
< torch.cuda.synchronize()
< self.elapsed_ += (time.time() - self.start_time)
< self.started_ = False
<
< def start_v2(self):
< """Start the timer."""
< assert not self.started_, f"{self.name_} timer has already been started"
---
> assert not self.started_, 'timer has already been started'
224c199
< def stop_v2(self):
---
> def stop(self):
226c201
< assert self.started_, f'{self.name_} timer is not started'
---
> assert self.started_, 'timer is not started'
229,230c204
< self.started_ = False
< self.logged_times += 1
---
> self.started_ = False
236d209
< self.logged_times = 0
278,282d250
<
< from megatron import mpu
< from megatron.utils import report_memory
< from megatron.utils import debug_mem_report
<
284,287c252
< time_to_csv = [[],[]]
< string = f'\n==> Time (ms) | [stage {mpu.get_pipeline_model_parallel_rank()}, virtual {mpu.get_virtual_pipeline_model_parallel_rank()}, rank {torch.distributed.get_rank()}]'
< string_ops = f'\n==> OP Time (us) | [stage {mpu.get_pipeline_model_parallel_rank()}, virtual {mpu.get_virtual_pipeline_model_parallel_rank()}, rank {torch.distributed.get_rank()}]'
< string_mem, mem_to_csv = report_memory(f"\n==> Memory | [stage {mpu.get_pipeline_model_parallel_rank()}, virtual {mpu.get_virtual_pipeline_model_parallel_rank()}, rank {torch.distributed.get_rank()}]", get_list=True)
---
> string = 'time (ms)'
289,301c254,256
< logged_times = self.timers[name].logged_times
< if logged_times > 0:
< elapsed_time = self.timers[name].elapsed(
< reset=reset) * 1000000.0 / logged_times
< string_ops += ' | {}: {:.2f}'.format(name, elapsed_time)
< else:
< elapsed_time = self.timers[name].elapsed(
< reset=reset) * 1000.0 / normalizer
< string += ' | {}: {:.2f}'.format(name, elapsed_time)
< time_to_csv[0].append(name)
< time_to_csv[1].append(f"{elapsed_time:.2f}")
< time_to_csv[0] += mem_to_csv[0]
< time_to_csv[1] += mem_to_csv[1]
---
> elapsed_time = self.timers[name].elapsed(
> reset=reset) * 1000.0 / normalizer
> string += ' | {}: {:.2f}'.format(name, elapsed_time)
303,304c258,260
< print(string, flush=True)
< print(string_mem, flush=True)
---
> if torch.distributed.get_rank() == (
> torch.distributed.get_world_size() - 1):
> print(string, flush=True)
307,308d262
<
< return time_to_csv
\ No newline at end of file
diff --color -r runtime/megatron/initialize.py ../Megatron-LM-base/megatron/initialize.py
2,9d1
< # Copyright (c) Microsoft Corporation.
< # Licensed under the MIT License.
<
< # The file has been adapted from the following Megatron-LM file:
< # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/initialize.py
< # Git commit hash: 42c1cf4279acea5a554500dcb552211f44cbec45
< # We retain the following copyright from the original files:
<
122,142c114,129
< if args.model_name in ["gpt"]:
< seq_len = args.seq_length
<
< ## Temporarily bypass the check in Aceso
< attn_batch_size = 4
< # attn_batch_size = \
< # (args.num_attention_heads / args.tensor_model_parallel_size) * \
< # args.micro_batch_size
<
< # Constraints on sequence length and attn_batch_size to enable warp based
< # optimization and upper triangular optimization (for causal mask)
< custom_kernel_constraint = seq_len > 16 and seq_len <=2048 and \
< seq_len % 4 == 0 and attn_batch_size % 4 == 0
< # Print a warning.
< if not ((args.fp16 or args.bf16) and
< custom_kernel_constraint and
< args.masked_softmax_fusion):
< if args.rank == 0:
< print('WARNING: constraints for invoking optimized'
< ' fused softmax kernel are not met. We default'
< ' back to unfused kernel invocations.', flush=True)
---
> seq_len = args.seq_length
> attn_batch_size = \
> (args.num_attention_heads / args.tensor_model_parallel_size) * \
> args.micro_batch_size
> # Constraints on sequence length and attn_batch_size to enable warp based
> # optimization and upper triangular optimization (for causal mask)
> custom_kernel_constraint = seq_len > 16 and seq_len <=2048 and \
> seq_len % 4 == 0 and attn_batch_size % 4 == 0
> # Print a warning.
> if not ((args.fp16 or args.bf16) and
> custom_kernel_constraint and
> args.masked_softmax_fusion):
> if args.rank == 0:
> print('WARNING: constraints for invoking optimized'
> ' fused softmax kernel are not met. We default'
> ' back to unfused kernel invocations.', flush=True)
203d189
< # Aceso: use different initialization function
208c194,196
< mpu.initialize_model_parallel_flexpipe()
---
> mpu.initialize_model_parallel(args.tensor_model_parallel_size,
> args.pipeline_model_parallel_size,
> args.virtual_pipeline_model_parallel_size)
diff --color -r runtime/megatron/microbatches.py ../Megatron-LM-base/megatron/microbatches.py
27,31c27,28
< args.global_batch_size, args.micro_batch_size, 1)
<
< # num_microbatches_calculator = ConstantNumMicroBatches(
< # args.global_batch_size, args.micro_batch_size,
< # args.data_parallel_size)
---
> args.global_batch_size, args.micro_batch_size,
> args.data_parallel_size)
36,53c33,50
< # else:
< # assert len(args.rampup_batch_size) == 3, 'expected the following ' \
< # 'format: --rampup-batch-size <start batch size> ' \
< # '<batch size incerement> <ramp-up samples>'
< # start_batch_size = int(args.rampup_batch_size[0])
< # batch_size_increment = int(args.rampup_batch_size[1])
< # ramup_samples = int(args.rampup_batch_size[2])
< # if args.rank == 0:
< # print('will use batch size rampup starting from global batch '
< # 'size {} to global batch size {} with batch size increments '
< # '{} over {} samples.'.format(start_batch_size,
< # args.global_batch_size,
< # batch_size_increment,
< # ramup_samples), flush=True)
< # num_microbatches_calculator = RampupBatchsizeNumMicroBatches(
< # start_batch_size, batch_size_increment, ramup_samples,
< # args.global_batch_size, args.micro_batch_size,
< # args.data_parallel_size)
---
> else:
> assert len(args.rampup_batch_size) == 3, 'expected the following ' \
> 'format: --rampup-batch-size <start batch size> ' \
> '<batch size incerement> <ramp-up samples>'
> start_batch_size = int(args.rampup_batch_size[0])
> batch_size_increment = int(args.rampup_batch_size[1])
> ramup_samples = int(args.rampup_batch_size[2])
> if args.rank == 0:
> print('will use batch size rampup starting from global batch '
> 'size {} to global batch size {} with batch size increments '
> '{} over {} samples.'.format(start_batch_size,
> args.global_batch_size,
> batch_size_increment,
> ramup_samples), flush=True)
> num_microbatches_calculator = RampupBatchsizeNumMicroBatches(
> start_batch_size, batch_size_increment, ramup_samples,
> args.global_batch_size, args.micro_batch_size,
> args.data_parallel_size)
Only in ../Megatron-LM-base/megatron/model: bert_model.py
Only in ../Megatron-LM-base/megatron/model: biencoder_model.py
Only in ../Megatron-LM-base/megatron/model: classification.py
diff --color -r runtime/megatron/model/distributed.py ../Megatron-LM-base/megatron/model/distributed.py
25,26d24
< from megatron.utils import unwrap_model
< from .module import Float16Module
28,29c26
< import os
< LOG_NAME = os.environ.get("LOG_NAME", None)
---
>
148,149c145
< # store the start index for the gradients.
<
---
> # store the start index for the gradients.
170,173c166
<
< args = get_args()
< rank_in_pipeline = mpu.get_pipeline_model_parallel_rank()
< self.resharding = args.resharding_stages[rank_in_pipeline]
---
>
194c187
< ## TODO: continious buffer with resharding.
---
>
198d190
< # args = get_args()
200,201d191
< if self.resharding:
< raise RuntimeError("cross-op resharding with continues buffer is not supported yet.")
207,309c197,218
< if self.resharding:
< # Otherwise, bucketize and all-reduce
< buckets = {}
< dp_groups = {}
< dp_sizes = {}
< # Pack the buckets.
< model_ = unwrap_model(self.module, (Float16Module))
< for op in model_.language_model.ops:
< tp_size = op.tp_size
< dp_size = op.dp_size
< for param in op.parameters():
< if param.requires_grad and param.grad is not None:
< data_type = param.data.type()
< key_str = str(data_type)+str(tp_size)+str(dp_size)
< if key_str not in buckets:
< buckets[key_str] = []
< buckets[key_str].append(param)
< param.main_grad = param.grad
<
< if key_str not in dp_groups:
< dp_groups[key_str] = mpu.get_data_parallel_group_via_op_index(op.op_index)
< dp_sizes[key_str] = dp_size
<
< # For each bucket, all-reduce and copy all-reduced grads.
< for key_str in buckets:
< bucket = buckets[key_str]
< grads = [param.grad.data for param in bucket]
< coalesced = _flatten_dense_tensors(grads)
< coalesced /= dp_sizes[key_str]
< torch.distributed.all_reduce(
< coalesced, group=dp_groups[key_str])
< for buf, synced in zip(grads, _unflatten_dense_tensors(
< coalesced, grads)):
< buf.copy_(synced)
< else:
< # Otherwise, bucketize and all-reduce
< buckets = {}
< # Pack the buckets.
< for param in self.module.parameters():
< if param.requires_grad and param.grad is not None:
< tp = param.data.type()
< if tp not in buckets:
< buckets[tp] = []
< buckets[tp].append(param)
< param.main_grad = param.grad
<
< # For each bucket, all-reduce and copy all-reduced grads.
< for tp in buckets:
< bucket = buckets[tp]
< grads = [param.grad.data for param in bucket]
< coalesced = _flatten_dense_tensors(grads)
< coalesced /= mpu.get_data_parallel_world_size()
< torch.distributed.all_reduce(
< coalesced, group=mpu.get_data_parallel_group())
< for buf, synced in zip(grads, _unflatten_dense_tensors(
< coalesced, grads)):
< buf.copy_(synced)
<
<
< # def allreduce_gradients(self):
< # """Reduce gradients across data parallel ranks."""
< # # If we have buffers, simply reduce the data in the buffer.
< # if self._grad_buffers is not None:
< # for _, buffer_ in self._grad_buffers.items():
< # buffer_.data /= mpu.get_data_parallel_world_size()
< # torch.distributed.all_reduce(
< # buffer_.data, group=mpu.get_data_parallel_group())
< # else:
< # # Otherwise, bucketize and all-reduce
< # buckets = {}
< # # Pack the buckets.
< # for param in self.module.parameters():
< # if param.requires_grad and param.grad is not None:
< # tp = param.data.type()
< # if tp not in buckets:
< # buckets[tp] = []
< # buckets[tp].append(param)
< # param.main_grad = param.grad
<
< # # print(f"[DEBUG] ======> allreduce_gradients <=====")
< # # for name, params in self.module.named_parameters():
< # # if params.requires_grad:
< # # if params.grad is not None:
< # # string = f"[DEBUG] param name {name}, requires_grad: {params.requires_grad},\n main_grad: {params.main_grad}"
< # # else:
< # # string = f"[DEBUG] param name {name}, requires_grad: {params.requires_grad},\n grad = None"
< # # else:
< # # string = f"[DEBUG] param name {name}, requires_grad: {params.requires_grad}"
< # # with open(f"{LOG_NAME}_debug_grad_rank_{torch.distributed.get_rank()}.log", "a+") as f:
< # # f.write(string+"\n")
<
<
< # # For each bucket, all-reduce and copy all-reduced grads.
< # for tp in buckets:
< # bucket = buckets[tp]
< # grads = [param.grad.data for param in bucket]
< # coalesced = _flatten_dense_tensors(grads)
< # coalesced /= mpu.get_data_parallel_world_size()
< # torch.distributed.all_reduce(
< # coalesced, group=mpu.get_data_parallel_group())
< # for buf, synced in zip(grads, _unflatten_dense_tensors(
< # coalesced, grads)):
< # buf.copy_(synced)
---
> # Otherwise, bucketize and all-reduce
> buckets = {}
> # Pack the buckets.
> for param in self.module.parameters():
> if param.requires_grad and param.grad is not None:
> tp = param.data.type()
> if tp not in buckets:
> buckets[tp] = []
> buckets[tp].append(param)
> param.main_grad = param.grad
>
> # For each bucket, all-reduce and copy all-reduced grads.
> for tp in buckets:
> bucket = buckets[tp]
> grads = [param.grad.data for param in bucket]
> coalesced = _flatten_dense_tensors(grads)
> coalesced /= mpu.get_data_parallel_world_size()
> torch.distributed.all_reduce(
> coalesced, group=mpu.get_data_parallel_group())
> for buf, synced in zip(grads, _unflatten_dense_tensors(
> coalesced, grads)):
> buf.copy_(synced)
Only in runtime/megatron/model: flex_gpt.py
Only in runtime/megatron/model: flex_model.py
Only in runtime/megatron/model: flex_ops.py
Only in runtime/megatron/model: flex_resnet.py
Only in runtime/megatron/model: flex_t5.py
diff --color -r runtime/megatron/model/fused_softmax.py ../Megatron-LM-base/megatron/model/fused_softmax.py
16d15
<
18d16
< import torch.nn as nn
34a33
>
38d36
<
46a45
>