-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathmoeOp.cpp
More file actions
2476 lines (2270 loc) · 138 KB
/
Copy pathmoeOp.cpp
File metadata and controls
2476 lines (2270 loc) · 138 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) 2022-2026, 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.
*/
#if defined(USING_OSS_CUTLASS_MOE_GEMM)
#include "tensorrt_llm/kernels/cutlass_kernels/include/moe_kernels.h"
#else
#include "moe_gemm_kernels.h"
#include "moe_kernels.h"
#endif
// Always include the public header for moe_gemm_kernels.h
#include "tensorrt_llm/kernels/cutlass_kernels/include/moe_gemm_kernels.h"
#include "tensorrt_llm/kernels/cutlass_kernels/include/moe_lora_device_path.h"
#include "tensorrt_llm/kernels/cutlass_kernels/include/moe_lora_problem_builder.h"
#include "tensorrt_llm/kernels/cutlass_kernels/include/moe_lora_slot_expand.h"
#include "cutlass/gemm_coord.h"
#include "tensorrt_llm/common/config.h"
#include "tensorrt_llm/common/cublasMMWrapper.h"
#include "tensorrt_llm/common/dataType.h"
#include "tensorrt_llm/common/opUtils.h"
#include "tensorrt_llm/common/workspace.h"
#include "tensorrt_llm/kernels/cuda_graph_grouped_gemm.h"
#include "tensorrt_llm/kernels/cutlass_kernels/fp8_blockscale_gemm/fp8_blockscale_gemm.h"
#include "tensorrt_llm/kernels/cutlass_kernels/include/cutlass_kernel_selector.h"
#include "tensorrt_llm/kernels/lora/lora.h"
#include "tensorrt_llm/runtime/torchUtils.h"
#include "tensorrt_llm/thop/thUtils.h"
#include <ATen/native/cuda/Resize.h>
#include <functional>
#include <map>
#define C10_THROW_ERROR_FORMATTED(ErrorType, ...) \
do \
{ \
std::ostringstream oss; \
oss << __VA_ARGS__; \
C10_THROW_ERROR(ErrorType, oss.str()); \
} while (0)
TRTLLM_NAMESPACE_BEGIN
namespace torch_ext
{
namespace common = tensorrt_llm::common;
namespace kernels = CUTLASS_MOE_GEMM_KERNELS_NAMESPACE;
using ActivationParams = CUTLASS_MOE_GEMM_NAMESPACE::ActivationParams;
using ActivationType = CUTLASS_MOE_GEMM_NAMESPACE::ActivationType;
using MoeGemmId = CUTLASS_MOE_GEMM_NAMESPACE::MoeGemmId;
// Always use public header as it is just utility functions and types
using TmaWarpSpecializedGroupedGemmInput = tensorrt_llm::kernels::cutlass_kernels::TmaWarpSpecializedGroupedGemmInput;
using profiler_backend = CUTLASS_MOE_GEMM_KERNELS_NAMESPACE::GemmProfilerBackend;
// Mirrors tensorrt_llm::kernels::RequestType for the LoRA host_request_types layout.
// kCONTEXT/kGENERATION encoding matches the rest of the LoRA stack (e.g. loraOp.cpp).
enum class MoeLoraRequestType : int32_t
{
kCONTEXT = 0,
kGENERATION = 1
};
// ---------------------------------------------------------------------------
// libtorch-bound implementation of MoeLoraDeviceRunFn.
//
// This is the per-module GEMM dispatch the device LoRA path uses. It builds the
// per-token problem descriptors on device via the libtorch-free
// launchMoeLoraProblemBuilder, then dispatches cudaGraph(SplitK)GroupedGemm.
// The latter allocates workspace via at::Tensor, so this function must live in
// th_common, which links libtorch. moe_kernels.cu reaches it indirectly through
// the function pointer stored in LoraParams::device_path.run; that indirection
// keeps libmoe_gemm_src.a (also linked into the TensorRT plugin shared object)
// free of a transitive dependency on libtorch.
// ---------------------------------------------------------------------------
inline void moeLoraDeviceRunImpl(::tensorrt_llm::kernels::cutlass_kernels::MoeLoraDevicePathModule const& mod,
int64_t num_permuted_tokens, int64_t in_hidden_size, int64_t max_lora_rank, int64_t dtype_bytes,
int64_t splitk_slices, void const* input_base, void* output_base, nvinfer1::DataType data_type, cudaStream_t stream)
{
TLLM_CHECK_WITH_INFO(mod.permuted_ranks_dev != nullptr,
"Device-path LoRA module is missing permuted ranks buffer (forgot to populate device_path?).");
// Repack the device-resident scratch into the bundle the problem-builder
// consumes. The typed casts recover the concrete pointer types that
// MoeLoraDevicePathModule stores as void* for header decoupling.
::tensorrt_llm::kernels::cutlass_kernels::MoeLoraGemmGroupArrays arrays{};
arrays.problem_sizes_in = static_cast<cutlass::gemm::GemmCoord*>(mod.problem_sizes_in_dev);
arrays.problem_sizes_out = static_cast<cutlass::gemm::GemmCoord*>(mod.problem_sizes_out_dev);
arrays.a_ptrs_in = mod.a_ptrs_in_dev;
arrays.b_ptrs_in = mod.b_ptrs_in_dev;
arrays.d_ptrs_in = mod.d_ptrs_in_dev;
arrays.b_ptrs_out = mod.b_ptrs_out_dev;
arrays.d_ptrs_out = mod.d_ptrs_out_dev;
arrays.lda_in = mod.lda_in_dev;
arrays.ldb_in = mod.ldb_in_dev;
arrays.ldd_in = mod.ldd_in_dev;
arrays.ldb_out = mod.ldb_out_dev;
arrays.ldd_out = mod.ldd_out_dev;
arrays.splitk_offsets = mod.splitk_offsets_dev;
::tensorrt_llm::kernels::cutlass_kernels::launchMoeLoraProblemBuilder(mod.permuted_ranks_dev, mod.permuted_ptrs_dev,
input_base, mod.lowrank_workspace_dev, output_base, num_permuted_tokens, in_hidden_size, mod.out_hidden_size,
max_lora_rank, dtype_bytes, splitk_slices, arrays, stream);
sync_check_cuda_error(stream);
// The cuda_graph_(split_k_)grouped_gemm wrappers accept ldc == ldd when C
// aliases D (the no-bias case). The problem-builder produces a single
// ldd_in / ldd_out per stage, reused for ldcGpu below.
auto* host_max_in = static_cast<cutlass::gemm::GemmCoord*>(mod.host_max_problem_in_pinned);
auto* host_max_out = static_cast<cutlass::gemm::GemmCoord*>(mod.host_max_problem_out_pinned);
// kMinKN mirrors the value attention LoRA uses for kernel selection. The
// wrappers fall back to the smaller-tile family when min(K, N) < kMinKN.
constexpr int kMinKN = 16;
// In-GEMM (low-rank down-projection). Each problem is a single permuted
// token (M=1), so split-K over K offers no benefit. Use the plain grouped
// GEMM; the split-K grouped GEMM raises an illegal instruction on SM100 when
// reused within a process.
::tensorrt_llm::kernels::cudaGraphGroupedGemm(arrays.problem_sizes_in, static_cast<int>(num_permuted_tokens),
arrays.a_ptrs_in, arrays.b_ptrs_in, arrays.d_ptrs_in, arrays.d_ptrs_in, arrays.lda_in, arrays.ldb_in,
arrays.ldd_in, arrays.ldd_in,
/*isLoraIn=*/true, data_type, kMinKN, host_max_in, stream);
sync_check_cuda_error(stream);
::tensorrt_llm::kernels::cudaGraphGroupedGemm(arrays.problem_sizes_out, static_cast<int>(num_permuted_tokens),
arrays.d_ptrs_in /*== a_ptrs_out*/, arrays.b_ptrs_out, arrays.d_ptrs_out, arrays.d_ptrs_out, arrays.ldd_in,
arrays.ldb_out, arrays.ldd_out, arrays.ldd_out,
/*isLoraIn=*/false, data_type, kMinKN, host_max_out, stream);
sync_check_cuda_error(stream);
}
class FusedMoeRunner : public torch::CustomClassHolder
{
public:
template <typename TypeAct, typename TypeWeight, bool NeedQuant = false>
std::unique_ptr<kernels::CutlassMoeFCRunnerInterface> switch_output_type(c10::ScalarType output_type)
{
switch (output_type)
{
case c10::ScalarType::Long: // INT64 == FP4
case c10::ScalarType::Float8_e4m3fn:
// TODO We need an atomic FP8 reduction for the finalize fusions
C10_THROW_ERROR_FORMATTED(NotImplementedError,
"Outputting " << torch::toString(output_type) << " directly is not currently supported");
// return std::make_unique<kernels::CutlassMoeFCRunner<Type, Type>>();
case c10::ScalarType::Half:
if constexpr (NeedQuant)
{
return std::make_unique<kernels::CutlassMoeFCRunner<TypeAct, TypeWeight, half, half>>();
}
else
{
return std::make_unique<kernels::CutlassMoeFCRunner<TypeAct, TypeWeight, half, TypeAct>>();
}
#ifdef ENABLE_BF16
case c10::ScalarType::BFloat16:
if constexpr (NeedQuant)
{
return std::make_unique<
kernels::CutlassMoeFCRunner<TypeAct, TypeWeight, __nv_bfloat16, __nv_bfloat16>>();
}
else
{
return std::make_unique<kernels::CutlassMoeFCRunner<TypeAct, TypeWeight, __nv_bfloat16, TypeAct>>();
}
#endif
default:
C10_THROW_ERROR_FORMATTED(Error,
"Invalid output type " << torch::toString(output_type) << " specified for "
<< torch::toString(mActivationDtype));
}
};
template <typename TypeAct>
std::unique_ptr<kernels::CutlassMoeFCRunnerInterface> create_weight_quant_runner()
{
if (isInt8Quant())
{
return std::make_unique<kernels::CutlassMoeFCRunner<TypeAct, uint8_t>>();
}
else if (isInt4Quant())
{
#ifdef ENABLE_FP8
if (mUseW4GroupScaling)
{
return std::make_unique<
kernels::CutlassMoeFCRunner<__nv_fp8_e4m3, cutlass::uint4b_t, TypeAct, TypeAct>>();
}
#endif
return std::make_unique<kernels::CutlassMoeFCRunner<TypeAct, cutlass::uint4b_t>>();
}
else
{
C10_THROW_ERROR_FORMATTED(Error, "Unsupported weight quantization type");
}
}
FusedMoeRunner(c10::ScalarType activation_dtype, c10::ScalarType weight_dtype, c10::ScalarType output_dtype,
bool use_deepseek_fp8_block_scale, bool use_w4_group_scaling, bool use_int8_woq_per_channel,
bool use_mxfp8_act_scaling, bool use_fused_finalize)
{
mActivationDtype = activation_dtype;
mWeightDtype = weight_dtype;
mOutputDtype = output_dtype;
mUseDeepSeekFP8BlockScaling = use_deepseek_fp8_block_scale;
mUseW4GroupScaling = use_w4_group_scaling;
mUseINT8WoqPerChannel = use_int8_woq_per_channel;
mUseMxfp8ActScaling = use_mxfp8_act_scaling;
mUseFusedFinalize = use_fused_finalize;
mInnerDimMultiplier = 1;
// keep consistent with cpp/tensorrt_llm/plugins/mixtureOfExperts/mixtureOfExpertsPlugin.cpp
if (mActivationDtype == c10::ScalarType::Half && mWeightDtype == c10::ScalarType::Half)
{
mKernelRunner = std::make_shared<kernels::CutlassMoeFCRunner<half, half>>();
}
#ifdef ENABLE_BF16
else if (mActivationDtype == c10::ScalarType::BFloat16 && mWeightDtype == c10::ScalarType::BFloat16)
{
mKernelRunner = std::make_shared<kernels::CutlassMoeFCRunner<__nv_bfloat16, __nv_bfloat16>>();
}
#ifdef ENABLE_FP8
else if (mActivationDtype == c10::ScalarType::BFloat16 && mWeightDtype == c10::ScalarType::Float8_e4m3fn)
{
mKernelRunner = std::make_unique<kernels::CutlassMoeFCRunner<__nv_bfloat16, __nv_fp8_e4m3>>();
}
#endif
#endif
#ifdef ENABLE_FP8
if (isFp8Quant())
{
mKernelRunner = switch_output_type<__nv_fp8_e4m3, __nv_fp8_e4m3>(mOutputDtype);
}
#endif
#ifdef ENABLE_FP4
if (isWMxfp4AMxfp8Quant() || isWMxfp4AFp8Quant())
{
mInnerDimMultiplier = 16; // 16 FP4 -> 1 LONG
mKernelRunner = switch_output_type<__nv_fp8_e4m3, __nv_fp4_e2m1>(mOutputDtype);
}
if (isNvfp4Quant())
{
mInnerDimMultiplier = 16; // 16 FP4 -> 1 LONG
switch (mActivationDtype)
{
case c10::ScalarType::Half:
#ifdef ENABLE_BF16
case c10::ScalarType::BFloat16:
#endif
mKernelRunner = switch_output_type<__nv_fp4_e2m1, __nv_fp4_e2m1, true>(mOutputDtype);
break;
default: mKernelRunner = switch_output_type<__nv_fp4_e2m1, __nv_fp4_e2m1, false>(mOutputDtype);
}
}
if (isWFP4A16Quant())
{
mInnerDimMultiplier = 2;
if (mActivationDtype == c10::ScalarType::Half)
{
mKernelRunner = std::make_shared<kernels::CutlassMoeFCRunner<half, __nv_fp4_e2m1>>();
}
#ifdef ENABLE_BF16
else if (mActivationDtype == c10::ScalarType::BFloat16)
{
mKernelRunner = std::make_shared<kernels::CutlassMoeFCRunner<__nv_bfloat16, __nv_fp4_e2m1>>();
}
#endif
}
#endif
if (isIntWeightOnlyQuant())
{
if (isInt4Quant())
{
mInnerDimMultiplier = 2; // 2 INT4 -> 1 INT8
}
switch (mActivationDtype)
{
#ifdef ENABLE_FP8
case c10::ScalarType::Float8_e4m3fn:
{
if (isInt4Quant() and mUseW4GroupScaling)
{
mKernelRunner = std::make_unique<
kernels::CutlassMoeFCRunner<__nv_fp8_e4m3, cutlass::uint4b_t, __nv_bfloat16, __nv_fp8_e4m3>>();
}
else
{
C10_THROW_ERROR_FORMATTED(Error, "FP8 activation type is not supported for non-W4A8 quantization");
}
break;
}
#endif
case c10::ScalarType::Half: mKernelRunner = create_weight_quant_runner<half>(); break;
case c10::ScalarType::BFloat16: mKernelRunner = create_weight_quant_runner<__nv_bfloat16>(); break;
default: C10_THROW_ERROR_FORMATTED(Error, "Unsupported activation type for int-type weight");
}
}
if (!mKernelRunner)
{
C10_THROW_ERROR_FORMATTED(Error,
"Could not construct fused moe op with the requested input combination Activation: "
<< torch::toString(mActivationDtype) << ", Weight: " << torch::toString(mWeightDtype)
<< ", Output: " << torch::toString(mOutputDtype));
}
mKernelRunner->use_fused_finalize_ = mUseFusedFinalize;
mProfiler = std::make_shared<kernels::GemmProfilerBackend>();
mGemm1Profiles = mKernelRunner->getTactics(MoeGemmId::GEMM_1);
mGemm2Profiles = mKernelRunner->getTactics(MoeGemmId::GEMM_2);
cuInit(0);
// Device-LoRA-path opt-in for the per-request (eager) schema. Any
// non-empty value other than "0"/"OFF"/"off" enables it, matching
// LORA_USE_UNIFIED_GEMM. The slot-indexed (CUDA-graph) schema always
// uses the device path regardless, since the host path is not
// capturable (it does a host-side cudaEventSynchronize).
if (char const* envv = std::getenv("TLLM_MOE_LORA_USE_DEVICE_PATH"))
{
std::string val(envv);
mUseDeviceLoraPath = !val.empty() && val != "0" && val != "OFF" && val != "off";
}
}
~FusedMoeRunner()
{
if (mProfileWorkspace != nullptr)
{
auto const cu_free_status = cudaFree(mProfileWorkspace);
TORCH_CHECK(
cu_free_status == cudaSuccess, "Can't free profile workspace during FusedMoeRunner destruction.");
}
if (mLoraMemcpyEvent != nullptr)
{
// Destruction is best-effort; do not throw from the destructor.
(void) cudaEventDestroy(mLoraMemcpyEvent);
mLoraMemcpyEvent = nullptr;
}
}
FusedMoeRunner(FusedMoeRunner const&) = delete;
void operator=(FusedMoeRunner const&) = delete;
// Release internal workspace buffers to free GPU memory.
// Workspaces will be re-allocated on the next runMoe/runGemmProfile call.
void clearWorkspaces()
{
std::lock_guard<std::mutex> lock(mMutex);
mStreamWorkspaces.clear();
freeProfileWorkspace();
// LoraImpl objects retain non-trivial cuBLAS state; drop the cache so the
// next LoRA call re-builds them. The shared cuBLAS wrapper is kept.
mLoraImplCache.clear();
}
torch::Tensor runMoe(torch::Tensor const& input, torch::Tensor const& token_selected_experts,
torch::optional<torch::Tensor> const& token_final_scales, torch::Tensor const& fc1_expert_weights,
torch::optional<torch::Tensor> const& fc1_expert_biases, torch::Tensor const& fc2_expert_weights,
torch::optional<torch::Tensor> const& fc2_expert_biases,
torch::optional<c10::ArrayRef<torch::Tensor>> const& quant_scales,
torch::optional<torch::Tensor> const& input_sf, bool const swizzled_input_sf,
torch::optional<torch::Tensor> const& swiglu_alpha, torch::optional<torch::Tensor> const& swiglu_beta,
torch::optional<torch::Tensor> const& swiglu_limit, int64_t const tp_size, int64_t const tp_rank,
int64_t const ep_size, int64_t const ep_rank, int64_t const cluster_size, int64_t const cluster_rank,
bool const enable_alltoall, bool min_latency_mode, torch::optional<c10::ArrayRef<int64_t>> const& profile_ids,
torch::optional<int64_t> const& activation_type, torch::optional<int64_t> const& unpadded_hidden_size,
torch::optional<int64_t> const& num_valid_tokens, torch::optional<torch::Tensor> const& out_tensor,
bool use_dynamic_fc2_scale = false,
// Routed-expert LoRA inputs (all optional; presence of fc1_lora_ranks activates LoRA).
// Each *_ranks : CPU int32 [num_seqs]
// Each *_weights : CPU int64 [num_seqs, 3], holding (A_ptr, B_ptr, DoRA_ptr); DoRA unused.
torch::optional<torch::Tensor> const& fc1_lora_ranks = torch::nullopt,
torch::optional<torch::Tensor> const& fc1_lora_weight_ptrs = torch::nullopt,
torch::optional<torch::Tensor> const& fc2_lora_ranks = torch::nullopt,
torch::optional<torch::Tensor> const& fc2_lora_weight_ptrs = torch::nullopt,
torch::optional<torch::Tensor> const& gated_lora_ranks = torch::nullopt,
torch::optional<torch::Tensor> const& gated_lora_weight_ptrs = torch::nullopt,
torch::optional<torch::Tensor> const& host_request_types = torch::nullopt,
torch::optional<torch::Tensor> const& host_context_lengths = torch::nullopt, int64_t lora_max_low_rank = 0,
// Slot-indexed CUDA-graph LoRA inputs (mutually exclusive with the per-request
// schema above). When fc1_slot_lora_ranks is provided, the per-token expansion
// is performed inside the op via token_to_slot[t] indexed into the slot tables.
// slot_*_ranks : CPU pinned int32 [max_lora_size]
// slot_*_weight_ptrs : CPU pinned int64 [max_lora_size, 3] (A, B, dora-ignored)
// token_to_slot : CPU pinned int32 [>= num_tokens]
torch::optional<torch::Tensor> const& fc1_slot_lora_ranks = torch::nullopt,
torch::optional<torch::Tensor> const& fc1_slot_lora_weight_ptrs = torch::nullopt,
torch::optional<torch::Tensor> const& fc2_slot_lora_ranks = torch::nullopt,
torch::optional<torch::Tensor> const& fc2_slot_lora_weight_ptrs = torch::nullopt,
torch::optional<torch::Tensor> const& gated_slot_lora_ranks = torch::nullopt,
torch::optional<torch::Tensor> const& gated_slot_lora_weight_ptrs = torch::nullopt,
torch::optional<torch::Tensor> const& token_to_slot = torch::nullopt)
{
std::lock_guard<std::mutex> lock(mMutex);
// Free the profile workspace to save memory
freeProfileWorkspace();
TORCH_CHECK(cluster_size == 1 && cluster_rank == 0, "smart_router is supported in min_latency mode");
CHECK_INPUT(input, mActivationDtype)
CHECK_INPUT(token_selected_experts, at::ScalarType::Int)
if (token_final_scales)
{
CHECK_INPUT(token_final_scales.value(), at::ScalarType::Float)
}
CHECK_INPUT(fc1_expert_weights, mWeightDtype)
CHECK_INPUT(fc2_expert_weights, mWeightDtype)
TORCH_CHECK(input.dim() == 2, "input must be 2D.");
TORCH_CHECK(token_selected_experts.dim() == 2, "token_selected_experts must be 2D.");
TORCH_CHECK(fc1_expert_weights.dim() == 3, "fc1_expert_weights must be 3D.");
TORCH_CHECK(fc2_expert_weights.dim() == 3, "fc2_expert_weights must be 3D.");
if (fc1_expert_biases.has_value() || fc2_expert_biases.has_value())
{
CHECK_INPUT(fc1_expert_biases.value(), mOutputDtype);
CHECK_INPUT(fc2_expert_biases.value(), mOutputDtype);
TORCH_CHECK(fc1_expert_biases.value().dim() == 2, "fc1_expert_biases must be 2D.");
TORCH_CHECK(fc2_expert_biases.value().dim() == 2, "fc2_expert_biases must be 2D.");
TORCH_CHECK(fc1_expert_weights.sizes()[0] == fc1_expert_biases.value().sizes()[0],
"fc1_expert_weights and fc1_expert_biases must have the same number of experts.");
TORCH_CHECK(fc2_expert_weights.sizes()[0] == fc2_expert_biases.value().sizes()[0],
"fc2_expert_weights and fc2_expert_biases must have the same number of experts.");
TORCH_CHECK(fc1_expert_biases.value().sizes()[1] == fc1_expert_weights.sizes()[1],
"fc1_expert_biases should match fc1_expert_weights output shape.");
TORCH_CHECK(fc2_expert_biases.value().sizes()[1] == fc2_expert_weights.sizes()[1],
"fc2_expert_biases should match fc2_expert_weights output shape.");
}
if (fc1_expert_biases.has_value() || fc2_expert_biases.has_value())
{
CHECK_INPUT(fc1_expert_biases.value(), mOutputDtype);
CHECK_INPUT(fc2_expert_biases.value(), mOutputDtype);
TORCH_CHECK(fc1_expert_biases.value().dim() == 2, "fc1_expert_biases must be 2D.");
TORCH_CHECK(fc2_expert_biases.value().dim() == 2, "fc2_expert_biases must be 2D.");
TORCH_CHECK(fc1_expert_weights.sizes()[0] == fc1_expert_biases.value().sizes()[0],
"fc1_expert_weights and fc1_expert_biases must have the same number of experts.");
TORCH_CHECK(fc2_expert_weights.sizes()[0] == fc2_expert_biases.value().sizes()[0],
"fc2_expert_weights and fc2_expert_biases must have the same number of experts.");
TORCH_CHECK(fc1_expert_biases.value().sizes()[1] == fc1_expert_weights.sizes()[1],
"fc1_expert_biases should match fc1_expert_weights output shape.");
TORCH_CHECK(fc2_expert_biases.value().sizes()[1] == fc2_expert_weights.sizes()[1],
"fc2_expert_biases should match fc2_expert_weights output shape.");
}
TORCH_CHECK(input.sizes()[0] == token_selected_experts.sizes()[0],
"input and token_selected_experts must have the same num tokens.");
if (token_final_scales)
{
TORCH_CHECK(token_final_scales.value().dim() == 2, "token_selected_experts_probs must be 2D.");
TORCH_CHECK(input.sizes()[0] == token_final_scales.value().sizes()[0],
"input and token_selected_experts_probs must have the same num tokens.");
TORCH_CHECK(token_selected_experts.sizes()[1] == token_final_scales.value().sizes()[1],
"token_selected_experts and token_final_scales must have the same number of experts per token.");
}
TORCH_CHECK(fc1_expert_weights.sizes()[0] == fc2_expert_weights.sizes()[0],
"fc1_expert_weights and fc2_expert_weights must have the same number of experts.");
ActivationType base_activation_type = activation_type.has_value()
? static_cast<ActivationType>(activation_type.value())
: ActivationType::Swiglu;
if (mUseINT8WoqPerChannel)
{
// Note: The weight shape for INT8 weight only quantization is different, e.g., fc2_expert_weights:
// [num_experts, inter_size, hidden_size]
// Mirror the non-woq else-branch below: gated activations (Swiglu/Geglu) require fc1's
// intermediate dim to be 2x fc2's (one half each for gate and up), while non-gated
// activations (Relu2/Identity/ReLU/SiLU/Gelu, e.g. Nemotron-H) require them to be equal.
if (isGatedActivation(base_activation_type))
{
TORCH_CHECK(fc1_expert_weights.sizes()[2] == fc2_expert_weights.sizes()[1] * mInnerDimMultiplier * 2,
"fc1_expert_weights inter size must be 2 times fc2_expert_weights inter size.");
}
else
{
TORCH_CHECK(fc1_expert_weights.sizes()[2] == fc2_expert_weights.sizes()[1] * mInnerDimMultiplier,
"fc1_expert_weights inter size must be equal to fc2_expert_weights inter size.");
}
}
else
{
if (isGatedActivation(base_activation_type))
{
TORCH_CHECK(fc1_expert_weights.sizes()[1] == fc2_expert_weights.sizes()[2] * mInnerDimMultiplier * 2,
"fc1_expert_weights inter size must be 2 times fc2_expert_weights inter size.");
}
else
{
TORCH_CHECK(fc1_expert_weights.sizes()[1] == fc2_expert_weights.sizes()[2] * mInnerDimMultiplier,
"fc1_expert_weights inter size must be equal to fc2_expert_weights inter size.");
}
}
int experts_per_token = token_selected_experts.sizes()[1];
int64_t num_rows = input.sizes()[0];
int64_t hidden_size = fc2_expert_weights.sizes()[1];
int64_t unpadded_hidden_size_val
= unpadded_hidden_size.has_value() ? unpadded_hidden_size.value() : hidden_size;
int64_t inter_size = fc2_expert_weights.sizes()[2] * mInnerDimMultiplier;
if (mUseINT8WoqPerChannel)
{
// Note: The weight shape for INT8 weight only quantization is different, e.g., fc2_expert_weights:
// [num_experts, inter_size, hidden_size]
hidden_size = fc2_expert_weights.sizes()[2] * mInnerDimMultiplier;
inter_size = fc2_expert_weights.sizes()[1];
}
if (isWMxfp4AMxfp8Quant() || isWMxfp4AFp8Quant())
{
// MXFP4 weights are required to bealigned to 128 bytes
TORCH_CHECK(hidden_size % 128 == 0, "hidden_size must be divisible by 128 for MXFP4 weights");
TORCH_CHECK(inter_size % 128 == 0, "inter_size must be divisible by 128 for MXFP4 weights");
}
else
{
// TMA requires at least 128 bit alignment
auto min_alignment
= 128 / (8 * std::min(c10::elementSize(mActivationDtype), c10::elementSize(mWeightDtype)));
TORCH_CHECK(hidden_size % min_alignment == 0, "hidden_size ", hidden_size, " must be divisible by ",
min_alignment, " for weights");
TORCH_CHECK(inter_size % min_alignment == 0, "inter_size ", inter_size, " must be divisible by ",
min_alignment, " for weights");
}
int const num_experts_on_rank = fc2_expert_weights.sizes()[0];
auto const num_experts_total = static_cast<int>(num_experts_on_rank * ep_size);
auto parallelism_config = kernels::MOEParallelismConfig(tp_size, tp_rank, ep_size, ep_rank);
if (swiglu_alpha.has_value())
{
CHECK_INPUT(swiglu_alpha.value(), at::ScalarType::Float);
TORCH_CHECK(swiglu_alpha.value().sizes()[0] == num_experts_on_rank,
"swiglu_alpha must have num_experts_on_rank elements.");
base_activation_type = ActivationType::SwigluBias;
}
if (swiglu_beta.has_value())
{
CHECK_INPUT(swiglu_beta.value(), at::ScalarType::Float);
TORCH_CHECK(swiglu_beta.value().sizes()[0] == num_experts_on_rank,
"swiglu_beta must have num_experts_on_rank elements.");
base_activation_type = ActivationType::SwigluBias;
}
if (swiglu_limit.has_value())
{
CHECK_INPUT(swiglu_limit.value(), at::ScalarType::Float);
TORCH_CHECK(swiglu_limit.value().sizes()[0] == num_experts_on_rank,
"swiglu_limit must have num_experts_on_rank elements.");
base_activation_type = ActivationType::SwigluBias;
}
auto activation_params = ActivationParams(base_activation_type,
reinterpret_cast<float const*>(swiglu_alpha.has_value() ? swiglu_alpha.value().const_data_ptr() : nullptr),
reinterpret_cast<float const*>(swiglu_beta.has_value() ? swiglu_beta.value().const_data_ptr() : nullptr),
reinterpret_cast<float const*>(swiglu_limit.has_value() ? swiglu_limit.value().const_data_ptr() : nullptr));
setRunnerProfiles(profile_ids);
auto stream = at::cuda::getCurrentCUDAStream(input.get_device());
std::vector<int64_t> output_shape = {num_rows, unpadded_hidden_size_val};
torch::Tensor output;
if (out_tensor.has_value())
{
auto const& provided = out_tensor.value();
CHECK_INPUT(provided, mOutputDtype);
TORCH_CHECK(provided.sizes() == output_shape, "Provided out tensor has incorrect shape. Expected ",
output_shape, ", got ", provided.sizes());
output = provided;
}
else
{
output = torch::empty(output_shape, input.options().dtype(mOutputDtype));
}
// ===== Routed-expert LoRA setup =====
// LoRA is activated by the per-request schema (fc1_lora_ranks).
bool const lora_per_request = fc1_lora_ranks.has_value();
bool const lora_slot_indexed = fc1_slot_lora_ranks.has_value();
bool const lora_active = lora_per_request || lora_slot_indexed;
bool const is_gated_act = isGatedActivation(base_activation_type);
if (lora_active)
{
// The per-request and slot-indexed schemas are mutually exclusive:
// each drives a different token->adapter expansion inside
// buildMoeLoraParams, and supplying both is ambiguous. The Python
// wrapper (torch_custom_ops.fused_moe) rejects this too, but the op
// is public, so enforce it here as well for direct C++/op callers.
TORCH_CHECK(!(lora_per_request && lora_slot_indexed),
"MoE LoRA: the per-request (fc1_lora_ranks, ...) and slot-indexed (fc1_slot_lora_ranks, ..., "
"token_to_slot) input schemas are mutually exclusive. Provide exactly one, not both.");
// Conservative rejections (min-latency, alltoall, quant, graph capture).
TORCH_CHECK(!min_latency_mode, "MoE LoRA is not supported in min-latency mode.");
TORCH_CHECK(!enable_alltoall,
"MoE LoRA is not supported with alltoall: the per-token adapter pointer arrays do not survive "
"cross-rank token reshuffling.");
TORCH_CHECK(mActivationDtype == c10::ScalarType::Half || mActivationDtype == c10::ScalarType::BFloat16,
"MoE LoRA only supports fp16 and bf16 activation dtypes.");
TORCH_CHECK(mWeightDtype == c10::ScalarType::Half || mWeightDtype == c10::ScalarType::BFloat16,
"MoE LoRA only supports unquantized fp16/bf16 expert weights.");
// CUDA-graph capture is only safe on the device LoRA path. The
// legacy host path performs a host-side cudaEventSynchronize and
// per-token pointer expansion in setupLoraWorkspace, plus host-side
// run-length encoding in LoraImpl::run, none of which is capturable.
// The device path (launchMoeLoraPointerExpand and
// runMoeLoraDeviceModule in moe_kernels.cu) runs entirely on the
// stream. The slot-indexed schema implies the device path (see the
// constructor's activation-story comment), so capture is allowed
// whenever the device path will be taken: env-var opt-in OR
// slot-indexed inputs.
bool const use_device_path = mUseDeviceLoraPath || lora_slot_indexed;
TORCH_CHECK(use_device_path || !tensorrt_llm::common::isCapturing(stream),
"MoE LoRA + CUDA graph capture requires the device LoRA path. The per-request schema runs "
"the legacy host path by default, which performs a host-side cudaEventSynchronize after a "
"D2H pointer-expansion copy and is not capturable. Use the slot-indexed schema (which always "
"takes the device path), set TLLM_MOE_LORA_USE_DEVICE_PATH=1, run LoRA eagerly, or disable "
"MoE LoRA when capturing.");
}
// Build LoraParams up-front so we can compute the required cuBLAS workspace before allocation.
auto lora_params_opt = buildMoeLoraParams(fc1_lora_ranks, fc1_lora_weight_ptrs, fc2_lora_ranks,
fc2_lora_weight_ptrs, gated_lora_ranks, gated_lora_weight_ptrs, host_request_types, host_context_lengths,
fc1_slot_lora_ranks, fc1_slot_lora_weight_ptrs, fc2_slot_lora_ranks, fc2_slot_lora_weight_ptrs,
gated_slot_lora_ranks, gated_slot_lora_weight_ptrs, token_to_slot,
/*num_tokens=*/num_rows, hidden_size, inter_size, mActivationDtype, lora_max_low_rank, is_gated_act, stream,
static_cast<int>(experts_per_token));
size_t lora_workspace_size = 0;
// The device path uses persistent device scratch and never touches the
// legacy cuBLAS lora_workspace, so skip computing/allocating it there to
// avoid duplicating LoRA scratch per stream (and the resulting OOM risk
// at large top_k/rank).
if (lora_params_opt.has_value() && !lora_params_opt->device_path.enabled)
{
auto const lora_dtype = loraTypeFromActDtype(mActivationDtype);
lora_workspace_size = computeLoraWorkspaceSize(lora_params_opt->fc1_lora_impl,
lora_params_opt->fc2_lora_impl, num_rows, experts_per_token, lora_params_opt->num_reqs, lora_dtype);
}
WorkspaceInfo const& workspace_info = getWorkspaceInfo(num_rows, hidden_size, inter_size, num_experts_total,
static_cast<int>(experts_per_token), base_activation_type, parallelism_config, min_latency_mode, stream,
lora_active, lora_workspace_size);
auto quant_params
= getQuantParams(num_experts_on_rank, hidden_size, inter_size, quant_scales, base_activation_type);
// Dynamic fc2 scale: allocate workspace buffers
at::Tensor dynamic_fc2_amax_tensor, dynamic_fc2_alpha_tensor, dynamic_fc2_bf16_tensor;
if (use_dynamic_fc2_scale && isNvfp4Quant() && quant_scales.has_value() && quant_scales.value().size() >= 7)
{
auto opts_f32 = at::TensorOptions().dtype(at::ScalarType::Float).device(input.device());
auto opts_bf16 = at::TensorOptions().dtype(at::ScalarType::BFloat16).device(input.device());
dynamic_fc2_amax_tensor = at::empty({1}, opts_f32);
dynamic_fc2_alpha_tensor = at::empty({num_experts_on_rank}, opts_f32);
int64_t expanded_rows = num_rows * static_cast<int64_t>(experts_per_token);
dynamic_fc2_bf16_tensor = at::empty({expanded_rows, inter_size}, opts_bf16);
quant_params.fp4.dynamic_fc2_input_scale.enabled = true;
quant_params.fp4.dynamic_fc2_input_scale.amax = dynamic_fc2_amax_tensor.data_ptr<float>();
quant_params.fp4.dynamic_fc2_input_scale.alpha = dynamic_fc2_alpha_tensor.data_ptr<float>();
quant_params.fp4.dynamic_fc2_input_scale.bf16_buffer = dynamic_fc2_bf16_tensor.data_ptr();
// 7th element: per-expert fc2_weight_scale_2 passed directly from Python
quant_params.fp4.dynamic_fc2_input_scale.weight_scale_2
= static_cast<float const*>(quant_scales.value()[6].data_ptr());
}
kernels::MoeMinLatencyParams min_latency_params{};
// LoraParams is either the populated one we just built or a default-constructed empty one (use_lora=false).
::tensorrt_llm::kernels::LoraParams lora_params
= lora_params_opt.value_or(::tensorrt_llm::kernels::LoraParams{});
if (lora_active && !lora_params.device_path.enabled)
{
lora_params.workspace = workspace_info.lora_workspace;
}
#ifdef USING_OSS_CUTLASS_MOE_GEMM
mKernelRunner->runMoe(input.const_data_ptr(),
input_sf.has_value() ? input_sf.value().const_data_ptr() : nullptr, swizzled_input_sf,
reinterpret_cast<int const*>(token_selected_experts.const_data_ptr()),
token_final_scales.has_value() ? reinterpret_cast<float const*>(token_final_scales.value().const_data_ptr())
: nullptr,
fc1_expert_weights.const_data_ptr(),
fc1_expert_biases.has_value() ? fc1_expert_biases.value().const_data_ptr() : nullptr, activation_params,
fc2_expert_weights.const_data_ptr(),
fc2_expert_biases.has_value() ? fc2_expert_biases.value().const_data_ptr() : nullptr, quant_params,
num_rows, num_valid_tokens.has_value() ? num_valid_tokens.value() : num_rows, hidden_size,
unpadded_hidden_size_val, inter_size, num_experts_total, static_cast<int>(experts_per_token),
static_cast<char*>(workspace_info.workspace.data_ptr()), output.data_ptr(),
static_cast<int*>(workspace_info.src_to_dest_map), parallelism_config, enable_alltoall, lora_active,
lora_params, mUseDeepSeekFP8BlockScaling, min_latency_mode, min_latency_params, stream);
#else
mKernelRunner->runMoe(input.const_data_ptr(),
input_sf.has_value() ? input_sf.value().const_data_ptr() : nullptr, swizzled_input_sf,
reinterpret_cast<int const*>(token_selected_experts.const_data_ptr()),
token_final_scales.has_value() ? reinterpret_cast<float const*>(token_final_scales.value().const_data_ptr())
: nullptr,
fc1_expert_weights.const_data_ptr(),
fc1_expert_biases.has_value() ? fc1_expert_biases.value().const_data_ptr() : nullptr, activation_params,
fc2_expert_weights.const_data_ptr(),
fc2_expert_biases.has_value() ? fc2_expert_biases.value().const_data_ptr() : nullptr, quant_params,
num_rows, num_valid_tokens.has_value() ? num_valid_tokens.value() : num_rows, hidden_size, inter_size,
num_experts_total, static_cast<int>(experts_per_token),
static_cast<char*>(workspace_info.workspace.data_ptr()), output.data_ptr(),
static_cast<int*>(workspace_info.src_to_dest_map), parallelism_config, lora_active, lora_params,
mUseDeepSeekFP8BlockScaling, min_latency_mode, min_latency_params, stream);
#endif
return output;
}
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor> runMoeMinLantency(torch::Tensor const& input,
torch::Tensor const& token_selected_experts, torch::optional<torch::Tensor> const& token_final_scales,
torch::Tensor const& fc1_expert_weights, torch::optional<torch::Tensor> const& fc1_expert_biases,
torch::Tensor const& fc2_expert_weights, torch::optional<torch::Tensor> const& fc2_expert_biases,
torch::optional<c10::ArrayRef<torch::Tensor>> const& quant_scales,
torch::optional<torch::Tensor> const& input_sf, bool const swizzled_input_sf,
torch::optional<torch::Tensor> const& swiglu_alpha, torch::optional<torch::Tensor> const& swiglu_beta,
torch::optional<torch::Tensor> const& swiglu_limit, int64_t const tp_size, int64_t const tp_rank,
int64_t const ep_size, int64_t const ep_rank, int64_t const cluster_size, int64_t const cluster_rank,
bool const enable_alltoall, bool min_latency_mode, torch::optional<c10::ArrayRef<int64_t>> const& profile_ids,
torch::optional<int64_t> const& activation_type, torch::optional<int64_t> const& unpadded_hidden_size,
torch::optional<int64_t> const& num_valid_tokens, torch::optional<torch::Tensor> const& out_tensor)
{
std::lock_guard<std::mutex> lock(mMutex);
// Free the profile workspace to save memory
freeProfileWorkspace();
CHECK_INPUT(input, mActivationDtype)
CHECK_INPUT(token_selected_experts, at::ScalarType::Int)
if (token_final_scales)
{
CHECK_INPUT(token_final_scales.value(), at::ScalarType::Float)
}
CHECK_INPUT(fc1_expert_weights, mWeightDtype)
CHECK_INPUT(fc2_expert_weights, mWeightDtype)
TORCH_CHECK(input.dim() == 2, "input must be 2D.");
TORCH_CHECK(token_selected_experts.dim() == 2, "token_selected_experts must be 2D.");
TORCH_CHECK(fc1_expert_weights.dim() == 3, "fc1_expert_weights must be 3D.");
TORCH_CHECK(fc2_expert_weights.dim() == 3, "fc2_expert_weights must be 3D.");
if (fc1_expert_biases.has_value() || fc2_expert_biases.has_value())
{
CHECK_INPUT(fc1_expert_biases.value(), mOutputDtype);
CHECK_INPUT(fc2_expert_biases.value(), mOutputDtype);
TORCH_CHECK(fc1_expert_biases.value().dim() == 2, "fc1_expert_biases must be 2D.");
TORCH_CHECK(fc2_expert_biases.value().dim() == 2, "fc2_expert_biases must be 2D.");
TORCH_CHECK(fc1_expert_weights.sizes()[0] == fc1_expert_biases.value().sizes()[0],
"fc1_expert_weights and fc1_expert_biases must have the same number of experts.");
TORCH_CHECK(fc2_expert_weights.sizes()[0] == fc2_expert_biases.value().sizes()[0],
"fc2_expert_weights and fc2_expert_biases must have the same number of experts.");
TORCH_CHECK(fc1_expert_biases.value().sizes()[1] == fc1_expert_weights.sizes()[1],
"fc1_expert_biases should match fc1_expert_weights output shape.");
TORCH_CHECK(fc2_expert_biases.value().sizes()[1] == fc2_expert_weights.sizes()[1],
"fc2_expert_biases should match fc2_expert_weights output shape.");
}
TORCH_CHECK(input.sizes()[0] == token_selected_experts.sizes()[0],
"input and token_selected_experts must have the same num tokens.");
if (token_final_scales)
{
TORCH_CHECK(token_final_scales.value().dim() == 2, "token_selected_experts_probs must be 2D.");
TORCH_CHECK(input.sizes()[0] == token_final_scales.value().sizes()[0],
"input and token_selected_experts_probs must have the same num tokens.");
TORCH_CHECK(token_selected_experts.sizes()[1] == token_final_scales.value().sizes()[1],
"token_selected_experts and token_final_scales must have the same number of experts per token.");
}
TORCH_CHECK(fc1_expert_weights.sizes()[0] == fc2_expert_weights.sizes()[0],
"fc1_expert_weights and fc2_expert_weights must have the same number of experts.");
TORCH_CHECK(!input_sf.has_value() || isWMxfp4AMxfp8Quant() || isNvfp4Quant(),
"Block-scaling factors provided for non block-scaling quantization");
int experts_per_token = token_selected_experts.sizes()[1];
int64_t num_rows = input.sizes()[0];
int64_t hidden_size = fc2_expert_weights.sizes()[1];
int64_t unpadded_hidden_size_val
= unpadded_hidden_size.has_value() ? unpadded_hidden_size.value() : hidden_size;
int64_t inter_size = fc2_expert_weights.sizes()[2] * mInnerDimMultiplier;
int const num_experts_on_rank = fc2_expert_weights.sizes()[0];
auto const num_experts_total = static_cast<int>(num_experts_on_rank * ep_size);
auto parallelism_config
= kernels::MOEParallelismConfig(tp_size, tp_rank, ep_size, ep_rank, cluster_size, cluster_rank);
ActivationType base_activation_type = activation_type.has_value()
? static_cast<ActivationType>(activation_type.value())
: ActivationType::Swiglu;
if (swiglu_alpha.has_value())
{
CHECK_INPUT(swiglu_alpha.value(), at::ScalarType::Float);
TORCH_CHECK(swiglu_alpha.value().sizes()[0] == num_experts_on_rank,
"swiglu_alpha must have num_experts_on_rank elements.");
base_activation_type = ActivationType::SwigluBias;
}
if (swiglu_beta.has_value())
{
CHECK_INPUT(swiglu_beta.value(), at::ScalarType::Float);
TORCH_CHECK(swiglu_beta.value().sizes()[0] == num_experts_on_rank,
"swiglu_beta must have num_experts_on_rank elements.");
base_activation_type = ActivationType::SwigluBias;
}
if (swiglu_limit.has_value())
{
CHECK_INPUT(swiglu_limit.value(), at::ScalarType::Float);
TORCH_CHECK(swiglu_limit.value().sizes()[0] == num_experts_on_rank,
"swiglu_limit must have num_experts_on_rank elements.");
base_activation_type = ActivationType::SwigluBias;
}
auto activation_params = ActivationParams(base_activation_type,
reinterpret_cast<float const*>(swiglu_alpha.has_value() ? swiglu_alpha.value().const_data_ptr() : nullptr),
reinterpret_cast<float const*>(swiglu_beta.has_value() ? swiglu_beta.value().const_data_ptr() : nullptr),
reinterpret_cast<float const*>(swiglu_limit.has_value() ? swiglu_limit.value().const_data_ptr() : nullptr));
// Validate the fc1/fc2 inter-size relationship now that the activation type (gated vs
// non-gated) is finalized. INT8-woq uses a transposed weight layout, so its fc1/fc2 dim
// ordering differs from the non-woq path; both mirror the gated/non-gated split used in
// runMoe(). Gated activations (Swiglu/Geglu) require fc1's intermediate dim to be 2x fc2's;
// non-gated (Relu2/Identity/ReLU/SiLU/Gelu, e.g. Nemotron-H) require them to be equal.
if (mUseINT8WoqPerChannel)
{
if (isGatedActivation(base_activation_type))
{
TORCH_CHECK(fc1_expert_weights.sizes()[2] == fc2_expert_weights.sizes()[1] * mInnerDimMultiplier * 2,
"fc1_expert_weights inter size must be 2 times fc2_expert_weights inter size.");
}
else
{
TORCH_CHECK(fc1_expert_weights.sizes()[2] == fc2_expert_weights.sizes()[1] * mInnerDimMultiplier,
"fc1_expert_weights inter size must be equal to fc2_expert_weights inter size.");
}
}
else
{
if (isGatedActivation(base_activation_type))
{
TORCH_CHECK(fc1_expert_weights.sizes()[1] == fc2_expert_weights.sizes()[2] * mInnerDimMultiplier * 2,
"fc1_expert_weights inter size must be 2 times fc2_expert_weights inter size.");
}
else
{
TORCH_CHECK(fc1_expert_weights.sizes()[1] == fc2_expert_weights.sizes()[2] * mInnerDimMultiplier,
"fc1_expert_weights inter size must be equal to fc2_expert_weights inter size.");
}
}
setRunnerProfiles(profile_ids);
auto stream = at::cuda::getCurrentCUDAStream(input.get_device());
std::vector<int64_t> output_shape = {num_rows * num_experts_on_rank, unpadded_hidden_size_val};
torch::Tensor output;
if (out_tensor.has_value())
{
auto const& provided = out_tensor.value();
CHECK_INPUT(provided, mOutputDtype);
TORCH_CHECK(provided.sizes() == output_shape, "Provided out tensor has incorrect shape. Expected ",
output_shape, ", got ", provided.sizes());
output = provided;
}
else
{
output = torch::empty(output_shape, input.options().dtype(mOutputDtype));
}
auto num_active_experts_per_node = torch::empty({1}, input.options().dtype(at::ScalarType::Int));
auto experts_to_token_score
= torch::empty({num_experts_on_rank, num_rows}, input.options().dtype(at::ScalarType::Float));
auto active_expert_global_ids = torch::empty({num_experts_on_rank}, input.options().dtype(at::ScalarType::Int));
kernels::MoeMinLatencyParams min_latency_params{};
min_latency_params.num_active_experts_per_node = static_cast<int*>(num_active_experts_per_node.data_ptr());
min_latency_params.experts_to_token_score = static_cast<float*>(experts_to_token_score.data_ptr());
min_latency_params.active_expert_global_ids = static_cast<int*>(active_expert_global_ids.data_ptr());
WorkspaceInfo const& workspace_info = getWorkspaceInfo(num_rows, hidden_size, inter_size, num_experts_total,
static_cast<int>(experts_per_token), base_activation_type, parallelism_config, min_latency_mode, stream);
auto quant_params
= getQuantParams(num_experts_on_rank, hidden_size, inter_size, quant_scales, base_activation_type);
// TODO: support lora in the future
::tensorrt_llm::kernels::LoraParams lora_params{};
#ifdef USING_OSS_CUTLASS_MOE_GEMM
mKernelRunner->runMoe(input.const_data_ptr(),
input_sf.has_value() ? input_sf.value().const_data_ptr() : nullptr, swizzled_input_sf,
reinterpret_cast<int const*>(token_selected_experts.const_data_ptr()),
token_final_scales.has_value() ? reinterpret_cast<float const*>(token_final_scales.value().const_data_ptr())
: nullptr,
fc1_expert_weights.const_data_ptr(),
fc1_expert_biases.has_value() ? fc1_expert_biases.value().const_data_ptr() : nullptr, activation_params,
fc2_expert_weights.const_data_ptr(),
fc2_expert_biases.has_value() ? fc2_expert_biases.value().const_data_ptr() : nullptr, quant_params,
num_rows, num_valid_tokens.has_value() ? num_valid_tokens.value() : num_rows, hidden_size,
unpadded_hidden_size_val, inter_size, num_experts_total, static_cast<int>(experts_per_token),
static_cast<char*>(workspace_info.workspace.data_ptr()), output.data_ptr(),
static_cast<int*>(workspace_info.src_to_dest_map), parallelism_config, enable_alltoall, false, lora_params,
mUseDeepSeekFP8BlockScaling, min_latency_mode, min_latency_params, stream);
#else
mKernelRunner->runMoe(input.const_data_ptr(),
input_sf.has_value() ? input_sf.value().const_data_ptr() : nullptr, swizzled_input_sf,
reinterpret_cast<int const*>(token_selected_experts.const_data_ptr()),
token_final_scales.has_value() ? reinterpret_cast<float const*>(token_final_scales.value().const_data_ptr())
: nullptr,
fc1_expert_weights.const_data_ptr(),
fc1_expert_biases.has_value() ? fc1_expert_biases.value().const_data_ptr() : nullptr, activation_params,
fc2_expert_weights.const_data_ptr(),
fc2_expert_biases.has_value() ? fc2_expert_biases.value().const_data_ptr() : nullptr, quant_params,
num_rows, num_valid_tokens.has_value() ? num_valid_tokens.value() : num_rows, hidden_size, inter_size,
num_experts_total, static_cast<int>(experts_per_token),
static_cast<char*>(workspace_info.workspace.data_ptr()), output.data_ptr(),
static_cast<int*>(workspace_info.src_to_dest_map), parallelism_config, false, lora_params,
mUseDeepSeekFP8BlockScaling, min_latency_mode, min_latency_params, stream);
#endif
return std::make_tuple(output, num_active_experts_per_node, experts_to_token_score, active_expert_global_ids);
}
int64_t getTacticNum(int64_t const gemm_idx)
{
std::lock_guard<std::mutex> lock(mMutex);
TORCH_CHECK(gemm_idx == 1 || gemm_idx == 2, "gemm_idx must be 1 or 2");
return (gemm_idx == 1) ? mGemm1Profiles.size() : mGemm2Profiles.size();
}
// TODO Update this to be able to tell if we are profiling swiglu bias
void runGemmProfile(torch::Tensor const& input, torch::Tensor const& fc1_expert_weights,
torch::optional<torch::Tensor> const& fc1_expert_biases, torch::Tensor const& fc2_expert_weights,
torch::optional<torch::Tensor> const& fc2_expert_biases, int64_t const top_k, int64_t const tp_size,
int64_t const tp_rank, int64_t const ep_size, int64_t const ep_rank, int64_t const cluster_size,
int64_t const cluster_rank, bool const enable_alltoall, bool const min_latency_mode, int64_t const gemm_idx,
int64_t const profile_id, bool const do_preparation, int64_t const activation_type_int,
int64_t const unpadded_hidden_size)
{
std::lock_guard<std::mutex> lock(mMutex);
// TODO: support profiling under fp8 block scaling in the future
if (mUseDeepSeekFP8BlockScaling)
{
return;
}
ActivationType activation_type = static_cast<ActivationType>(activation_type_int);
int64_t const num_rows = input.sizes()[0];
int64_t hidden_size = fc2_expert_weights.sizes()[1];
int64_t inter_size = fc2_expert_weights.sizes()[2] * mInnerDimMultiplier;
if (mUseINT8WoqPerChannel)
{
// Note: The weight shape for INT8 weight only quantization is different, e.g., fc2_expert_weights:
// [num_experts, inter_size, hidden_size]
hidden_size = fc2_expert_weights.sizes()[2] * mInnerDimMultiplier;
inter_size = fc2_expert_weights.sizes()[1];
}
int64_t const group_size_
= isInt4Quant() ? TmaWarpSpecializedGroupedGemmInput::INT4GroupwiseParams::int4_group_size : -1;
int64_t const group_size = isWFP4A16Quant()
? TmaWarpSpecializedGroupedGemmInput::INT4GroupwiseParams::wfp4a16_group_size
: group_size_;
int const num_experts = static_cast<int>(fc2_expert_weights.sizes()[0] * ep_size);
auto const gemm_to_profile
= (gemm_idx == 1) ? profiler_backend::GemmToProfile::GEMM_1 : profiler_backend::GemmToProfile::GEMM_2;
auto const& profiles = (gemm_idx == 1) ? mGemm1Profiles : mGemm2Profiles;
// Get specific profile configs according to the profile_id.
// Fallback tactic is set to be 0
// TODO: use the best tactic id found offline for a better default inference perf
auto const& profile = profile_id == -1 ? profiles.front() : profiles[profile_id];
auto stream = at::cuda::getCurrentCUDAStream(input.get_device());
auto const* expert_weights_ptr
= (gemm_idx == 1) ? fc1_expert_weights.const_data_ptr() : fc2_expert_weights.const_data_ptr();
// Preparation phase, only enabled during autotuning warmup phase.
if (do_preparation)
{
// Set profiled gemm idx
mProfiler->mGemmToProfile = gemm_to_profile;
// mProfiler init
auto parallelism_config = kernels::MOEParallelismConfig(static_cast<int>(tp_size),
static_cast<int>(tp_rank), static_cast<int>(ep_size), static_cast<int>(ep_rank),
static_cast<int>(cluster_size), static_cast<int>(cluster_rank));
bool const USE_BIAS = fc1_expert_biases.has_value() || fc2_expert_biases.has_value();
bool const USE_LORA = false;