forked from flashinfer-ai/flashinfer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcutlass_fused_moe_kernels.cuh
More file actions
4875 lines (4323 loc) · 241 KB
/
Copy pathcutlass_fused_moe_kernels.cuh
File metadata and controls
4875 lines (4323 loc) · 241 KB
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
/*
* Copyright (c) 2020-2025, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cuda.h>
#include <cuda_fp16.h>
#include <float.h>
#include <math.h>
#include <algorithm>
#include <memory>
#include <numeric>
#include <random>
#include <sstream>
#include "tensorrt_llm/common/memoryUtils.h"
#include "tensorrt_llm/common/workspace.h"
// Ignore CUTLASS warnings about type punning
#ifdef __GNUC__ // Check if the compiler is GCC or Clang
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
#include "cute/tensor.hpp"
#include "cutlass/conv/convolution.h"
// Order matters here, packed_stride.hpp is missing cute and convolution includes
#include "cutlass/array.h"
#include "cutlass/epilogue/thread/activation.h"
#include "cutlass/numeric_conversion.h"
#include "cutlass/numeric_types.h"
#include "cutlass/util/packed_stride.hpp"
#include "cutlass_extensions/epilogue/thread/fused_activations.h"
#ifdef __GNUC__ // Check if the compiler is GCC or Clang
#pragma GCC diagnostic pop
#endif
#include "moe_kernels.h"
#include "moe_util_kernels.h"
#include "tensorrt_llm/common/cudaUtils.h"
#include "tensorrt_llm/common/dataType.h"
#include "tensorrt_llm/common/envUtils.h"
#include "tensorrt_llm/kernels/cutlass_kernels/cutlass_type_conversion.h"
#include "tensorrt_llm/kernels/preQuantScaleKernel.h"
#include "tensorrt_llm/kernels/quantization.cuh"
#ifndef CUDART_VERSION
#error CUDART_VERSION Undefined!
#elif (CUDART_VERSION >= 11050)
#include <curand_kernel.h>
#include <curand_philox4x32_x.h>
#include <cub/cub.cuh>
#else
#include "3rdparty/cub/cub.cuh"
#endif
using namespace tensorrt_llm::kernels;
using namespace tensorrt_llm::common;
namespace tensorrt_llm::kernels::cutlass_kernels {
/**
* Takes the input maps and prepares the expanded maps for min latency
* @param num_active_experts_per_node: Number of active experts on current node
* @param experts_to_token_scores: The score of each token for each activated expert. 0 if the
* expert is not chosen by the token. Only the first num_active_experts_per_ rows are valid
* @param active_expert_global_ids: The global expert id for each activated expert
* Only the first num_active_experts_per_ values are valid
* @param expert_first_token_offset: Store the first token offset for each expert
*/
template <typename T, int BLOCK_SIZE>
__device__ __forceinline__ void initTensor(T* value, int const tid, int const total_num,
T const init_value) {
for (int i = tid; i < total_num; i += BLOCK_SIZE) {
value[i] = init_value;
}
}
template <typename T, int BLOCK_SIZE>
__device__ __forceinline__ void setLocalExperts(int* s_local_experts,
T const* token_selected_experts,
int const total_num_experts, int const tid,
int const start_expert, int const end_expert) {
for (int i = tid; i < total_num_experts; i += BLOCK_SIZE) {
int const expert = token_selected_experts[i];
// If expert is in the current node, subtract start_expert to shift the range to [0,
// num_experts_per_node)
bool is_valid_expert = expert >= start_expert && expert < end_expert;
if (is_valid_expert) {
int local_expert_id = expert - start_expert;
if (s_local_experts[local_expert_id] == 0) {
s_local_experts[local_expert_id] =
1; // @TODO: Make sure that we allow duplicated write here
}
}
}
__syncthreads();
}
template <typename T, int BLOCK_SIZE>
__device__ __forceinline__ void prefixSum(T* out, T* in, int const num, int const tid) {
typedef cub::BlockScan<T, BLOCK_SIZE> BlockScan;
__shared__ typename BlockScan::TempStorage tempStorage;
T threadData = 0;
if (tid < num) {
threadData = in[tid];
}
BlockScan(tempStorage).InclusiveSum(threadData, threadData);
__syncthreads();
if (tid < num) {
out[tid] = threadData;
}
__syncthreads();
}
__device__ __forceinline__ void setActiveNum(int& num_active, int& num_active_offset_start,
int& num_active_offset_end, int const cluster_size,
int const cluster_rank) {
int num_remainder = num_active % cluster_size;
int num_active_per_node =
max(0, num_active - 1) / cluster_size; // num_active_per_node shouldn't be neg
if (cluster_rank < num_remainder) {
num_active = num_active_per_node + 1;
num_active_offset_start = cluster_rank * num_active;
} else {
num_active = num_active_per_node;
num_active_offset_start = cluster_rank * num_active_per_node + num_remainder;
}
num_active_offset_end = num_active_offset_start + num_active;
}
template <int BLOCK_SIZE>
__global__ void buildMinLatencyActiveExpertMapsKernel(
int* num_active_experts_per_node, float* experts_to_token_scores, int* active_expert_global_ids,
int64_t* expert_first_token_offset, int const* token_selected_experts,
float const* token_final_scales, int64_t const num_tokens, int const num_experts_per_token,
int const start_expert, int const end_expert, int const num_experts_per_node,
bool const smart_routing, int const cluster_rank, int const cluster_size,
int const num_experts_smem) {
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.wait;");
#endif
// Use one block to process the min latency case
int tid = threadIdx.x;
// 0. init the global memory experts_to_token_scores [num_experts_per_node, num_token]
int const total_local_scales = num_experts_per_node * num_tokens;
initTensor<float, BLOCK_SIZE>(experts_to_token_scores, tid, total_local_scales, 0.0f);
initTensor<int, BLOCK_SIZE>(active_expert_global_ids, tid, num_experts_per_node, -1);
__threadfence(); //@Todo: check do I need this fence for previous zero setting
// 1. mask for the active expert: 1 stands for active
extern __shared__ int s_local_experts[];
int* s_store_experts = s_local_experts + num_experts_smem;
initTensor<int, BLOCK_SIZE>(s_local_experts, tid, num_experts_smem, 0);
__syncthreads();
// 2. set the shared array s_local_experts[]
int const total_num_experts = num_tokens * num_experts_per_token;
setLocalExperts<int, BLOCK_SIZE>(s_local_experts, token_selected_experts, total_num_experts, tid,
start_expert, end_expert);
// 3. perform prefix sum to acquire the store position and total active experts
//@TODO: Use cub first, might need to change it to self-defined api
prefixSum<int, BLOCK_SIZE>(s_store_experts, s_local_experts, num_experts_smem, tid);
// 4. store the num of active experts
int num_active = s_store_experts[num_experts_smem - 1];
int num_active_offset_start = 0;
int num_active_offset_end = 0;
if (smart_routing) {
setActiveNum(num_active, num_active_offset_start, num_active_offset_end, cluster_size,
cluster_rank);
}
if (tid == 0) {
*num_active_experts_per_node = num_active;
}
// 5. store the global expert id for each expert
if (smart_routing) {
for (int i = tid; i < num_experts_smem; i += BLOCK_SIZE) {
if (s_local_experts[i]) {
int offset = s_store_experts[i] - 1;
if (offset >= num_active_offset_start && offset < num_active_offset_end) {
active_expert_global_ids[offset - num_active_offset_start] = i;
} else {
s_local_experts[i] = 0;
}
}
}
__syncthreads(); // Need sync to update the s_local_experts
} else {
for (int i = tid; i < num_experts_smem; i += BLOCK_SIZE) {
if (s_local_experts[i]) {
int offset = s_store_experts[i] - 1;
active_expert_global_ids[offset] = i + start_expert;
}
}
}
// 6. store the scale values
__threadfence(); //@Todo: check do I need this fence for previous zero setting
for (int i = tid; i < total_num_experts; i += BLOCK_SIZE) {
int const expert = token_selected_experts[i];
// If expert is not in the current node, set it to num_experts_per_node
// If expert is in the current node, subtract start_expert to shift the range to [0,
// num_experts_per_node)
bool is_valid_expert =
smart_routing ? s_local_experts[expert] : (expert >= start_expert && expert < end_expert);
if (is_valid_expert) {
int token = i / num_experts_per_token;
float const scale = token_final_scales[i];
int offset = s_store_experts[expert - start_expert] - 1 - num_active_offset_start;
experts_to_token_scores[offset * num_tokens + token] = scale;
}
}
// 7. set default value for redundant memory
for (int i_exp = num_active + tid; i_exp < num_experts_per_node; i_exp += BLOCK_SIZE) {
active_expert_global_ids[i_exp] = -1;
}
// 8. set expert_first_token_offset
for (int i_exp = tid; i_exp < num_experts_per_node + 1; i_exp += BLOCK_SIZE) {
if (i_exp < num_active) {
expert_first_token_offset[i_exp] = i_exp * num_tokens;
} else {
expert_first_token_offset[i_exp] = num_active * num_tokens;
}
}
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.launch_dependents;");
#endif
}
void buildMinLatencyActiveExpertMaps(
int* num_active_experts_per_node, float* experts_to_token_scores, int* active_expert_global_ids,
int64_t* expert_first_token_offset, int const* token_selected_experts,
float const* token_final_scales, int64_t const num_tokens, int const experts_per_token,
int const start_expert, int const end_expert, int const num_experts_per_node,
int const cluster_rank, int const cluster_size, int const num_experts_smem, bool enable_pdl,
cudaStream_t const stream) {
TLLM_CHECK_WITH_INFO(num_experts_per_node == (end_expert - start_expert),
"num_experts_per_node must be equal to end_expert - start_expert");
TLLM_CHECK_WITH_INFO(num_experts_per_node <= 256,
"don't support num_experts_per_node > 256 cases");
int const threads = 256;
int const blocks = 1;
bool const smart_routing = cluster_size > 1;
cudaLaunchConfig_t config;
config.gridDim = blocks;
config.blockDim = threads;
config.dynamicSmemBytes = num_experts_smem * sizeof(int) * 2;
config.stream = stream;
cudaLaunchAttribute attrs[1];
attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
attrs[0].val.programmaticStreamSerializationAllowed = enable_pdl;
config.numAttrs = 1;
config.attrs = attrs;
cudaLaunchKernelEx(&config, buildMinLatencyActiveExpertMapsKernel<threads>,
num_active_experts_per_node, experts_to_token_scores, active_expert_global_ids,
expert_first_token_offset, token_selected_experts, token_final_scales,
num_tokens, experts_per_token, start_expert, end_expert, num_experts_per_node,
smart_routing, cluster_rank, cluster_size, num_experts_smem);
}
template <int BLOCK_SIZE, int EXPERTS_PER_TOKEN, int LOG2_NUM_EXPERTS>
__global__ void fusedBuildExpertMapsSortFirstTokenKernel(
int const* const token_selected_experts, int* const permuted_row_to_unpermuted_row,
int* const unpermuted_row_to_permuted_row, int64_t* const expert_first_token_offset,
int64_t const num_tokens, int const experts_per_token, int const start_expert,
int const end_expert, int const num_experts_per_node) {
// Only using block wise collective so we can only have one block
assert(gridDim.x == 1);
assert(start_expert <= end_expert);
assert(num_experts_per_node == (end_expert - start_expert));
assert(num_experts_per_node <= (1 << LOG2_NUM_EXPERTS));
int const token = blockIdx.x * BLOCK_SIZE + threadIdx.x;
bool is_valid_token = token < num_tokens;
// This is the masked expert id for this token
int local_token_selected_experts[EXPERTS_PER_TOKEN];
// This is the final permuted rank of this token (ranked by selected expert)
int local_token_permuted_indices[EXPERTS_PER_TOKEN];
// Wait PDL before reading token_selected_experts
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.wait;");
#endif
// build expert map
// we need to populate expert ids for all threads, even if there are
// fewer tokens
#pragma unroll
for (int i = 0; i < EXPERTS_PER_TOKEN; i++) {
int const expert = is_valid_token ? token_selected_experts[token * EXPERTS_PER_TOKEN + i]
: num_experts_per_node;
// If the token is not valid, set the expert id to num_experts_per_node + 1
// If expert is not in the current node, set it to num_experts_per_node
// If expert is in the current node, subtract start_expert to shift the range to [0,
// num_experts_per_node)
bool is_valid_expert = expert >= start_expert && expert < end_expert;
local_token_selected_experts[i] = !is_valid_token ? num_experts_per_node + 1
: is_valid_expert ? (expert - start_expert)
: num_experts_per_node;
}
// TODO: decompose cub's sort to expose the bucket starts, and just return
// that to elide the binary search
// sort the expert map
using BlockRadixRank = cub::BlockRadixRank<BLOCK_SIZE, LOG2_NUM_EXPERTS, false>;
extern __shared__ unsigned char temp_storage[];
auto& sort_temp = *reinterpret_cast<typename BlockRadixRank::TempStorage*>(temp_storage);
// Sanity check that the number of bins do correspond to the number of experts
static_assert(BlockRadixRank::BINS_TRACKED_PER_THREAD * BLOCK_SIZE >= (1 << LOG2_NUM_EXPERTS));
assert(BlockRadixRank::BINS_TRACKED_PER_THREAD * BLOCK_SIZE >= num_experts_per_node);
int local_expert_first_token_offset[BlockRadixRank::BINS_TRACKED_PER_THREAD];
cub::BFEDigitExtractor<int> extractor(0, LOG2_NUM_EXPERTS);
BlockRadixRank(sort_temp).RankKeys(local_token_selected_experts, local_token_permuted_indices,
extractor, local_expert_first_token_offset);
// We are done with compute, launch the dependent kernels while the stores are in flight
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.launch_dependents;");
#endif
// write to shared memory and global memory
if (is_valid_token) {
#pragma unroll
for (int i = 0; i < EXPERTS_PER_TOKEN; i++) {
int const unpermuted_row = i * num_tokens + token;
int const permuted_row = local_token_permuted_indices[i];
permuted_row_to_unpermuted_row[permuted_row] = unpermuted_row;
unpermuted_row_to_permuted_row[unpermuted_row] = permuted_row;
}
}
#pragma unroll
for (int expert_id = 0; expert_id < BlockRadixRank::BINS_TRACKED_PER_THREAD; expert_id++) {
int out_expert_id = expert_id + token * BlockRadixRank::BINS_TRACKED_PER_THREAD;
if (out_expert_id < num_experts_per_node + 1) {
expert_first_token_offset[out_expert_id] = local_expert_first_token_offset[expert_id];
}
}
}
template <int BLOCK_SIZE, int EXPERTS_PER_TOKEN, int LOG2_NUM_EXPERTS>
bool fusedBuildExpertMapsSortFirstTokenDispatch(
int const* token_selected_experts, int* permuted_row_to_unpermuted_row,
int* unpermuted_row_to_permuted_row, int64_t* expert_first_token_offset,
int64_t const num_tokens, int const num_experts_per_node, int const experts_per_token,
int const start_expert, int const end_expert, bool enable_pdl, cudaStream_t stream) {
TLLM_CHECK_WITH_INFO(num_experts_per_node == (end_expert - start_expert),
"num_experts_per_node must be equal to end_expert - start_expert");
int const threads = BLOCK_SIZE;
int const blocks = (num_tokens + threads - 1) / threads;
TLLM_CHECK_WITH_INFO(blocks == 1, "Current implementation requires single block");
using BlockRadixRank = cub::BlockRadixRank<BLOCK_SIZE, LOG2_NUM_EXPERTS, false>;
size_t shared_size = sizeof(typename BlockRadixRank::TempStorage);
cudaLaunchConfig_t config;
config.gridDim = blocks;
config.blockDim = threads;
config.dynamicSmemBytes = shared_size;
config.stream = stream;
cudaLaunchAttribute attrs[1];
attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
attrs[0].val.programmaticStreamSerializationAllowed = enable_pdl;
config.numAttrs = 1;
config.attrs = attrs;
auto kernel =
&fusedBuildExpertMapsSortFirstTokenKernel<BLOCK_SIZE, EXPERTS_PER_TOKEN, LOG2_NUM_EXPERTS>;
int device = 0;
int max_smem_per_block = 0;
check_cuda_error(cudaGetDevice(&device));
check_cuda_error(
cudaDeviceGetAttribute(&max_smem_per_block, cudaDevAttrMaxSharedMemoryPerBlockOptin, device));
if (shared_size >= static_cast<size_t>(max_smem_per_block)) {
// This should mean that
// cudaFuncSetAttribute(cutlass::Kernel<GemmKernel>,
// cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size) wouldn't work.
return false;
}
check_cuda_error(
cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, shared_size));
check_cuda_error(
cudaLaunchKernelEx(&config, kernel, token_selected_experts, permuted_row_to_unpermuted_row,
unpermuted_row_to_permuted_row, expert_first_token_offset, num_tokens,
experts_per_token, start_expert, end_expert, num_experts_per_node));
return true;
}
template <int EXPERTS_PER_TOKEN, int LOG2_NUM_EXPERTS>
bool fusedBuildExpertMapsSortFirstTokenBlockSize(
int const* token_selected_experts, int* permuted_row_to_unpermuted_row,
int* unpermuted_row_to_permuted_row, int64_t* expert_first_token_offset,
int64_t const num_tokens, int const num_experts_per_node, int const experts_per_token,
int const start_expert, int const end_expert, bool enable_pdl, cudaStream_t stream) {
int const block_size = num_tokens;
if (num_tokens > 256) {
TLLM_LOG_TRACE(
"Number of tokens %d is greater than 256, which is not supported for fused moe prologues",
num_tokens);
return false;
}
auto func = &fusedBuildExpertMapsSortFirstTokenDispatch<32, EXPERTS_PER_TOKEN, LOG2_NUM_EXPERTS>;
if (block_size > 32 && block_size <= 64) {
func = &fusedBuildExpertMapsSortFirstTokenDispatch<64, EXPERTS_PER_TOKEN, LOG2_NUM_EXPERTS>;
} else if (block_size > 64 && block_size <= 128) {
func = &fusedBuildExpertMapsSortFirstTokenDispatch<128, EXPERTS_PER_TOKEN, LOG2_NUM_EXPERTS>;
} else if (block_size > 128 && block_size <= 256) {
func = &fusedBuildExpertMapsSortFirstTokenDispatch<256, EXPERTS_PER_TOKEN, LOG2_NUM_EXPERTS>;
}
return func(token_selected_experts, permuted_row_to_unpermuted_row,
unpermuted_row_to_permuted_row, expert_first_token_offset, num_tokens,
num_experts_per_node, experts_per_token, start_expert, end_expert, enable_pdl,
stream);
}
template <int LOG2_NUM_EXPERTS>
bool fusedBuildExpertMapsSortFirstTokenBlockSize(
int const* token_selected_experts, int* permuted_row_to_unpermuted_row,
int* unpermuted_row_to_permuted_row, int64_t* expert_first_token_offset,
int64_t const num_tokens, int const num_experts_per_node, int const experts_per_token,
int const start_expert, int const end_expert, bool enable_pdl, cudaStream_t stream) {
auto func = &fusedBuildExpertMapsSortFirstTokenBlockSize<1, LOG2_NUM_EXPERTS>;
switch (experts_per_token) {
case 1: {
func = &fusedBuildExpertMapsSortFirstTokenBlockSize<1, LOG2_NUM_EXPERTS>;
break;
}
case 2: {
func = &fusedBuildExpertMapsSortFirstTokenBlockSize<2, LOG2_NUM_EXPERTS>;
break;
}
case 4: {
func = &fusedBuildExpertMapsSortFirstTokenBlockSize<4, LOG2_NUM_EXPERTS>;
break;
}
case 6: {
func = &fusedBuildExpertMapsSortFirstTokenBlockSize<6, LOG2_NUM_EXPERTS>;
break;
}
case 8: {
func = &fusedBuildExpertMapsSortFirstTokenBlockSize<8, LOG2_NUM_EXPERTS>;
break;
}
default: {
TLLM_LOG_TRACE("Top-K value %d does not have supported fused moe prologues",
experts_per_token);
return false;
}
}
return func(token_selected_experts, permuted_row_to_unpermuted_row,
unpermuted_row_to_permuted_row, expert_first_token_offset, num_tokens,
num_experts_per_node, experts_per_token, start_expert, end_expert, enable_pdl,
stream);
}
bool fusedBuildExpertMapsSortFirstToken(
int const* token_selected_experts, int* permuted_row_to_unpermuted_row,
int* unpermuted_row_to_permuted_row, int64_t* expert_first_token_offset,
int64_t const num_tokens, int const num_experts_per_node, int const experts_per_token,
int const start_expert, int const end_expert, bool enable_pdl, cudaStream_t stream) {
// We need enough bits to represent [0, num_experts_per_node+1] (inclusive) i.e.
// num_experts_per_node + 2 values This is floor(log2(num_experts_per_node+1)) + 1
int expert_log = static_cast<int>(log2(num_experts_per_node + 1)) + 1;
if (expert_log <= 9) {
auto funcs = std::array{&fusedBuildExpertMapsSortFirstTokenBlockSize<1>,
&fusedBuildExpertMapsSortFirstTokenBlockSize<2>,
&fusedBuildExpertMapsSortFirstTokenBlockSize<3>,
&fusedBuildExpertMapsSortFirstTokenBlockSize<4>,
&fusedBuildExpertMapsSortFirstTokenBlockSize<5>,
&fusedBuildExpertMapsSortFirstTokenBlockSize<6>,
&fusedBuildExpertMapsSortFirstTokenBlockSize<7>,
&fusedBuildExpertMapsSortFirstTokenBlockSize<8>,
&fusedBuildExpertMapsSortFirstTokenBlockSize<9>};
return funcs[expert_log - 1](token_selected_experts, permuted_row_to_unpermuted_row,
unpermuted_row_to_permuted_row, expert_first_token_offset,
num_tokens, num_experts_per_node, experts_per_token, start_expert,
end_expert, enable_pdl, stream);
}
TLLM_LOG_TRACE("Experts per node %d does not have supported fused moe prologues",
num_experts_per_node);
return false;
}
int64_t computeNumTokensPerBlock(int64_t const num_tokens, int64_t const num_experts_per_node) {
for (int64_t num_tokens_per_block = 32; num_tokens_per_block <= 1024; num_tokens_per_block *= 2) {
int64_t const num_blocks_per_seq =
tensorrt_llm::common::ceilDiv(num_tokens, num_tokens_per_block);
if (num_blocks_per_seq * num_experts_per_node <= num_tokens_per_block) {
return num_tokens_per_block;
}
}
return 1024;
}
template <int kNumTokensPerBlock>
__global__ void blockExpertPrefixSumKernel(int const* token_selected_experts,
int* blocked_expert_counts,
int* blocked_row_to_unpermuted_row,
int64_t const num_tokens,
int64_t const num_experts_per_token,
int const start_expert_id) {
using BlockScan = cub::BlockScan<int, kNumTokensPerBlock>;
__shared__ typename BlockScan::TempStorage temp_storage;
// target_expert_id and expert_id are offset by start_expert_id
int const target_expert_id = blockIdx.x;
int const block_id = blockIdx.y;
int const num_blocks_per_seq = gridDim.y;
int const token_id = block_id * kNumTokensPerBlock + threadIdx.x;
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.wait;");
#endif
int expanded_token_id = -1;
if (token_id < num_tokens) {
for (int i = 0; i < num_experts_per_token; i++) {
// TODO(enweiz): Fix uncoalesced access with shared memory.
int const expert_id =
token_selected_experts[token_id * num_experts_per_token + i] - start_expert_id;
if (expert_id == target_expert_id) {
expanded_token_id = i * num_tokens + token_id;
break;
}
}
}
int const has_matched = expanded_token_id >= 0 ? 1 : 0;
int index;
BlockScan(temp_storage).ExclusiveSum(has_matched, index);
if (has_matched) {
blocked_row_to_unpermuted_row[target_expert_id * num_tokens + block_id * kNumTokensPerBlock +
index] = expanded_token_id;
}
if (threadIdx.x == kNumTokensPerBlock - 1) {
blocked_expert_counts[target_expert_id * num_blocks_per_seq + block_id] = index + has_matched;
}
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.launch_dependents;");
#endif
}
void blockExpertPrefixSum(int const* token_selected_experts, int* blocked_expert_counts,
int* blocked_row_to_unpermuted_row, int64_t const num_tokens,
int64_t const num_experts_per_node, int64_t const num_experts_per_token,
int64_t const num_tokens_per_block, int64_t const num_blocks_per_seq,
int const start_expert_id, bool enable_pdl, cudaStream_t stream) {
dim3 const blocks(num_experts_per_node, num_blocks_per_seq);
dim3 const threads(num_tokens_per_block);
cudaLaunchConfig_t config;
config.gridDim = blocks;
config.blockDim = threads;
config.dynamicSmemBytes = 0;
config.stream = stream;
cudaLaunchAttribute attrs[1];
attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
attrs[0].val.programmaticStreamSerializationAllowed = enable_pdl;
config.numAttrs = 1;
config.attrs = attrs;
auto func = blockExpertPrefixSumKernel<1024>;
if (num_tokens_per_block <= 32) {
func = blockExpertPrefixSumKernel<32>;
} else if (num_tokens_per_block <= 64) {
func = blockExpertPrefixSumKernel<64>;
} else if (num_tokens_per_block <= 128) {
func = blockExpertPrefixSumKernel<128>;
} else if (num_tokens_per_block <= 256) {
func = blockExpertPrefixSumKernel<256>;
} else if (num_tokens_per_block <= 512) {
func = blockExpertPrefixSumKernel<512>;
}
cudaLaunchKernelEx(&config, func, token_selected_experts, blocked_expert_counts,
blocked_row_to_unpermuted_row, num_tokens, num_experts_per_token,
start_expert_id);
}
template <int kNumThreadsPerBlock>
__global__ void globalExpertPrefixSumLargeKernel(int const* blocked_expert_counts,
int* blocked_expert_counts_cumsum,
int64_t* expert_first_token_offset,
int64_t const num_experts_per_node,
int64_t const num_blocks_per_seq,
int64_t const num_elem_per_thread) {
using BlockScan = cub::BlockScan<int, kNumThreadsPerBlock>;
__shared__ typename BlockScan::TempStorage temp_storage;
int offset = threadIdx.x * num_elem_per_thread;
int cnt = 0;
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.wait;");
#endif
// Note: Because of limited registers, cannot store thread-level prefix sum or enable #pragma
// unroll
for (int i = 0; i < num_elem_per_thread; i++) {
// TODO(enweiz): Fix uncoalesced access with shared memory.
if (offset + i < num_experts_per_node * num_blocks_per_seq) {
cnt += blocked_expert_counts[offset + i];
}
}
int cumsum;
BlockScan(temp_storage).ExclusiveSum(cnt, cumsum);
for (int i = 0; i < num_elem_per_thread; i++) {
if (offset + i < num_experts_per_node * num_blocks_per_seq) {
blocked_expert_counts_cumsum[offset + i] = cumsum;
if ((offset + i) % num_blocks_per_seq == 0) {
expert_first_token_offset[(offset + i) / num_blocks_per_seq] = cumsum;
}
cumsum += blocked_expert_counts[offset + i];
if ((offset + i) == num_experts_per_node * num_blocks_per_seq - 1) {
expert_first_token_offset[num_experts_per_node] = cumsum;
}
}
}
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.launch_dependents;");
#endif
}
template <int kNumThreadsPerBlock>
__global__ void globalExpertPrefixSumKernel(int const* blocked_expert_counts,
int* blocked_expert_counts_cumsum,
int64_t* expert_first_token_offset,
int64_t const num_experts_per_node,
int64_t const num_blocks_per_seq) {
using BlockScan = cub::BlockScan<int, kNumThreadsPerBlock>;
__shared__ typename BlockScan::TempStorage temp_storage;
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.wait;");
#endif
int const cnt = threadIdx.x < num_experts_per_node * num_blocks_per_seq
? blocked_expert_counts[threadIdx.x]
: 0;
int cumsum;
BlockScan(temp_storage).ExclusiveSum(cnt, cumsum);
if (threadIdx.x < num_experts_per_node * num_blocks_per_seq) {
blocked_expert_counts_cumsum[threadIdx.x] = cumsum;
if (threadIdx.x % num_blocks_per_seq == 0) {
expert_first_token_offset[threadIdx.x / num_blocks_per_seq] = cumsum;
}
if (threadIdx.x == num_experts_per_node * num_blocks_per_seq - 1) {
expert_first_token_offset[num_experts_per_node] = cumsum + cnt;
}
}
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.launch_dependents;");
#endif
}
void globalExpertPrefixSum(int const* blocked_expert_counts, int* blocked_expert_counts_cumsum,
int64_t* expert_first_token_offset, int64_t const num_experts_per_node,
int64_t const num_tokens_per_block, int64_t const num_blocks_per_seq,
bool enable_pdl, cudaStream_t stream) {
int64_t const num_elements = num_experts_per_node * num_blocks_per_seq;
cudaLaunchConfig_t config;
config.gridDim = 1;
config.blockDim = 1024;
config.dynamicSmemBytes = 0;
config.stream = stream;
cudaLaunchAttribute attrs[1];
attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
attrs[0].val.programmaticStreamSerializationAllowed = enable_pdl;
config.numAttrs = 1;
config.attrs = attrs;
if (num_elements <= 1024) {
auto func = globalExpertPrefixSumKernel<1024>;
if (num_elements <= 32) {
func = globalExpertPrefixSumKernel<32>;
config.blockDim = 32;
} else if (num_elements <= 64) {
func = globalExpertPrefixSumKernel<64>;
config.blockDim = 64;
} else if (num_elements <= 128) {
func = globalExpertPrefixSumKernel<128>;
config.blockDim = 128;
} else if (num_elements <= 256) {
func = globalExpertPrefixSumKernel<256>;
config.blockDim = 256;
} else if (num_elements <= 512) {
func = globalExpertPrefixSumKernel<512>;
config.blockDim = 512;
}
cudaLaunchKernelEx(&config, func, blocked_expert_counts, blocked_expert_counts_cumsum,
expert_first_token_offset, num_experts_per_node, num_blocks_per_seq);
} else {
auto func = globalExpertPrefixSumLargeKernel<1024>;
int64_t const num_elem_per_thread = tensorrt_llm::common::ceilDiv(num_elements, 1024);
cudaLaunchKernelEx(&config, func, blocked_expert_counts, blocked_expert_counts_cumsum,
expert_first_token_offset, num_experts_per_node, num_blocks_per_seq,
num_elem_per_thread);
}
}
__global__ void mergeExpertPrefixSumKernel(int const* blocked_expert_counts,
int const* blocked_expert_counts_cumsum,
int const* blocked_row_to_unpermuted_row,
int* permuted_token_selected_experts,
int* permuted_row_to_unpermuted_row,
int* unpermuted_row_to_permuted_row,
int const num_tokens) {
int const target_expert_id = blockIdx.x;
int const block_id = blockIdx.y;
int const num_blocks_per_seq = gridDim.y;
int const token_id = block_id * blockDim.x + threadIdx.x;
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.wait;");
#endif
int const cnt = blocked_expert_counts[target_expert_id * num_blocks_per_seq + block_id];
int const offset = blocked_expert_counts_cumsum[target_expert_id * num_blocks_per_seq + block_id];
if (threadIdx.x < cnt) {
int const unpermuted_row =
blocked_row_to_unpermuted_row[target_expert_id * num_tokens + token_id];
int const permuted_row = offset + threadIdx.x;
permuted_row_to_unpermuted_row[permuted_row] = unpermuted_row;
permuted_token_selected_experts[permuted_row] = target_expert_id;
unpermuted_row_to_permuted_row[unpermuted_row] = permuted_row;
}
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
asm volatile("griddepcontrol.launch_dependents;");
#endif
}
void mergeExpertPrefixSum(int const* blocked_expert_counts, int const* blocked_expert_counts_cumsum,
int const* blocked_row_to_unpermuted_row,
int* permuted_token_selected_experts, int* permuted_row_to_unpermuted_row,
int* unpermuted_row_to_permuted_row, int64_t const num_tokens,
int64_t const num_experts_per_node, int64_t const num_tokens_per_block,
int64_t const num_blocks_per_seq, bool enable_pdl, cudaStream_t stream) {
dim3 const blocks(num_experts_per_node, num_blocks_per_seq);
dim3 const threads(num_tokens_per_block);
cudaLaunchConfig_t config;
config.gridDim = blocks;
config.blockDim = threads;
config.dynamicSmemBytes = 0;
config.stream = stream;
cudaLaunchAttribute attrs[1];
attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
attrs[0].val.programmaticStreamSerializationAllowed = enable_pdl;
config.numAttrs = 1;
config.attrs = attrs;
cudaLaunchKernelEx(&config, mergeExpertPrefixSumKernel, blocked_expert_counts,
blocked_expert_counts_cumsum, blocked_row_to_unpermuted_row,
permuted_token_selected_experts, permuted_row_to_unpermuted_row,
unpermuted_row_to_permuted_row, num_tokens);
}
// threeStepBuildExpertMapsSortFirstToken uses three kernels to achieve the sort of
// token_selected_experts
// 1. blockExpertPrefixSumKernel launches [num_experts_per_node, num_blocks_per_seq] CTAs; each CTA
// has num_tokens_per_block threads. blocked_row_to_unpermuted_row points to a 2D buffer of size
// [num_experts_per_node, num_tokens], which can be viewed as [num_experts_per_node,
// num_blocks_per_seq] blocks, and each block has num_tokens_per_block tokens. Note that each CTA
// corresponds to a block in blocked_row_to_unpermuted_row. Within each CTA, the threads leverage
// cub::BlockScan to compute the offsets of tokens that activate the target expert. If a thread's
// token activates the target expert, the thread stores its unpermuted_row to the buffer block with
// the offset. In addition, the kernel also stores the expert counts for each block to another 2D
// buffer blocked_expert_counts of size [num_experts_per_node, num_blocks_per_seq].
// 2. globalExpertPrefixSumKernel launches 1 CTA; that CTA has num_experts_per_node *
// num_blocks_per_seq threads. The kernel views blocked_expert_counts as a 1D buffer, and leverages
// cub::BlockScan to compute the prefix sum of the expert counts for each block. The prefix sum is
// stored to blocked_expert_counts_cumsum.
// 3. mergeExpertPrefixSumKernel launches [num_experts_per_node, num_blocks_per_seq] CTAs; each CTA
// has num_tokens_per_block threads. Each CTA obtains the block-level offset from
// blocked_expert_counts_cumsum, and thus compacts blocked_row_to_unpermuted_row to
// permuted_row_to_unpermuted_row. In addition, with the block-level offsets, the kernel fills
// permuted_token_selected_experts.
// computeNumTokensPerBlock decides num_tokens_per_block. Note that both blockExpertPrefixSumKernel
// and globalExpertPrefixSumKernel leverage cub::BlockScan, and their CTA sizes are
// num_tokens_per_block and num_experts_per_node * num_blocks_per_seq, respectively.
// computeNumTokensPerBlock tries to find a minimum CTA size for both kernels, so that the
// block-leval cub::BlockScan can be efficient.
void threeStepBuildExpertMapsSortFirstToken(
int const* token_selected_experts, int* permuted_token_selected_experts,
int* permuted_row_to_unpermuted_row, int* unpermuted_row_to_permuted_row,
int64_t* expert_first_token_offset, int* blocked_expert_counts,
int* blocked_expert_counts_cumsum, int* blocked_row_to_unpermuted_row, int64_t const num_tokens,
int64_t const num_experts_per_node, int64_t const num_experts_per_token,
int const start_expert_id, bool enable_pdl, cudaStream_t stream) {
int64_t const num_tokens_per_block = computeNumTokensPerBlock(num_tokens, num_experts_per_node);
int64_t const num_blocks_per_seq =
tensorrt_llm::common::ceilDiv(num_tokens, num_tokens_per_block);
blockExpertPrefixSum(token_selected_experts, blocked_expert_counts, blocked_row_to_unpermuted_row,
num_tokens, num_experts_per_node, num_experts_per_token,
num_tokens_per_block, num_blocks_per_seq, start_expert_id, enable_pdl,
stream);
sync_check_cuda_error(stream);
globalExpertPrefixSum(blocked_expert_counts, blocked_expert_counts_cumsum,
expert_first_token_offset, num_experts_per_node, num_tokens_per_block,
num_blocks_per_seq, enable_pdl, stream);
sync_check_cuda_error(stream);
mergeExpertPrefixSum(blocked_expert_counts, blocked_expert_counts_cumsum,
blocked_row_to_unpermuted_row, permuted_token_selected_experts,
permuted_row_to_unpermuted_row, unpermuted_row_to_permuted_row, num_tokens,
num_experts_per_node, num_tokens_per_block, num_blocks_per_seq, enable_pdl,
stream);
}
// ============================== Infer GEMM sizes =================================
// TODO Could linear search be better for small # experts
template <class T>
__device__ inline int64_t findTotalEltsLessThanTarget(T const* sorted_indices,
int64_t const arr_length, T const target) {
int64_t low = 0, high = arr_length - 1, target_location = -1;
while (low <= high) {
int64_t mid = (low + high) / 2;
if (sorted_indices[mid] >= target) {
high = mid - 1;
} else {
low = mid + 1;
target_location = mid;
}
}
return target_location + 1;
}
template <class T>
using sizeof_bits = cutlass::sizeof_bits<
typename cutlass_kernels::TllmToCutlassTypeAdapter<std::remove_cv_t<T>>::type>;
// Function to safely offset an pointer that may contain sub-byte types (FP4/INT4)
template <class T>
__host__ __device__ constexpr T* safe_inc_ptr(T* ptr, size_t offset) {
constexpr int adjustment = (sizeof_bits<T>::value < 8) ? (8 / sizeof_bits<T>::value) : 1;
assert(offset % adjustment == 0 && "Attempt to offset index to sub-byte");
return ptr + offset / adjustment;
}
__host__ __device__ constexpr int64_t getOffsetWeightSF(
int64_t expert_id, int64_t gemm_n, int64_t gemm_k,
TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType scaling_type) {
auto function = [=](int64_t min_n_dim_alignment, int64_t min_k_dim_alignment,
int64_t block_size) {
int64_t padded_gemm_n =
TmaWarpSpecializedGroupedGemmInput::alignToSfDim(gemm_n, min_n_dim_alignment);
int64_t padded_gemm_k =
TmaWarpSpecializedGroupedGemmInput::alignToSfDim(gemm_k, min_k_dim_alignment);
assert(gemm_k % block_size == 0);
return expert_id * padded_gemm_n * padded_gemm_k / block_size;
};
switch (scaling_type) {
case TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType::MXFPX:
return function(TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentMXFPX,
TmaWarpSpecializedGroupedGemmInput::MinKDimAlignmentMXFPX,
TmaWarpSpecializedGroupedGemmInput::MXFPXBlockScaleVectorSize);
case TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType::NVFP4:
return function(TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentNVFP4,
TmaWarpSpecializedGroupedGemmInput::MinKDimAlignmentNVFP4,
TmaWarpSpecializedGroupedGemmInput::NVFP4BlockScaleVectorSize);
case TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType::NONE:
return 0; // No scaling factors, no offset
}
assert(false && "Unrecognized scaling type");
return 0;
}
__host__ __device__ constexpr int64_t getOffsetActivationSF(
int64_t expert_id, int64_t token_offset, int64_t gemm_k,
TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType scaling_type) {
auto function = [=](int64_t min_n_dim_alignment, int64_t min_k_dim_alignment,
int64_t block_size) {
// This formulation ensures that:
// `sf_offset[i + 1] - sf_offset[i] >= padded(token_offset[i + 1] - token_offset[i])`
// is true for all possible token distributions.
int64_t padded_sf_start_offset = TmaWarpSpecializedGroupedGemmInput::alignToSfDim(
token_offset + expert_id * (min_n_dim_alignment - 1), min_n_dim_alignment);
int64_t padded_gemm_k =
TmaWarpSpecializedGroupedGemmInput::alignToSfDim(gemm_k, min_k_dim_alignment);
assert(gemm_k % block_size == 0);
assert(padded_gemm_k % block_size == 0);
return padded_sf_start_offset * padded_gemm_k / block_size;
};
switch (scaling_type) {
case TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType::MXFPX:
return function(TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentMXFPX,
TmaWarpSpecializedGroupedGemmInput::MinKDimAlignmentMXFPX,
TmaWarpSpecializedGroupedGemmInput::MXFPXBlockScaleVectorSize);
case TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType::NVFP4:
return function(TmaWarpSpecializedGroupedGemmInput::MinNDimAlignmentNVFP4,
TmaWarpSpecializedGroupedGemmInput::MinKDimAlignmentNVFP4,
TmaWarpSpecializedGroupedGemmInput::NVFP4BlockScaleVectorSize);
case TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType::NONE:
return 0; // No scaling factors, no offset
}
assert(false && "Unrecognized scaling type");
return 0;
}
template <class GemmOutputType, class QuantizedType, class ComputeElem, int VecSize>
__device__ auto quantizePackedFPXValue(
ComputeElem& post_act_val, float global_scale_val, int64_t num_tokens_before_expert,
int64_t expert_id, int64_t token_id, int64_t elem_idx, int64_t num_cols,
TmaWarpSpecializedGroupedGemmInput::ElementSF* act_sf_flat,
TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType scaling_type) {
constexpr bool is_fp8 = std::is_same_v<QuantizedType, __nv_fp8_e4m3>;
static constexpr int NumThreadsPerSF = VecSize / CVT_ELTS_PER_THREAD;
// Quantize the input to FP4
static_assert(std::is_same_v<GemmOutputType, __nv_bfloat16> ||
std::is_same_v<GemmOutputType, half>);
static_assert(ComputeElem::kElements == CVT_ELTS_PER_THREAD);
PackedVec<GemmOutputType> packed_vec{};
for (int i = 0; i < CVT_ELTS_PER_THREAD / 2; i++) {
packed_vec.elts[i].x = static_cast<GemmOutputType>(post_act_val[i * 2 + 0]);
packed_vec.elts[i].y = static_cast<GemmOutputType>(post_act_val[i * 2 + 1]);
}
// We need to offset into the scaling factors for just this expert
auto act_sf_expert = act_sf_flat + getOffsetActivationSF(expert_id, num_tokens_before_expert,
num_cols, scaling_type);
// Use `token - num_tokens_before_expert` because we want this to be relative to the start of this
// expert
auto sf_out =
cvt_quant_get_sf_out_offset<TmaWarpSpecializedGroupedGemmInput::ElementSF, NumThreadsPerSF>(
std::nullopt /* batchIdx */, token_id - num_tokens_before_expert, elem_idx,
std::nullopt /* numRows */, num_cols / VecSize, act_sf_expert,
QuantizationSFLayout::SWIZZLED_128x4);
// Do the conversion and set the output and scaling factor
auto func = [&]() {
if constexpr (is_fp8) {
return [](PackedVec<GemmOutputType>& vec, float /* ignored */, uint8_t* SFout) -> uint64_t {
static_assert(TmaWarpSpecializedGroupedGemmInput::MXFPXBlockScaleVectorSize == VecSize);
return cvt_warp_fp16_to_mxfp8<GemmOutputType, VecSize>(vec, SFout);
};
} else {
return (scaling_type == TmaWarpSpecializedGroupedGemmInput::FpXBlockScalingType::NVFP4)
? &cvt_warp_fp16_to_fp4<GemmOutputType, VecSize, false>
: &cvt_warp_fp16_to_fp4<GemmOutputType, VecSize, true>;
}