layer.py 55.2 KB
Newer Older
xiaobochen's avatar
xiaobochen committed
1
2
3
import logging
from typing import Callable, List, Optional, Tuple

4
import einops
xiaobochen's avatar
xiaobochen committed
5
import torch
6
from sgl_kernel import silu_and_mul
Lianmin Zheng's avatar
Lianmin Zheng committed
7
from torch.nn import Module
8

9
from sglang.srt.custom_op import CustomOp
10
11
12
13
from sglang.srt.distributed import (
    get_tensor_model_parallel_rank,
    get_tensor_model_parallel_world_size,
)
fzyzcjy's avatar
fzyzcjy committed
14
15
from sglang.srt.eplb.expert_location import get_global_expert_location_metadata
from sglang.srt.eplb.expert_location_dispatch import ExpertLocationDispatchInfo
Ke Bao's avatar
Ke Bao committed
16
from sglang.srt.layers.moe.ep_moe.kernels import (
17
18
    ep_gather,
    ep_scatter,
19
    gelu_and_mul_triton_kernel,
xiaobochen's avatar
xiaobochen committed
20
    grouped_gemm_triton,
21
    moe_ep_deepgemm_preprocess,
xiaobochen's avatar
xiaobochen committed
22
23
24
    post_reorder_triton_kernel,
    pre_reorder_triton_kernel,
    run_moe_ep_preproess,
25
    silu_and_mul_masked_post_quant_fwd,
xiaobochen's avatar
xiaobochen committed
26
    silu_and_mul_triton_kernel,
27
    tma_align_input_scale,
xiaobochen's avatar
xiaobochen committed
28
)
29
from sglang.srt.layers.moe.fused_moe_triton import FusedMoeWeightScaleSupported
30
from sglang.srt.layers.moe.fused_moe_triton.layer import FusedMoE, FusedMoEMethodBase
Ke Bao's avatar
Ke Bao committed
31
from sglang.srt.layers.moe.topk import select_experts
32
from sglang.srt.layers.quantization import deep_gemm_wrapper
xiaobochen's avatar
xiaobochen committed
33
34
35
36
from sglang.srt.layers.quantization.base_config import (
    QuantizationConfig,
    QuantizeMethodBase,
)
37
from sglang.srt.layers.quantization.fp8 import Fp8Config, Fp8MoEMethod
38
from sglang.srt.layers.quantization.fp8_kernel import (
Alex Sun's avatar
Alex Sun committed
39
    is_fp8_fnuz,
40
    scaled_fp8_quant,
41
    sglang_per_token_group_quant_fp8,
42
43
    sglang_per_token_quant_fp8,
)
Alex Sun's avatar
Alex Sun committed
44
from sglang.srt.layers.quantization.fp8_utils import normalize_e4m3fn_to_e4m3fnuz
45
from sglang.srt.managers.schedule_batch import global_server_args_dict
46
from sglang.srt.model_executor.forward_batch_info import ForwardMode
47
48
from sglang.srt.utils import (
    DeepEPMode,
49
    ceil_div,
50
51
52
53
54
    dispose_tensor,
    get_bool_env_var,
    is_hip,
    set_weight_attrs,
)
55

Lianmin Zheng's avatar
Lianmin Zheng committed
56
_is_hip = is_hip()
Alex Sun's avatar
Alex Sun committed
57
_is_fp8_fnuz = is_fp8_fnuz()
58
_use_aiter = get_bool_env_var("SGLANG_USE_AITER") and _is_hip
59

Lianmin Zheng's avatar
Lianmin Zheng committed
60
61
if _is_hip:
    from vllm._custom_ops import scaled_fp8_quant
62

63
64
65
66
67
if _use_aiter:
    from aiter import ActivationType, QuantType
    from aiter.fused_moe import fused_moe
    from aiter.ops.shuffle import shuffle_weight

xiaobochen's avatar
xiaobochen committed
68
69
70
71
72
73
logger = logging.getLogger(__name__)


class GroupedGemmRunner(torch.nn.Module):
    flashinfer_gemm_warpper = None

74
75
76
77
78
79
    def __init__(
        self,
        device,
        use_flashinfer: bool = False,
        use_per_token_if_dynamic: bool = True,
    ):
xiaobochen's avatar
xiaobochen committed
80
81
82
        super().__init__()
        self.device = device
        self.use_flashinfer = use_flashinfer
83
        self.use_per_token_if_dynamic = use_per_token_if_dynamic
xiaobochen's avatar
xiaobochen committed
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
        if self.use_flashinfer and GroupedGemmRunner.flashinfer_gemm_warpper is None:
            GroupedGemmRunner._init_flashinfer_wrapper(device)

    @classmethod
    def _init_flashinfer_wrapper(cls, device):
        from flashinfer import SegmentGEMMWrapper

        workspace_buffer = torch.empty(
            128 * 1024 * 1024, dtype=torch.int8, device=device
        )
        cls.flashinfer_gemm_warpper = SegmentGEMMWrapper(workspace_buffer)

    # c = a * b
    def forward(
        self,
        a: torch.Tensor,
        b: torch.Tensor,
        c: torch.Tensor,
        batch_size: int,
        weight_column_major: bool,
        seg_indptr: Optional[torch.Tensor] = None,
        weight_indices: Optional[torch.Tensor] = None,
        use_fp8_w8a8: bool = False,
        scale_a: torch.Tensor = None,
        scale_b: torch.Tensor = None,
109
        block_shape: Optional[List[int]] = None,
fzyzcjy's avatar
fzyzcjy committed
110
        c_dtype=None,
xiaobochen's avatar
xiaobochen committed
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
    ):
        if self.use_flashinfer:
            # TODO: flashinfer
            assert False
            assert GroupedGemmRunner.flashinfer_gemm_warpper is not None
            c = GroupedGemmRunner.flashinfer_gemm_warpper.run(
                x=a,
                weights=b,
                batch_size=batch_size,
                weight_column_major=weight_column_major,
                seg_indptr=seg_indptr,
                weight_indices=weight_indices,
            )
        else:
            assert weight_column_major == True
            c = grouped_gemm_triton(
                a,
                b,
                c,
                batch_size,
                weight_column_major,
                seg_indptr,
                weight_indices,
                use_fp8_w8a8,
                scale_a,
                scale_b,
137
                block_shape=block_shape,
fzyzcjy's avatar
fzyzcjy committed
138
                c_dtype=c_dtype,
139
                use_per_token_if_dynamic=self.use_per_token_if_dynamic,
xiaobochen's avatar
xiaobochen committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
            )
        return c


class EPMoE(torch.nn.Module):
    """
    MoE Expert Parallel Impl


    """

    def __init__(
        self,
        num_experts: int,
        top_k: int,
        hidden_size: int,
        intermediate_size: int,
fzyzcjy's avatar
fzyzcjy committed
157
        layer_id: int,
xiaobochen's avatar
xiaobochen committed
158
159
160
161
        params_dtype: Optional[torch.dtype] = None,
        renormalize: bool = True,
        use_grouped_topk: bool = False,
        num_expert_group: Optional[int] = None,
162
        num_fused_shared_experts: int = 0,
xiaobochen's avatar
xiaobochen committed
163
164
165
166
        topk_group: Optional[int] = None,
        quant_config: Optional[QuantizationConfig] = None,
        tp_size: Optional[int] = None,
        prefix: str = "",
Ke Bao's avatar
Ke Bao committed
167
        correction_bias: Optional[torch.Tensor] = None,
168
        custom_routing_function: Optional[Callable] = None,
169
        activation: str = "silu",
170
        routed_scaling_factor: Optional[float] = None,
171
        use_per_token_if_dynamic: bool = True,
xiaobochen's avatar
xiaobochen committed
172
173
174
175
176
177
178
179
180
181
182
    ):
        super().__init__()

        if params_dtype is None:
            params_dtype = torch.get_default_dtype()

        self.tp_size = (
            tp_size if tp_size is not None else get_tensor_model_parallel_world_size()
        )
        self.tp_rank = get_tensor_model_parallel_rank()

fzyzcjy's avatar
fzyzcjy committed
183
        self.layer_id = layer_id
xiaobochen's avatar
xiaobochen committed
184
185
        self.num_experts = num_experts
        assert self.num_experts % self.tp_size == 0
186
187
188
        assert (
            num_fused_shared_experts == 0
        ), "num_fused_shared_experts is not supported in EP"
189
        self.num_fused_shared_experts = num_fused_shared_experts
xiaobochen's avatar
xiaobochen committed
190
191
192
193
194
195
196
197
198
199
200
201
        self.num_experts_per_partition = self.num_experts // self.tp_size
        self.start_expert_id = self.tp_rank * self.num_experts_per_partition
        self.end_expert_id = self.start_expert_id + self.num_experts_per_partition - 1

        self.top_k = top_k
        self.intermediate_size = intermediate_size
        self.renormalize = renormalize
        self.use_grouped_topk = use_grouped_topk
        if self.use_grouped_topk:
            assert num_expert_group is not None and topk_group is not None
        self.num_expert_group = num_expert_group
        self.topk_group = topk_group
Ke Bao's avatar
Ke Bao committed
202
        self.correction_bias = correction_bias
203
        self.custom_routing_function = custom_routing_function
204
        self.activation = activation
205
        self.routed_scaling_factor = routed_scaling_factor
206
        self.use_per_token_if_dynamic = use_per_token_if_dynamic
xiaobochen's avatar
xiaobochen committed
207
208
209
210

        if quant_config is None:
            self.quant_method: Optional[QuantizeMethodBase] = UnquantizedEPMoEMethod()
            self.use_fp8_w8a8 = False
211
212
            self.use_block_quant = False
            self.block_shape = None
xiaobochen's avatar
xiaobochen committed
213
214
215
216
217
218
            self.activation_scheme = None
        else:
            self.quant_method: Optional[QuantizeMethodBase] = Fp8EPMoEMethod(
                quant_config
            )
            self.use_fp8_w8a8 = True
219
220
221
222
223
224
            self.use_block_quant = getattr(self.quant_method, "block_quant", False)
            self.block_shape = (
                self.quant_method.quant_config.weight_block_size
                if self.use_block_quant
                else None
            )
xiaobochen's avatar
xiaobochen committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
            self.fp8_dtype = torch.float8_e4m3fn
            self.activation_scheme = quant_config.activation_scheme

        self.quant_method.create_weights(
            layer=self,
            num_experts_per_partition=self.num_experts_per_partition,
            hidden_size=hidden_size,
            intermediate_size=self.intermediate_size,
            params_dtype=params_dtype,
            weight_loader=self.weight_loader,
        )

        self.grouped_gemm_runner = None

239
240
241
242
243
244
245
246
247
248
249
250
251
        self.w13_weight_fp8 = (
            self.w13_weight,
            (
                self.w13_weight_scale_inv
                if self.use_block_quant
                else self.w13_weight_scale
            ),
        )
        self.w2_weight_fp8 = (
            self.w2_weight,
            self.w2_weight_scale_inv if self.use_block_quant else self.w2_weight_scale,
        )

xiaobochen's avatar
xiaobochen committed
252
    def forward(self, hidden_states: torch.Tensor, router_logits: torch.Tensor):
253
254
255
256
257
258
259
260
261
262
        if deep_gemm_wrapper.ENABLE_JIT_DEEPGEMM and self.use_fp8_w8a8:
            return self.forward_deepgemm(hidden_states, router_logits)
        else:
            return self.forward_normal(hidden_states, router_logits)

    def forward_deepgemm(
        self, hidden_states: torch.Tensor, router_logits: torch.Tensor
    ):
        assert self.quant_method is not None
        assert self.activation == "silu"
fzyzcjy's avatar
fzyzcjy committed
263
264
265
        hidden_states_shape = hidden_states.shape
        hidden_states_dtype = hidden_states.dtype
        hidden_states_device = hidden_states.device
266
267
268
269
270
271
272
273
274
275
276
277
278
        topk_weights, topk_ids = select_experts(
            hidden_states=hidden_states,
            router_logits=router_logits,
            top_k=self.top_k,
            use_grouped_topk=self.use_grouped_topk,
            renormalize=self.renormalize,
            topk_group=self.topk_group,
            num_expert_group=self.num_expert_group,
            num_fused_shared_experts=self.num_fused_shared_experts,
            correction_bias=self.correction_bias,
            custom_routing_function=self.custom_routing_function,
            routed_scaling_factor=self.routed_scaling_factor,
        )
fzyzcjy's avatar
fzyzcjy committed
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
        if not self.use_block_quant:
            # Convert per-tensor quant to per-block quant by repeating scales for forward_deepgemm
            scale_block_size = 128
            w13_weight_scale_n = 2 * (
                (self.intermediate_size + scale_block_size - 1) // scale_block_size
            )
            w13_weight_scale_k = (
                hidden_states_shape[-1] + scale_block_size - 1
            ) // scale_block_size
            w13_weight_scale = (
                self.w13_weight_scale.unsqueeze(1)
                .repeat_interleave(w13_weight_scale_n, dim=1)
                .unsqueeze(2)
                .repeat_interleave(w13_weight_scale_k, dim=2)
            )
            self.w13_weight_fp8 = (
                self.w13_weight,
                w13_weight_scale,
            )
            w2_weight_scale_n = (
                hidden_states_shape[-1] + scale_block_size - 1
            ) // scale_block_size
            w2_weight_scale_k = (
                self.intermediate_size + scale_block_size - 1
            ) // scale_block_size
            w2_weight_scale = (
                self.w2_weight_scale.unsqueeze(1)
                .repeat_interleave(w2_weight_scale_n, dim=1)
                .unsqueeze(2)
                .repeat_interleave(w2_weight_scale_k, dim=2)
            )
            self.w2_weight_fp8 = (
                self.w2_weight,
                w2_weight_scale,
            )
xiaobochen's avatar
xiaobochen committed
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
        # PreReorder
        m_max, masked_m, expected_m, src2dst, gateup_input, gateup_input_scale = (
            moe_ep_deepgemm_preprocess(
                topk_ids,
                self.num_experts,
                hidden_states,
                self.top_k,
                self.start_expert_id,
                self.end_expert_id,
                self.block_shape,
            )
        )

        dispose_tensor(hidden_states)

        # GroupGemm-0
        gateup_input_fp8 = (
            gateup_input,
            deep_gemm_wrapper.get_col_major_tma_aligned_tensor(gateup_input_scale),
        )
        num_groups, m, k = gateup_input_fp8[0].size()
        n = self.w13_weight.size(1)
        gateup_output = torch.empty(
            (num_groups, m, n), device=hidden_states_device, dtype=torch.bfloat16
        )
        deep_gemm_wrapper.grouped_gemm_nt_f8f8bf16_masked(
            gateup_input_fp8, self.w13_weight_fp8, gateup_output, masked_m, expected_m
        )
        del gateup_input
        del gateup_input_fp8

        # Act
        down_input = torch.empty(
            (
                gateup_output.shape[0],
                gateup_output.shape[1],
                gateup_output.shape[2] // 2,
            ),
            device=hidden_states_device,
            dtype=self.fp8_dtype,
        )
        scale_block_size = 128
        down_input_scale = torch.empty(
            (
                gateup_output.shape[0],
                gateup_output.shape[1],
                gateup_output.shape[2] // 2 // scale_block_size,
            ),
            device=hidden_states_device,
            dtype=torch.float32,
        )
        silu_and_mul_masked_post_quant_fwd(
            gateup_output,
            down_input,
            down_input_scale,
            scale_block_size,
            masked_m,
        )
        del gateup_output

        # GroupGemm-1
        n = self.w2_weight.size(1)
        down_input_fp8 = (
            down_input,
            deep_gemm_wrapper.get_col_major_tma_aligned_tensor(down_input_scale),
        )
        down_output = torch.empty(
            (num_groups, m, n), device=hidden_states_device, dtype=torch.bfloat16
        )
        deep_gemm_wrapper.grouped_gemm_nt_f8f8bf16_masked(
            down_input_fp8, self.w2_weight_fp8, down_output, masked_m, expected_m
        )
        del down_input
        del down_input_fp8

        # PostReorder
        output = torch.empty(
            hidden_states_shape, dtype=hidden_states_dtype, device=hidden_states_device
        )
        post_reorder_triton_kernel[(hidden_states_shape[0],)](
            down_output,
            output,
            src2dst,
            topk_ids,
            topk_weights,
            self.start_expert_id,
            self.end_expert_id,
            self.top_k,
            hidden_states_shape[1],
            m_max * self.start_expert_id,
            BLOCK_SIZE=512,
        )
        return output

    def forward_normal(self, hidden_states: torch.Tensor, router_logits: torch.Tensor):
        assert self.quant_method is not None
        hidden_states_shape = hidden_states.shape
        hidden_states_dtype = hidden_states.dtype
        hidden_states_device = hidden_states.device
xiaobochen's avatar
xiaobochen committed
415
416
        if self.grouped_gemm_runner is None:
            self.grouped_gemm_runner = GroupedGemmRunner(
417
418
                hidden_states.device,
                use_flashinfer=False,  # TODO: use flashinfer
419
                use_per_token_if_dynamic=self.use_per_token_if_dynamic,
xiaobochen's avatar
xiaobochen committed
420
421
            )

Ke Bao's avatar
Ke Bao committed
422
423
424
425
426
427
428
429
        topk_weights, topk_ids = select_experts(
            hidden_states=hidden_states,
            router_logits=router_logits,
            top_k=self.top_k,
            use_grouped_topk=self.use_grouped_topk,
            renormalize=self.renormalize,
            topk_group=self.topk_group,
            num_expert_group=self.num_expert_group,
430
            num_fused_shared_experts=self.num_fused_shared_experts,
Ke Bao's avatar
Ke Bao committed
431
            correction_bias=self.correction_bias,
432
            custom_routing_function=self.custom_routing_function,
433
            routed_scaling_factor=self.routed_scaling_factor,
434
435
436
            expert_location_dispatch_info=ExpertLocationDispatchInfo.init_new(
                layer_id=self.layer_id,
            ),
xiaobochen's avatar
xiaobochen committed
437
438
439
440
441
442
443
444
445
        )

        reorder_topk_ids, src2dst, seg_indptr = run_moe_ep_preproess(
            topk_ids, self.num_experts
        )

        gateup_input = torch.empty(
            (int(hidden_states.shape[0] * self.top_k), hidden_states.shape[1]),
            device=hidden_states.device,
446
447
448
449
450
            dtype=(
                self.fp8_dtype
                if (self.use_fp8_w8a8 and not self.use_block_quant)
                else hidden_states.dtype
            ),
xiaobochen's avatar
xiaobochen committed
451
        )
452
        if self.activation_scheme == "dynamic" and not self.use_block_quant:
453
454
455
456
457
458
459
460
461
462
            if self.use_per_token_if_dynamic:
                max_value = torch.max(hidden_states, dim=1).values.to(torch.float32)
                self.w13_input_scale = max_value / torch.finfo(self.fp8_dtype).max
            else:
                max_value = (
                    torch.max(hidden_states)
                    .repeat(self.num_experts_per_partition)
                    .to(torch.float32)
                )
                self.w13_input_scale = max_value / torch.finfo(self.fp8_dtype).max
xiaobochen's avatar
xiaobochen committed
463
464
465
466
467
468
469
470
471
472
473
474
475

        # PreReorder
        pre_reorder_triton_kernel[(hidden_states.shape[0],)](
            hidden_states,
            gateup_input,
            src2dst,
            topk_ids,
            self.w13_input_scale,
            self.start_expert_id,
            self.end_expert_id,
            self.top_k,
            hidden_states.shape[1],
            BLOCK_SIZE=512,
476
            use_per_token_if_dynamic=self.use_per_token_if_dynamic,
xiaobochen's avatar
xiaobochen committed
477
        )
fzyzcjy's avatar
fzyzcjy committed
478
        dispose_tensor(hidden_states)
xiaobochen's avatar
xiaobochen committed
479

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
        if (
            self.activation_scheme == "dynamic"
            and not self.use_block_quant
            and self.use_per_token_if_dynamic
        ):
            scale = torch.empty(
                hidden_states_shape[0] * self.top_k,
                device=hidden_states_device,
                dtype=torch.float32,
            )
            scale[src2dst] = (
                self.w13_input_scale.unsqueeze(1)
                .expand(hidden_states_shape[0], self.top_k)
                .reshape(-1)
            )
            self.w13_input_scale = scale

xiaobochen's avatar
xiaobochen committed
497
498
499
500
        seg_indptr_cur_rank = seg_indptr[self.start_expert_id : self.end_expert_id + 2]
        weight_indices_cur_rank = torch.arange(
            0,
            self.num_experts_per_partition,
fzyzcjy's avatar
fzyzcjy committed
501
            device=hidden_states_device,
xiaobochen's avatar
xiaobochen committed
502
503
504
505
506
507
            dtype=torch.int64,
        )
        # GroupGemm-0
        gateup_output = self.grouped_gemm_runner(
            a=gateup_input,
            b=self.w13_weight,
fzyzcjy's avatar
fzyzcjy committed
508
509
            c=None,
            c_dtype=hidden_states_dtype,
xiaobochen's avatar
xiaobochen committed
510
511
512
513
514
515
            batch_size=self.num_experts_per_partition,
            weight_column_major=True,
            seg_indptr=seg_indptr_cur_rank,
            weight_indices=weight_indices_cur_rank,
            use_fp8_w8a8=self.use_fp8_w8a8,
            scale_a=self.w13_input_scale,
516
517
518
519
520
521
            scale_b=(
                self.w13_weight_scale_inv
                if self.use_block_quant
                else self.w13_weight_scale
            ),
            block_shape=self.block_shape,
xiaobochen's avatar
xiaobochen committed
522
        )
fzyzcjy's avatar
fzyzcjy committed
523
        del gateup_input
xiaobochen's avatar
xiaobochen committed
524
525

        # Act
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
        if self.activation_scheme == "dynamic" and not self.use_block_quant:
            self.w2_input_scale = None
            down_input = torch.empty(
                gateup_output.shape[0],
                gateup_output.shape[1] // 2,
                device=gateup_output.device,
                dtype=hidden_states_dtype,
            )
        else:
            down_input = torch.empty(
                gateup_output.shape[0],
                gateup_output.shape[1] // 2,
                device=gateup_output.device,
                dtype=(
                    self.fp8_dtype
                    if (self.use_fp8_w8a8 and not self.use_block_quant)
                    else hidden_states_dtype
                ),
xiaobochen's avatar
xiaobochen committed
544
            )
545
546
547
548
549
550
551
552
553
554
555
556

        if self.activation == "silu":
            silu_and_mul_triton_kernel[(gateup_output.shape[0],)](
                gateup_output,
                down_input,
                gateup_output.shape[1],
                reorder_topk_ids,
                self.w2_input_scale,
                self.start_expert_id,
                self.end_expert_id,
                BLOCK_SIZE=512,
            )
557
558
559
560
561
562
563
564
565
566
567
        elif self.activation == "gelu":
            gelu_and_mul_triton_kernel[(gateup_output.shape[0],)](
                gateup_output,
                down_input,
                gateup_output.shape[1],
                reorder_topk_ids,
                self.w2_input_scale,
                self.start_expert_id,
                self.end_expert_id,
                BLOCK_SIZE=512,
            )
568
569
        else:
            raise ValueError(f"Unsupported activation: {self.activation=}")
fzyzcjy's avatar
fzyzcjy committed
570
        del gateup_output
xiaobochen's avatar
xiaobochen committed
571

572
573
574
575
576
577
578
579
580
581
        if self.activation_scheme == "dynamic" and not self.use_block_quant:
            if self.use_per_token_if_dynamic:
                down_input, self.w2_input_scale = sglang_per_token_quant_fp8(down_input)
            else:
                self.w2_input_scale = torch.ones(
                    self.num_experts_per_partition,
                    dtype=torch.float32,
                    device=hidden_states_device,
                )

xiaobochen's avatar
xiaobochen committed
582
583
584
585
        # GroupGemm-1
        down_output = torch.empty(
            down_input.shape[0],
            self.w2_weight.shape[1],
fzyzcjy's avatar
fzyzcjy committed
586
587
            device=hidden_states_device,
            dtype=hidden_states_dtype,
xiaobochen's avatar
xiaobochen committed
588
589
590
591
592
593
594
595
596
597
598
        )
        down_output = self.grouped_gemm_runner(
            a=down_input,
            b=self.w2_weight,
            c=down_output,
            batch_size=self.num_experts_per_partition,
            weight_column_major=True,
            seg_indptr=seg_indptr_cur_rank,
            weight_indices=weight_indices_cur_rank,
            use_fp8_w8a8=self.use_fp8_w8a8,
            scale_a=self.w2_input_scale,
599
600
601
602
603
604
            scale_b=(
                self.w2_weight_scale_inv
                if self.use_block_quant
                else self.w2_weight_scale
            ),
            block_shape=self.block_shape,
xiaobochen's avatar
xiaobochen committed
605
        )
fzyzcjy's avatar
fzyzcjy committed
606
        del down_input
xiaobochen's avatar
xiaobochen committed
607
608

        # PostReorder
fzyzcjy's avatar
fzyzcjy committed
609
610
611
612
        output = torch.empty(
            hidden_states_shape, dtype=hidden_states_dtype, device=hidden_states_device
        )
        post_reorder_triton_kernel[(hidden_states_shape[0],)](
xiaobochen's avatar
xiaobochen committed
613
614
615
616
617
618
619
620
            down_output,
            output,
            src2dst,
            topk_ids,
            topk_weights,
            self.start_expert_id,
            self.end_expert_id,
            self.top_k,
fzyzcjy's avatar
fzyzcjy committed
621
            hidden_states_shape[1],
622
            0,
xiaobochen's avatar
xiaobochen committed
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
            BLOCK_SIZE=512,
        )
        return output

    @classmethod
    def make_expert_params_mapping(
        cls,
        ckpt_gate_proj_name: str,
        ckpt_down_proj_name: str,
        ckpt_up_proj_name: str,
        num_experts: int,
    ) -> List[Tuple[str, str, int, str]]:
        return [
            # (param_name, weight_name, expert_id, shard_id)
            (
                (
                    "experts.w13_"
                    if weight_name in [ckpt_gate_proj_name, ckpt_up_proj_name]
                    else "experts.w2_"
                ),
                f"experts.{expert_id}.{weight_name}.",
                expert_id,
                shard_id,
            )
            for expert_id in range(num_experts)
            for shard_id, weight_name in [
                ("w1", ckpt_gate_proj_name),
                ("w2", ckpt_down_proj_name),
                ("w3", ckpt_up_proj_name),
            ]
        ]

    def weight_loader(
        self,
        param: torch.nn.Parameter,
        loaded_weight: torch.Tensor,
        weight_name: str,
        shard_id: str,
        expert_id: int,
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
    ) -> None:
        physical_expert_ids = (
            get_global_expert_location_metadata().logical_to_all_physical(
                self.layer_id, expert_id
            )
        )
        for physical_expert_id in physical_expert_ids:
            self._weight_loader_physical(
                param=param,
                loaded_weight=loaded_weight,
                weight_name=weight_name,
                shard_id=shard_id,
                expert_id=physical_expert_id,
            )

    def _weight_loader_physical(
        self,
        param: torch.nn.Parameter,
        loaded_weight: torch.Tensor,
        weight_name: str,
        shard_id: str,
        expert_id: int,
xiaobochen's avatar
xiaobochen committed
684
685
686
687
688
689
690
691
692
693
694
695
696
    ) -> None:
        if expert_id < self.start_expert_id or expert_id > self.end_expert_id:
            return
        expert_id = expert_id - self.start_expert_id

        if shard_id not in ("w1", "w2", "w3"):
            raise ValueError(
                f"shard_id must be ['w1','w2','w3'] but " f"got {shard_id}."
            )

        # Special case for fp8 scales.
        if "scale" in weight_name:
            self._load_fp8_scale(
697
698
699
700
701
                param.data,
                loaded_weight,
                weight_name,
                shard_id,
                expert_id,
xiaobochen's avatar
xiaobochen committed
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
            )
            return

        if shard_id == "w2":
            param.data[expert_id] = loaded_weight
        elif shard_id == "w1":
            param.data[expert_id][: self.intermediate_size, :] = loaded_weight
        elif shard_id == "w3":
            param.data[expert_id][self.intermediate_size :, :] = loaded_weight
        else:
            raise ValueError(f"Expected shard_id w1,w2 or w3 but got {shard_id}")

    def _load_fp8_scale(
        self,
        param: torch.nn.Parameter,
        loaded_weight: torch.Tensor,
        weight_name: str,
        shard_id: str,
        expert_id: int,
    ) -> None:
        param_data = param.data

        # Input scales can be loaded directly and should be equal.
        if "input_scale" in weight_name:
            if (
727
728
                (shard_id == "w1" or shard_id == "w3")
                and param_data[expert_id] != 1
xiaobochen's avatar
xiaobochen committed
729
730
731
732
733
734
735
736
737
738
                and (param_data[expert_id] - loaded_weight).abs() > 1e-5
            ):
                raise ValueError(
                    "input_scales of w1 and w3 of a layer "
                    f"must be equal. But got {param_data[expert_id]} "
                    f"vs. {loaded_weight}"
                )
            param_data[expert_id] = loaded_weight
        # Weight scales
        elif "weight_scale" in weight_name:
739
740
741
742
743
744
745
746
747
748
749
750
            if self.use_block_quant:
                block_n, block_k = self.block_shape[0], self.block_shape[1]
                if shard_id == "w1":
                    param_data[expert_id][
                        : (self.intermediate_size + block_n - 1) // block_n, :
                    ] = loaded_weight
                elif shard_id == "w3":
                    param_data[expert_id][
                        (self.intermediate_size + block_n - 1) // block_n :, :
                    ] = loaded_weight
                else:  # w2
                    param_data[expert_id] = loaded_weight
xiaobochen's avatar
xiaobochen committed
751
752
            # If we are in merged column case (gate_up_proj)
            else:
753
754
755
756
757
758
759
760
761
                if shard_id in ("w1", "w3"):
                    # We have to keep the weight scales of w1 and w3 because
                    # we need to re-quantize w1/w3 weights after weight loading.
                    idx = 0 if shard_id == "w1" else 1
                    param_data[expert_id][idx] = loaded_weight

                # If we are in the row parallel case (down_proj)
                else:
                    param_data[expert_id] = loaded_weight
xiaobochen's avatar
xiaobochen committed
762
763
764


class UnquantizedEPMoEMethod(FusedMoEMethodBase, CustomOp):
765

xiaobochen's avatar
xiaobochen committed
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
    def create_weights(
        self,
        layer: torch.nn.Module,
        num_experts_per_partition: int,
        hidden_size: int,
        intermediate_size: int,
        params_dtype: torch.dtype,
        **extra_weight_attrs,
    ):
        # Fused gate_up_proj (column parallel)
        w13_weight = torch.nn.Parameter(
            torch.empty(
                num_experts_per_partition,
                2 * intermediate_size,
                hidden_size,
                dtype=params_dtype,
            ),
            requires_grad=False,
        )
        layer.register_parameter("w13_weight", w13_weight)
        set_weight_attrs(w13_weight, extra_weight_attrs)

        # down_proj (row parallel)
        w2_weight = torch.nn.Parameter(
            torch.empty(
                num_experts_per_partition,
                hidden_size,
                intermediate_size,
                dtype=params_dtype,
            ),
            requires_grad=False,
        )
        layer.register_parameter("w2_weight", w2_weight)
        set_weight_attrs(w2_weight, extra_weight_attrs)

        # scale
802
803
804
        layer.register_parameter("w13_input_scale", None)
        layer.register_parameter("w13_weight_scale", None)

xiaobochen's avatar
xiaobochen committed
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
        ones_tensor = torch.ones(num_experts_per_partition, dtype=torch.float32)

        w2_input_scale = torch.nn.Parameter(
            ones_tensor,
            requires_grad=False,
        )
        layer.register_parameter("w2_input_scale", w2_input_scale)
        set_weight_attrs(w2_input_scale, extra_weight_attrs)

        w2_weight_scale = torch.nn.Parameter(
            ones_tensor,
            requires_grad=False,
        )
        layer.register_parameter("w2_weight_scale", w2_weight_scale)
        set_weight_attrs(w2_weight_scale, extra_weight_attrs)

    def apply(
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
        router_logits: torch.Tensor,
        top_k: int,
        renormalize: bool,
        use_grouped_topk: bool,
        topk_group: Optional[int] = None,
        num_expert_group: Optional[int] = None,
        custom_routing_function: Optional[Callable] = None,
    ) -> torch.Tensor:
        raise NotImplementedError


class Fp8EPMoEMethod(Fp8MoEMethod):
    """MoE method for FP8.
    Supports loading FP8 checkpoints with static weight scale and
    dynamic/static activation scale.

    Args:
        quant_config: The quantization config.
    """

    def __init__(self, quant_config: Fp8Config):
        self.quant_config = quant_config
847
        self.block_quant = self.quant_config.weight_block_size is not None
xiaobochen's avatar
xiaobochen committed
848
849
850
851
852
853
854
855
856
857
858
859
860

    def create_weights(
        self,
        layer: Module,
        num_experts_per_partition: int,
        hidden_size: int,
        intermediate_size: int,
        params_dtype: torch.dtype,
        **extra_weight_attrs,
    ):
        if self.quant_config.is_checkpoint_fp8_serialized:
            params_dtype = torch.float8_e4m3fn

861
862
863
864
865
866
867
        tp_size = get_tensor_model_parallel_world_size()
        if self.block_quant:
            block_n, block_k = (
                self.quant_config.weight_block_size[0],
                self.quant_config.weight_block_size[1],
            )
            # NOTE(HandH1998): To ensure proper alignment of the block-wise quantization scales, the output_size of the weights for both the gate and up layers must be divisible by block_n.
868
            # Required by column parallel or enabling merged weights
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
            if intermediate_size % block_n != 0:
                raise ValueError(
                    f"The output_size of gate's and up's weight = "
                    f"{intermediate_size} is not divisible by "
                    f"weight quantization block_n = {block_n}."
                )
            if tp_size > 1:
                # Required by row parallel
                if intermediate_size % block_k != 0:
                    raise ValueError(
                        f"The input_size of down's weight = "
                        f"{intermediate_size} is not divisible by "
                        f"weight quantization block_k = {block_k}."
                    )

xiaobochen's avatar
xiaobochen committed
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
        # WEIGHTS
        w13_weight = torch.nn.Parameter(
            torch.empty(
                num_experts_per_partition,
                2 * intermediate_size,
                hidden_size,
                dtype=params_dtype,
            ),
            requires_grad=False,
        )
        layer.register_parameter("w13_weight", w13_weight)
        set_weight_attrs(w13_weight, extra_weight_attrs)

        w2_weight = torch.nn.Parameter(
            torch.empty(
                num_experts_per_partition,
                hidden_size,
                intermediate_size,
                dtype=params_dtype,
            ),
            requires_grad=False,
        )
        layer.register_parameter("w2_weight", w2_weight)
        set_weight_attrs(w2_weight, extra_weight_attrs)

        # WEIGHT_SCALES
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
        if self.block_quant:
            w13_weight_scale = torch.nn.Parameter(
                torch.ones(
                    num_experts_per_partition,
                    2 * ((intermediate_size + block_n - 1) // block_n),
                    (hidden_size + block_k - 1) // block_k,
                    dtype=torch.float32,
                ),
                requires_grad=False,
            )
            w2_weight_scale = torch.nn.Parameter(
                torch.ones(
                    num_experts_per_partition,
                    (hidden_size + block_n - 1) // block_n,
                    (intermediate_size + block_k - 1) // block_k,
                    dtype=torch.float32,
                ),
                requires_grad=False,
            )
            layer.register_parameter("w13_weight_scale_inv", w13_weight_scale)
            layer.register_parameter("w2_weight_scale_inv", w2_weight_scale)
            assert self.quant_config.activation_scheme == "dynamic"
        else:
            # WEIGHT_SCALES
            # Allocate 2 scales for w1 and w3 respectively.
            w13_weight_scale = torch.nn.Parameter(
                torch.ones(num_experts_per_partition, 2, dtype=torch.float32),
                requires_grad=False,
            )
            layer.register_parameter("w13_weight_scale", w13_weight_scale)
xiaobochen's avatar
xiaobochen committed
940

941
942
943
944
945
            w2_weight_scale = torch.nn.Parameter(
                torch.ones(num_experts_per_partition, dtype=torch.float32),
                requires_grad=False,
            )
            layer.register_parameter("w2_weight_scale", w2_weight_scale)
xiaobochen's avatar
xiaobochen committed
946
947
        # Add the quantization method used (per tensor/grouped/channel)
        # to ensure the weight scales are loaded in properly
948
949
950
951
952
        extra_weight_attrs.update(
            {"quant_method": FusedMoeWeightScaleSupported.BLOCK.value}
            if self.block_quant
            else {"quant_method": FusedMoeWeightScaleSupported.TENSOR.value}
        )
xiaobochen's avatar
xiaobochen committed
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
        # If loading fp8 checkpoint, pass the weight loaders.
        # If loading an fp16 checkpoint, do not (we will quantize in
        #   process_weights_after_loading()
        if self.quant_config.is_checkpoint_fp8_serialized:
            set_weight_attrs(w13_weight_scale, extra_weight_attrs)
            set_weight_attrs(w2_weight_scale, extra_weight_attrs)

        # INPUT_SCALES
        if self.quant_config.activation_scheme == "static":
            if not self.quant_config.is_checkpoint_fp8_serialized:
                raise ValueError(
                    "Found static activation scheme for checkpoint that "
                    "was not serialized fp8."
                )

            w13_input_scale = torch.nn.Parameter(
                torch.ones(num_experts_per_partition, dtype=torch.float32),
                requires_grad=False,
            )
            layer.register_parameter("w13_input_scale", w13_input_scale)
            set_weight_attrs(w13_input_scale, extra_weight_attrs)

            w2_input_scale = torch.nn.Parameter(
                torch.ones(num_experts_per_partition, dtype=torch.float32),
                requires_grad=False,
            )
            layer.register_parameter("w2_input_scale", w2_input_scale)
            set_weight_attrs(w2_input_scale, extra_weight_attrs)

        else:
            layer.w13_input_scale = None
            layer.w2_input_scale = None

    def process_weights_after_loading(self, layer: Module) -> None:

        # If checkpoint is fp16, quantize in place.
        if not self.quant_config.is_checkpoint_fp8_serialized:
            # If rocm, use float8_e4m3fnuz as dtype
991
            fp8_dtype = torch.float8_e4m3fnuz if _is_hip else torch.float8_e4m3fn
xiaobochen's avatar
xiaobochen committed
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
            w13_weight = torch.empty_like(layer.w13_weight.data, dtype=fp8_dtype)
            w2_weight = torch.empty_like(layer.w2_weight.data, dtype=fp8_dtype)

            layer.w13_weight_scale = torch.nn.Parameter(
                torch.ones(
                    layer.num_experts_per_partition,
                    dtype=torch.float32,
                    device=w13_weight.device,
                ),
                requires_grad=False,
            )

            for expert in range(layer.num_experts_per_partition):
Lianmin Zheng's avatar
Lianmin Zheng committed
1005
1006
1007
1008
1009
1010
                w13_weight[expert, :, :], layer.w13_weight_scale[expert] = (
                    scaled_fp8_quant(layer.w13_weight.data[expert, :, :])
                )
                w2_weight[expert, :, :], layer.w2_weight_scale[expert] = (
                    scaled_fp8_quant(layer.w2_weight.data[expert, :, :])
                )
xiaobochen's avatar
xiaobochen committed
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
            layer.w13_weight = torch.nn.Parameter(w13_weight, requires_grad=False)
            layer.w2_weight = torch.nn.Parameter(w2_weight, requires_grad=False)
            return

        # If checkpoint is fp8, we need to handle that the
        # MoE kernels require single activation scale and single weight
        # scale for w13 per expert.
        else:
            if self.quant_config.activation_scheme == "static":
                if layer.w13_input_scale is None or layer.w2_input_scale is None:
                    raise ValueError(
                        "QuantConfig has static quantization, but found "
                        "activation scales are None."
                    )
1025
1026
1027
1028
                layer.w13_weight_scale = torch.nn.Parameter(
                    torch.max(layer.w13_weight_scale, dim=1).values,
                    requires_grad=False,
                )
Alex Sun's avatar
Alex Sun committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
            if self.block_quant:
                # If ROCm, normalize the weights and scales to e4m3fnuz
                if _is_fp8_fnuz:
                    # activation_scheme: dynamic
                    w13_weight, w13_weight_scale, _ = normalize_e4m3fn_to_e4m3fnuz(
                        weight=layer.w13_weight,
                        weight_scale=layer.w13_weight_scale_inv,
                        input_scale=None,
                    )
                    w2_weight, w2_weight_scale, _ = normalize_e4m3fn_to_e4m3fnuz(
                        weight=layer.w2_weight,
                        weight_scale=layer.w2_weight_scale_inv,
                        input_scale=None,
                    )
                    # Reset the parameter
                    layer.w13_weight = torch.nn.Parameter(
                        w13_weight, requires_grad=False
                    )
                    layer.w13_weight_scale_inv = torch.nn.Parameter(
                        w13_weight_scale, requires_grad=False
                    )
                    layer.w13_input_scale = None
                    layer.w2_weight = torch.nn.Parameter(w2_weight, requires_grad=False)
                    layer.w2_weight_scale_inv = torch.nn.Parameter(
                        w2_weight_scale, requires_grad=False
                    )
                    layer.w2_input_scale = None
1056
1057
1058
1059
1060
1061
1062
1063
1064
                if _use_aiter:
                    layer.w13_weight = torch.nn.Parameter(
                        shuffle_weight(layer.w13_weight.data, (16, 16)),
                        requires_grad=False,
                    )
                    layer.w2_weight = torch.nn.Parameter(
                        shuffle_weight(layer.w2_weight.data, (16, 16)),
                        requires_grad=False,
                    )
xiaobochen's avatar
xiaobochen committed
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
            return

    def apply(
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
        router_logits: torch.Tensor,
        top_k: int,
        renormalize: bool,
        use_grouped_topk: bool,
        topk_group: Optional[int] = None,
        num_expert_group: Optional[int] = None,
        custom_routing_function: Optional[Callable] = None,
    ) -> torch.Tensor:
        raise NotImplementedError
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094


class DeepEPMoE(EPMoE):
    """
    MoE Expert Parallel Impl based on DeepEP (https://github.com/deepseek-ai/DeepEP/tree/main)
    """

    _has_printed = False

    def __init__(
        self,
        num_experts: int,
        top_k: int,
        hidden_size: int,
        intermediate_size: int,
fzyzcjy's avatar
fzyzcjy committed
1095
        layer_id: int,
1096
1097
1098
1099
        params_dtype: Optional[torch.dtype] = None,
        renormalize: bool = True,
        use_grouped_topk: bool = False,
        num_expert_group: Optional[int] = None,
1100
        num_fused_shared_experts: int = 0,
1101
1102
1103
1104
1105
1106
1107
        topk_group: Optional[int] = None,
        quant_config: Optional[QuantizationConfig] = None,
        tp_size: Optional[int] = None,
        prefix: str = "",
        correction_bias: Optional[torch.Tensor] = None,
        custom_routing_function: Optional[Callable] = None,
        activation: str = "silu",
1108
        routed_scaling_factor: Optional[float] = None,
1109
        deepep_mode: DeepEPMode = DeepEPMode.auto,
1110
1111
    ):
        super().__init__(
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
            num_experts=num_experts,
            top_k=top_k,
            hidden_size=hidden_size,
            intermediate_size=intermediate_size,
            layer_id=layer_id,
            params_dtype=params_dtype,
            renormalize=renormalize,
            use_grouped_topk=use_grouped_topk,
            num_expert_group=num_expert_group,
            num_fused_shared_experts=num_fused_shared_experts,
            topk_group=topk_group,
            quant_config=quant_config,
            tp_size=tp_size,
            prefix=prefix,
            correction_bias=correction_bias,
            custom_routing_function=custom_routing_function,
            activation=activation,
            routed_scaling_factor=routed_scaling_factor,
1130
        )
1131
        self.deepep_mode = deepep_mode
1132
        if self.deepep_mode.enable_low_latency():
1133
1134
1135
            assert (
                deep_gemm_wrapper.ENABLE_JIT_DEEPGEMM
            ), f"DeepEP {self.deepep_mode} mode requires deep_gemm"
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
        if _use_aiter:
            # expert_mask is of size (self.num_experts_per_partition + 1),
            # the extra 1 is for invalid rank_id (in original deepep, the invalid rank_id is -1, but aiter does not allow -1, we use a mask to make those ids invalid)
            # for instance, if we have 4 experts on this rank, we would have a expert_mask like:
            #     self.expert_mask = [1, 1, 1, 1, 0]
            # idx from 0-3 is valid and will be processed, while idx == 4 will be masked out
            self.expert_mask = torch.zeros(
                (self.num_experts_per_partition + 1),
                device=torch.cuda.current_device(),
                dtype=torch.int,
            )
            # the last one is invalid rank_id
            self.expert_mask[:-1] = 1
        else:
            self.w13_weight_fp8 = (
                self.w13_weight,
                (
                    self.w13_weight_scale_inv
                    if self.use_block_quant
                    else self.w13_weight_scale
                ),
            )
            self.w2_weight_fp8 = (
                self.w2_weight,
                (
                    self.w2_weight_scale_inv
                    if self.use_block_quant
                    else self.w2_weight_scale
                ),
            )
1166
1167
1168
1169

    def forward(
        self,
        hidden_states: torch.Tensor,
1170
1171
        topk_idx: torch.Tensor,
        topk_weights: torch.Tensor,
1172
1173
        reorder_topk_ids: torch.Tensor,
        seg_indptr: torch.Tensor,
1174
1175
        masked_m: torch.Tensor,
        expected_m: int,
1176
        num_recv_tokens_per_expert: List[int],
1177
1178
        forward_mode: ForwardMode,
    ):
1179
1180
1181
        if _use_aiter:
            # in forward_aiter, we skip token permutation and unpermutation, which have been fused inside aiter kernel
            return self.forward_aiter(hidden_states, topk_idx, topk_weights)
1182
1183
        resolved_deepep_mode = self.deepep_mode.resolve(forward_mode)
        if resolved_deepep_mode == DeepEPMode.normal:
1184
            if deep_gemm_wrapper.ENABLE_JIT_DEEPGEMM:
1185
1186
1187
1188
1189
                return self.forward_deepgemm_contiguous(
                    hidden_states, topk_idx, topk_weights, num_recv_tokens_per_expert
                )
            else:
                return self.forward_normal(hidden_states, reorder_topk_ids, seg_indptr)
1190
        elif resolved_deepep_mode == DeepEPMode.low_latency:
1191
            return self.forward_deepgemm_masked(hidden_states, masked_m, expected_m)
1192
        else:
1193
            raise ValueError(f"Invalid deepep_mode: {self.deepep_mode}")
1194
1195
1196
1197

    def forward_normal(
        self,
        hidden_states: torch.Tensor,
1198
1199
        reorder_topk_ids: torch.Tensor,
        seg_indptr: torch.Tensor,
1200
    ):
fzyzcjy's avatar
fzyzcjy committed
1201
1202
1203
        hidden_states_dtype = hidden_states.dtype
        hidden_states_device = hidden_states.device

1204
1205
1206
1207
1208
1209
        assert self.quant_method is not None
        assert self.activation == "silu"
        if self.grouped_gemm_runner is None:
            self.grouped_gemm_runner = GroupedGemmRunner(
                hidden_states.device, use_flashinfer=False  # TODO: use flashinfer
            )
1210

1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
        if self.activation_scheme == "dynamic" and not self.use_block_quant:
            max_value = (
                torch.max(hidden_states)
                .repeat(self.num_experts_per_partition)
                .to(torch.float32)
            )
            self.w13_input_scale = max_value / torch.finfo(self.fp8_dtype).max
        weight_indices_cur_rank = torch.arange(
            0,
            self.num_experts_per_partition,
            device=hidden_states.device,
            dtype=torch.int64,
        )

        # GroupGemm-0
        if hidden_states.shape[0] > 0:
            gateup_output = self.grouped_gemm_runner(
                a=hidden_states,
                b=self.w13_weight,
fzyzcjy's avatar
fzyzcjy committed
1230
1231
                c=None,
                c_dtype=hidden_states.dtype,
1232
1233
                batch_size=self.num_experts_per_partition,
                weight_column_major=True,
1234
                seg_indptr=seg_indptr,
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
                weight_indices=weight_indices_cur_rank,
                use_fp8_w8a8=self.use_fp8_w8a8,
                scale_a=self.w13_input_scale,
                scale_b=(
                    self.w13_weight_scale_inv
                    if self.use_block_quant
                    else self.w13_weight_scale
                ),
                block_shape=self.block_shape,
            )
fzyzcjy's avatar
fzyzcjy committed
1245
1246
1247
1248
1249
1250
1251
        else:
            gateup_output = torch.empty(
                hidden_states.shape[0],
                self.w13_weight.shape[1],
                device=hidden_states.device,
                dtype=hidden_states.dtype,
            )
1252
1253
1254
1255
1256
1257
1258
1259
1260

        # Act
        down_input = torch.empty(
            gateup_output.shape[0],
            gateup_output.shape[1] // 2,
            device=gateup_output.device,
            dtype=(
                self.fp8_dtype
                if (self.use_fp8_w8a8 and not self.use_block_quant)
fzyzcjy's avatar
fzyzcjy committed
1261
                else hidden_states_dtype
1262
1263
1264
1265
1266
1267
            ),
        )
        if self.w2_input_scale is None and not self.use_block_quant:
            self.w2_input_scale = torch.ones(
                self.num_experts_per_partition,
                dtype=torch.float32,
fzyzcjy's avatar
fzyzcjy committed
1268
                device=hidden_states_device,
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
            )

        if self.activation == "silu":
            silu_and_mul_triton_kernel[(gateup_output.shape[0],)](
                gateup_output,
                down_input,
                gateup_output.shape[1],
                reorder_topk_ids,
                self.w2_input_scale,
                0,
                self.num_experts_per_partition - 1,
                BLOCK_SIZE=512,
            )
        else:
            raise ValueError(f"Unsupported activation: {self.activation=}")

fzyzcjy's avatar
fzyzcjy committed
1285
1286
        del gateup_output

1287
1288
1289
1290
        # GroupGemm-1
        down_output = torch.empty(
            down_input.shape[0],
            self.w2_weight.shape[1],
fzyzcjy's avatar
fzyzcjy committed
1291
1292
            device=hidden_states_device,
            dtype=hidden_states_dtype,
1293
1294
1295
1296
1297
1298
1299
1300
        )
        if down_input.shape[0] > 0:
            down_output = self.grouped_gemm_runner(
                a=down_input,
                b=self.w2_weight,
                c=down_output,
                batch_size=self.num_experts_per_partition,
                weight_column_major=True,
1301
                seg_indptr=seg_indptr,
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
                weight_indices=weight_indices_cur_rank,
                use_fp8_w8a8=self.use_fp8_w8a8,
                scale_a=self.w2_input_scale,
                scale_b=(
                    self.w2_weight_scale_inv
                    if self.use_block_quant
                    else self.w2_weight_scale
                ),
                block_shape=self.block_shape,
            )
        return down_output

1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
    def forward_aiter(
        self,
        hidden_states: torch.Tensor,
        topk_idx: torch.Tensor,
        topk_weights: torch.Tensor,
    ):
        if hidden_states.shape[0] == 0:
            return hidden_states
        # in original deepep, idx == -1 meaning invalid and will not be processed.
        # aiter does not accept -1, we use a expert mask to make these idx invalid
        # (idx == num_experts_per_partition) meaning not used in aiter fused_moe
        topk_idx_copy = topk_idx.to(torch.int32)
        topk_idx_copy[topk_idx_copy == -1] = self.num_experts_per_partition

        return fused_moe(
            hidden_states,
            self.w13_weight,
            self.w2_weight,
            topk_weights,
            topk_idx_copy,
            w1_scale=self.w13_weight_scale_inv,
            w2_scale=self.w2_weight_scale_inv,
            quant_type=QuantType.per_128x128,
            activation=(
                ActivationType.Silu
                if self.activation == "silu"
                else ActivationType.Gelu
            ),
            expert_mask=self.expert_mask,
        )

1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
    def forward_deepgemm_contiguous(
        self,
        hidden_states_fp8: Tuple[torch.Tensor, torch.Tensor],
        topk_idx,
        topk_weights,
        num_recv_tokens_per_expert: List[int],
    ):
        hidden_states_fp8, hidden_states_scale = hidden_states_fp8
        assert self.quant_method is not None
        assert self.activation == "silu"
        if num_recv_tokens_per_expert is None:
            return hidden_states_fp8.bfloat16()
        all_tokens = sum(num_recv_tokens_per_expert)
        if all_tokens <= 0:
            return hidden_states_fp8.bfloat16()
        M, K = hidden_states_fp8.size()
        N = self.w13_weight.size(1)
        scale_block_size = 128

fzyzcjy's avatar
fzyzcjy committed
1364
1365
1366
        hidden_states_fp8_shape = hidden_states_fp8.shape
        hidden_states_fp8_device = hidden_states_fp8.device
        hidden_states_fp8_dtype = hidden_states_fp8.dtype
1367
1368
1369
1370
1371
1372
1373

        input_tensor = [
            torch.empty(
                (all_tokens, K),
                device=hidden_states_fp8.device,
                dtype=hidden_states_fp8.dtype,
            ),
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
            (
                # TODO check whether need `zeros`
                torch.zeros(
                    (ceil_div(K // 128, 4), all_tokens),
                    device=hidden_states_fp8.device,
                    dtype=torch.int,
                ).transpose(0, 1)
                if deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0
                else torch.empty(
                    (all_tokens, K // 128),
                    device=hidden_states_fp8.device,
                    dtype=torch.float32,
                )
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
            ),
        ]
        m_indices = torch.empty(
            all_tokens, device=hidden_states_fp8.device, dtype=torch.int32
        )
        output_index = torch.empty_like(topk_idx)

        num_recv_tokens_per_expert_gpu = torch.tensor(
            num_recv_tokens_per_expert,
            dtype=torch.int32,
            pin_memory=True,
            device="cpu",
        ).cuda(non_blocking=True)
        expert_start_loc = torch.empty_like(num_recv_tokens_per_expert_gpu)

        ep_scatter(
            hidden_states_fp8,
            hidden_states_scale,
            topk_idx,
            num_recv_tokens_per_expert_gpu,
            expert_start_loc,
            input_tensor[0],
            input_tensor[1],
            m_indices,
            output_index,
1412
            scale_ue8m0=deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0,
1413
        )
fzyzcjy's avatar
fzyzcjy committed
1414
        dispose_tensor(hidden_states_fp8)
1415
1416
1417

        gateup_output = torch.empty(
            (all_tokens, N),
fzyzcjy's avatar
fzyzcjy committed
1418
            device=hidden_states_fp8_device,
1419
1420
            dtype=torch.bfloat16,
        )
1421
1422
        if not deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0:
            input_tensor[1] = tma_align_input_scale(input_tensor[1])
1423
        deep_gemm_wrapper.grouped_gemm_nt_f8f8bf16_contig(
1424
1425
            input_tensor, self.w13_weight_fp8, gateup_output, m_indices
        )
fzyzcjy's avatar
fzyzcjy committed
1426
        del input_tensor
1427
1428
1429
1430
1431
1432
1433
1434
1435
        down_input = torch.empty(
            (
                all_tokens,
                N // 2,
            ),
            device=gateup_output.device,
            dtype=torch.bfloat16,
        )
        silu_and_mul(gateup_output.view(-1, N), down_input)
fzyzcjy's avatar
fzyzcjy committed
1436
        del gateup_output
1437
1438
        down_output = torch.empty(
            (all_tokens, K),
fzyzcjy's avatar
fzyzcjy committed
1439
            device=hidden_states_fp8_device,
1440
1441
1442
            dtype=torch.bfloat16,
        )
        down_input_fp8, down_input_scale = sglang_per_token_group_quant_fp8(
1443
1444
1445
1446
1447
            down_input,
            scale_block_size,
            column_major_scales=deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0,
            scale_tma_aligned=deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0,
            scale_ue8m0=deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0,
1448
        )
fzyzcjy's avatar
fzyzcjy committed
1449
        del down_input
1450
1451
        if not deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0:
            down_input_scale = tma_align_input_scale(down_input_scale)
1452
        deep_gemm_wrapper.grouped_gemm_nt_f8f8bf16_contig(
1453
1454
1455
1456
1457
            (down_input_fp8, down_input_scale),
            self.w2_weight_fp8,
            down_output,
            m_indices,
        )
fzyzcjy's avatar
fzyzcjy committed
1458
        del down_input_fp8, down_input_scale
1459

fzyzcjy's avatar
fzyzcjy committed
1460
1461
1462
1463
1464
        gather_out = torch.empty(
            hidden_states_fp8_shape,
            device=hidden_states_fp8_device,
            dtype=torch.bfloat16,
        )
1465
1466
1467
1468
        ep_gather(down_output, topk_idx, topk_weights, output_index, gather_out)

        return gather_out

1469
1470
    def forward_deepgemm_masked(
        self,
1471
1472
1473
        hidden_states_fp8: Tuple[torch.Tensor, torch.Tensor],
        masked_m: torch.Tensor,
        expected_m: int,
1474
1475
1476
1477
1478
    ):
        assert self.quant_method is not None
        assert self.activation == "silu"

        # GroupGemm-0
1479
1480
1481
        num_groups, m, k = hidden_states_fp8[0].size()
        n = self.w13_weight.size(1)
        expected_m = min(expected_m, m)
1482
        gateup_output = torch.empty(
1483
1484
            (num_groups, m, n), device=hidden_states_fp8[0].device, dtype=torch.bfloat16
        )
1485
1486
1487
1488
1489
1490
        deep_gemm_wrapper.grouped_gemm_nt_f8f8bf16_masked(
            hidden_states_fp8,
            self.w13_weight_fp8,
            gateup_output,
            masked_m,
            expected_m,
1491
            recipe=(1, 128, 128) if deep_gemm_wrapper.DEEPGEMM_BLACKWELL else None,
1492
        )
fzyzcjy's avatar
fzyzcjy committed
1493
        dispose_tensor(hidden_states_fp8[0])
1494
1495
1496

        # Act
        down_input = torch.empty(
1497
1498
1499
1500
            (
                gateup_output.shape[0],
                gateup_output.shape[1],
                gateup_output.shape[2] // 2,
1501
            ),
1502
1503
            device=gateup_output.device,
            dtype=self.fp8_dtype,
1504
        )
1505
1506
1507
1508
        scale_block_size = 128
        down_input_scale = torch.empty(
            (
                gateup_output.shape[0],
1509
                gateup_output.shape[1],
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
                gateup_output.shape[2] // 2 // scale_block_size,
            ),
            device=gateup_output.device,
            dtype=torch.float32,
        )
        silu_and_mul_masked_post_quant_fwd(
            gateup_output,
            down_input,
            down_input_scale,
            scale_block_size,
            masked_m,
fzyzcjy's avatar
fzyzcjy committed
1521
            scale_ue8m0=deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0,
1522
        )
fzyzcjy's avatar
fzyzcjy committed
1523
        del gateup_output
1524
1525

        # GroupGemm-1
1526
1527
1528
        n = self.w2_weight.size(1)
        down_input_fp8 = (
            down_input,
fzyzcjy's avatar
fzyzcjy committed
1529
1530
1531
1532
1533
1534
1535
            (
                down_input_scale
                if deep_gemm_wrapper.DEEPGEMM_SCALE_UE8M0
                else deep_gemm_wrapper.get_col_major_tma_aligned_tensor(
                    down_input_scale
                )
            ),
1536
        )
1537
        down_output = torch.empty(
1538
1539
            (num_groups, m, n), device=down_input.device, dtype=torch.bfloat16
        )
1540
1541
1542
1543
1544
1545
        deep_gemm_wrapper.grouped_gemm_nt_f8f8bf16_masked(
            down_input_fp8,
            self.w2_weight_fp8,
            down_output,
            masked_m,
            expected_m,
1546
            recipe=(1, 128, 128) if deep_gemm_wrapper.DEEPGEMM_BLACKWELL else None,
1547
1548
1549
        )

        return down_output
1550
1551
1552
1553
1554


def get_moe_impl_class():
    if global_server_args_dict["enable_deepep_moe"]:
        return DeepEPMoE
1555
1556
1557
    if global_server_args_dict["enable_flashinfer_moe"]:
        # Must come before EPMoE because FusedMoE also supports enable_ep_moe
        return FusedMoE
1558
1559
1560
    if global_server_args_dict["enable_ep_moe"]:
        return EPMoE
    return FusedMoE