Skip to content

vllm.model_executor.layers.fused_moe.experts.gpt_oss_triton_kernels_moe

Classes:

Functions:

BaseOAITritonExperts

Bases: FusedMoEExpertsModular

Methods:

  • moe_problem_size –

    Extract the MoE problem size from the given tensor arguments:

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
class BaseOAITritonExperts(mk.FusedMoEExpertsModular):
    @property
    def expects_unquantized_inputs(self) -> bool:
        return True

    @staticmethod
    def _supports_current_device() -> bool:
        return _triton_kernel_moe_supports_current_device() and has_triton_kernels()

    @staticmethod
    def _supports_no_act_and_mul() -> bool:
        return False

    @staticmethod
    def _supports_quant_scheme(
        weight_key: QuantKey | None,
        activation_key: QuantKey | None,
    ) -> bool:
        SUPPORTED_W_A = [
            (kMxfp4Static, None),
        ]
        return (weight_key, activation_key) in SUPPORTED_W_A

    @staticmethod
    def _supports_activation(activation: MoEActivation) -> bool:
        raise NotImplementedError

    @staticmethod
    def _supports_parallel_config(moe_parallel_config: FusedMoEParallelConfig) -> bool:
        return True

    def moe_problem_size(
        self,
        a1: torch.Tensor,
        w1: torch.Tensor,
        w2: torch.Tensor,
        topk_ids: torch.Tensor,
    ) -> tuple[int, int, int, int, int]:
        """Extract the MoE problem size from the given tensor arguments:
        - a: The hidden states, input to the MoE layer.
        - w1: The first set of expert weights.
        - w2: The second set of expert weights.
        - topk_ids: The topk ids.
        Note: extracting the problem shape from the weight and activation
        tensors is not obvious.  It needs to be done this way specifically
        due to subtle issues with particular kernels, e.g. the int4 kernels
        divide the trailing dimension by two, so it's not "correct" to
        extract N or K from the trailing dimension of w1 or w2.  Similarly,
        some kernels transpose the weights, so this needs to be kept in mind.
        Note: This implementation covers most cases. However, if experts
        require a specialized implementation, like MarlinExperts, they are free
        to override this function.
        """
        assert len(w1.shape) == 3 and len(w2.shape) == 3
        E, _, N = w1.shape
        K = a1.size(-1)

        assert a1.dim() == 2
        assert topk_ids.size(0) == a1.size(0), f"{topk_ids.size(0)} != {a1.size(0)}"
        M = a1.size(0)

        assert topk_ids.dim() == 2
        topk = topk_ids.size(1)

        return E, M, N, K, topk

    def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
        # Weight application and reduction happens in the fused_experts kernel.
        return TopKWeightAndReduceNoOP()

    def _make_routing_data(
        self,
        topk_ids: torch.Tensor,
        topk_weights: torch.Tensor,
        num_local_experts: int,
    ) -> tuple["RoutingData", torch.Tensor, torch.Tensor]:
        return make_routing_data(topk_ids, topk_weights, num_local_experts)

moe_problem_size(a1, w1, w2, topk_ids)

Extract the MoE problem size from the given tensor arguments: - a: The hidden states, input to the MoE layer. - w1: The first set of expert weights. - w2: The second set of expert weights. - topk_ids: The topk ids. Note: extracting the problem shape from the weight and activation tensors is not obvious. It needs to be done this way specifically due to subtle issues with particular kernels, e.g. the int4 kernels divide the trailing dimension by two, so it's not "correct" to extract N or K from the trailing dimension of w1 or w2. Similarly, some kernels transpose the weights, so this needs to be kept in mind. Note: This implementation covers most cases. However, if experts require a specialized implementation, like MarlinExperts, they are free to override this function.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
def moe_problem_size(
    self,
    a1: torch.Tensor,
    w1: torch.Tensor,
    w2: torch.Tensor,
    topk_ids: torch.Tensor,
) -> tuple[int, int, int, int, int]:
    """Extract the MoE problem size from the given tensor arguments:
    - a: The hidden states, input to the MoE layer.
    - w1: The first set of expert weights.
    - w2: The second set of expert weights.
    - topk_ids: The topk ids.
    Note: extracting the problem shape from the weight and activation
    tensors is not obvious.  It needs to be done this way specifically
    due to subtle issues with particular kernels, e.g. the int4 kernels
    divide the trailing dimension by two, so it's not "correct" to
    extract N or K from the trailing dimension of w1 or w2.  Similarly,
    some kernels transpose the weights, so this needs to be kept in mind.
    Note: This implementation covers most cases. However, if experts
    require a specialized implementation, like MarlinExperts, they are free
    to override this function.
    """
    assert len(w1.shape) == 3 and len(w2.shape) == 3
    E, _, N = w1.shape
    K = a1.size(-1)

    assert a1.dim() == 2
    assert topk_ids.size(0) == a1.size(0), f"{topk_ids.size(0)} != {a1.size(0)}"
    M = a1.size(0)

    assert topk_ids.dim() == 2
    topk = topk_ids.size(1)

    return E, M, N, K, topk

OAITritonExperts

Bases: BaseOAITritonExperts

OAI Triton-based fused MoE expert implementation.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
class OAITritonExperts(BaseOAITritonExperts):
    """OAI Triton-based fused MoE expert implementation."""

    @staticmethod
    def _supports_activation(activation: MoEActivation) -> bool:
        return activation == MoEActivation.SWIGLUOAI

    @staticmethod
    def activation_format() -> mk.FusedMoEActivationFormat:
        return mk.FusedMoEActivationFormat.Standard

    def workspace_shapes(
        self,
        M: int,
        N: int,
        K: int,
        topk: int,
        global_num_experts: int,
        local_num_experts: int,
        expert_tokens_meta: mk.ExpertTokensMetadata | None,
        activation: MoEActivation,
    ) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
        # workspace are allocated inside the kernel
        activation_out_dim = self.adjust_N_for_activation(N, activation)
        workspace1 = (0, 0)
        workspace2 = (M * topk, activation_out_dim)
        output = (M, K)
        return (workspace1, workspace2, output)

    def apply(
        self,
        output: torch.Tensor,
        hidden_states: torch.Tensor,
        w1: torch.Tensor,
        w2: torch.Tensor,
        topk_weights: torch.Tensor,
        topk_ids: torch.Tensor,
        activation: MoEActivation,
        global_num_experts: int,
        expert_map: torch.Tensor | None,
        a1q_scale: torch.Tensor | None,
        a2_scale: torch.Tensor | None,
        workspace13: torch.Tensor,
        workspace2: torch.Tensor,
        expert_tokens_meta: mk.ExpertTokensMetadata | None,
        apply_router_weight_on_input: bool,
    ):
        if self.quant_config is None:
            self.quant_config: FusedMoEQuantConfig = FUSED_MOE_UNQUANTIZED_CONFIG

        if expert_map is not None:
            # Preserve -1 (invalid / non-local slots, e.g. from EP dispatch):
            # make_routing_data treats -1 as the skip sentinel.
            topk_ids = remap_topk_to_local(topk_ids, expert_map)

        local_num_experts = w1.shape[0]
        if global_num_experts == -1:
            global_num_experts = local_num_experts

        routing_data, gather_indx, scatter_indx = self._make_routing_data(
            topk_ids, topk_weights, local_num_experts
        )

        topk = topk_ids.size(1)
        triton_kernel_fused_experts(
            output,
            hidden_states,
            w1,
            w2,
            routing_data,
            gather_indx,
            scatter_indx,
            topk=topk,
            activation=activation,
            quant_config=self.quant_config,
            apply_router_weight_on_input=False,
            global_num_experts=local_num_experts,
            expert_map=None,  # applied already
            intermediate_cache=workspace2,
            a1q_scale=a1q_scale,
        )

OAITritonMxfp4ExpertsMonolithic

Bases: FusedMoEExpertsMonolithic

Monolithic Triton MXFP4 expert. Wraps triton_kernel_moe_forward().

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
class OAITritonMxfp4ExpertsMonolithic(mk.FusedMoEExpertsMonolithic):
    """Monolithic Triton MXFP4 expert. Wraps triton_kernel_moe_forward()."""

    def __init__(
        self,
        moe_config: FusedMoEConfig,
        quant_config: FusedMoEQuantConfig,
    ):
        super().__init__(moe_config, quant_config)
        self.topk = moe_config.experts_per_token
        self.renormalize = moe_config.routing_method in (
            RoutingMethodType.Renormalize,
            RoutingMethodType.RenormalizeNaive,
        )

    @staticmethod
    def activation_format() -> mk.FusedMoEActivationFormat:
        return mk.FusedMoEActivationFormat.Standard

    @staticmethod
    def _supports_current_device() -> bool:
        return _triton_kernel_moe_supports_current_device() and has_triton_kernels()

    @staticmethod
    def _supports_no_act_and_mul() -> bool:
        return False

    @staticmethod
    def _supports_quant_scheme(
        weight_key: QuantKey | None,
        activation_key: QuantKey | None,
    ) -> bool:
        SUPPORTED_W_A = [
            (kMxfp4Static, None),
        ]
        return (weight_key, activation_key) in SUPPORTED_W_A

    @staticmethod
    def _supports_activation(activation: MoEActivation) -> bool:
        return activation == MoEActivation.SWIGLUOAI

    @staticmethod
    def _supports_parallel_config(
        moe_parallel_config: FusedMoEParallelConfig,
    ) -> bool:
        return (
            not moe_parallel_config.use_all2all_kernels
            and not moe_parallel_config.enable_eplb
            and moe_parallel_config.dp_size <= 1
        )

    @staticmethod
    def _supports_routing_method(
        routing_method: RoutingMethodType,
        weight_key: QuantKey | None,
        activation_key: QuantKey | None,
    ) -> bool:
        return routing_method in [
            RoutingMethodType.Renormalize,
            RoutingMethodType.RenormalizeNaive,
        ]

    @staticmethod
    def _supports_router_logits_dtype(
        router_logits_dtype: torch.dtype | None,
        routing_method: RoutingMethodType,
    ) -> bool:
        return True

    @property
    def expects_unquantized_inputs(self) -> bool:
        return True

    def apply(
        self,
        hidden_states: torch.Tensor,
        w1: torch.Tensor,
        w2: torch.Tensor,
        router_logits: torch.Tensor,
        activation: MoEActivation,
        global_num_experts: int,
        expert_map: torch.Tensor | None,
        a1q_scale: torch.Tensor | None,
        apply_router_weight_on_input: bool,
        # grouped topk + fused topk bias parameters
        num_expert_group: int | None = None,
        e_score_correction_bias: torch.Tensor | None = None,
        routed_scaling_factor: float | None = None,
        topk_group: int | None = None,
        routing_replay_out: torch.Tensor | None = None,
    ) -> torch.Tensor:
        return triton_kernel_moe_forward(
            hidden_states=hidden_states,
            w1=w1,
            w2=w2,
            gating_output=router_logits,
            topk=self.topk,
            renormalize=self.renormalize,
            global_num_experts=global_num_experts,
            expert_map=expert_map,
            quant_config=self.quant_config,
            apply_router_weight_on_input=apply_router_weight_on_input,
        )

UnfusedOAITritonExperts

Bases: LoRAExpertsMixin, BaseOAITritonExperts

A Triton based MoE expert class that operates on expert standard format and explicitly keeps the activation and reduction (moe_sum) steps unfused from the matmul_ogs kernel. This exposes injection points for activation and moe_sum.

One use case for it is to inject LoRA modules on the activation and moe_sum.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
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
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
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
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
class UnfusedOAITritonExperts(LoRAExpertsMixin, BaseOAITritonExperts):
    """A Triton based MoE expert class that operates on expert standard
    format and explicitly keeps the activation and reduction (moe_sum) steps
    unfused from the matmul_ogs kernel. This exposes injection points
    for activation and moe_sum.

    One use case for it is to inject LoRA modules on the activation and moe_sum.
    """

    @staticmethod
    def _supports_activation(activation: MoEActivation) -> bool:
        return activation in [
            MoEActivation.SILU,
            MoEActivation.GELU,
            MoEActivation.SWIGLUOAI,
            MoEActivation.SWIGLUSTEP,
            MoEActivation.SWIGLUOAI_UNINTERLEAVE,
        ]

    @staticmethod
    def activation_format() -> mk.FusedMoEActivationFormat:
        return mk.FusedMoEActivationFormat.Standard

    def workspace_shapes(
        self,
        M: int,
        N: int,
        K: int,
        topk: int,
        global_num_experts: int,
        local_num_experts: int,
        expert_tokens_meta: mk.ExpertTokensMetadata | None,
        activation: MoEActivation,
    ) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
        # workspace are allocated inside the kernel
        activation_out_dim = self.adjust_N_for_activation(N, activation)
        workspace1 = (M * topk, activation_out_dim)
        workspace2 = (M * topk, max(N, K))
        output = (M, K)
        return (workspace1, workspace2, output)

    def activation(
        self,
        activation: MoEActivation,
        output: torch.Tensor,
        input: torch.Tensor,
        **kwargs,
    ) -> None:
        quant_config = self.quant_config or FUSED_MOE_UNQUANTIZED_CONFIG
        if activation == MoEActivation.SWIGLUOAI:
            alpha = (
                quant_config.gemm1_alpha
                if quant_config.gemm1_alpha is not None
                else 1.702
            )
            limit = (
                quant_config.gemm1_clamp_limit
                if quant_config.gemm1_clamp_limit is not None
                else 7.0
            )
            torch.ops._C.swigluoai_and_mul(output, input, alpha, limit)
        elif (
            activation == MoEActivation.SILU
            and quant_config.gemm1_clamp_limit is not None
        ):
            swiglu_limit_func(
                output,
                input,
                quant_config.gemm1_clamp_limit,
            )
        elif activation == MoEActivation.SWIGLUOAI_UNINTERLEAVE:
            assert quant_config.gemm1_clamp_limit is not None
            alpha = (
                quant_config.gemm1_alpha
                if quant_config.gemm1_alpha is not None
                else 1.0
            )
            beta = (
                quant_config.gemm1_beta if quant_config.gemm1_beta is not None else 0.0
            )
            torch.ops._C.silu_and_mul_with_clamp(
                output, input, quant_config.gemm1_clamp_limit, alpha, beta
            )
        else:
            super().activation(activation, output, input)

    def apply(
        self,
        output: torch.Tensor,
        hidden_states: torch.Tensor,
        w1: torch.Tensor,
        w2: torch.Tensor,
        topk_weights: torch.Tensor,
        topk_ids: torch.Tensor,
        activation: MoEActivation,
        global_num_experts: int,
        expert_map: torch.Tensor | None,
        a1q_scale: torch.Tensor | None,
        a2_scale: torch.Tensor | None,
        workspace13: torch.Tensor,
        workspace2: torch.Tensor,
        expert_tokens_meta: mk.ExpertTokensMetadata | None,
        apply_router_weight_on_input: bool,
    ):
        # Use local variable to help mypy narrow the type after None check
        quant_config = self.quant_config
        if quant_config is None:
            quant_config = FUSED_MOE_UNQUANTIZED_CONFIG

        global_topk_ids = topk_ids
        if expert_map is not None:
            # Preserve -1 (invalid / non-local slots, e.g. from EP dispatch):
            # make_routing_data treats -1 as the skip sentinel.
            topk_ids = remap_topk_to_local(topk_ids, expert_map)

        local_num_experts = w1.shape[0]
        if global_num_experts == -1:
            global_num_experts = local_num_experts

        routing_data, gather_indx, scatter_indx = self._make_routing_data(
            topk_ids, topk_weights, local_num_experts
        )

        topk = topk_ids.size(1)

        if triton_kernels_version == "3.8":
            # Activation and topk-reduce kept unfused from the matmuls (3.8 has
            # no in-kernel scatter+reduce); combine via external index_add.
            act_out_dim = self.adjust_N_for_activation(w1.shape[2], activation)
            M, K = hidden_states.shape[-2:]
            a_ragged = routing_data.ragged
            gather_tok = routing_data.gather_tok
            gammas = routing_data.gate_scal
            inter = matmul(
                hidden_states,
                w1,
                quant_config.w1_bias,
                a_ragged,
                None,
                gather_tok,
                None,
                quant_config.w1_precision,
                gammas=gammas if apply_router_weight_on_input else None,
            )

            lora_context = self._lora_context
            if lora_context is not None:
                s_ids = e_ids = n_pad = t_map = None
                s_ids, e_ids, n_pad, t_map = self.apply_w13_lora(
                    lora_context,
                    y=inter,
                    x=hidden_states,
                    topk_ids=global_topk_ids,
                    topk_weights=topk_weights,
                    expert_map=expert_map,
                    w1=w1,
                    w2=w2,
                    num_tokens=M,
                    top_k_num=topk,
                )

            act_out = torch.empty(
                (routing_data.n_valid, act_out_dim),
                dtype=hidden_states.dtype,
                device=hidden_states.device,
            )
            self.activation(activation, act_out, inter)
            down = matmul(
                act_out,
                w2,
                quant_config.w2_bias,
                a_ragged,
                None,
                None,
                None,
                quant_config.w2_precision,
                gammas=None if apply_router_weight_on_input else gammas,
            )

            if lora_context is not None:
                # w2 LoRA works in (num_tokens, topk, K) token-topk order. Scatter
                # the ragged rows there via the same expert-sort permutation
                # (flat idx = token*topk + slot = argsort(flat_e)), apply, then
                # gather the LoRA-updated rows back to ragged order for the combine.
                flat_e = topk_ids.reshape(-1).to(torch.int64).clamp(min=0)
                order = torch.argsort(flat_e, stable=True)
                down_tt = down.new_zeros((M * topk, K))
                down_tt[order] = down
                self.apply_w2_lora(
                    lora_context,
                    y=down_tt.view(M, topk, K),
                    x=act_out,
                    topk_weights=topk_weights,
                    sorted_token_ids_lora=s_ids,
                    expert_ids_lora=e_ids,
                    num_tokens_post_padded_lora=n_pad,
                    token_lora_mapping=t_map,
                    num_tokens=M,
                    w1=w1,
                    w2=w2,
                    top_k_num=topk,
                )
                down = down_tt[order]

            acc = torch.zeros((M, K), dtype=torch.float32, device=hidden_states.device)
            acc.index_add_(0, gather_tok.to(torch.int64), down.to(torch.float32))
            output.view(M, K).copy_(acc.to(output.dtype))
            return

        # type check, uint8 means mxfp4
        assert hidden_states.dtype == torch.bfloat16
        assert (
            quant_config.w1_bias is None or quant_config.w1_bias.dtype == torch.float32
        )
        assert (
            quant_config.w2_bias is None or quant_config.w2_bias.dtype == torch.float32
        )

        # Shape check, only check non-mxfp4
        assert hidden_states.ndim == 2
        assert hidden_states.shape[-1] == w1.shape[-2]
        assert w2.shape[-1] == w1.shape[1]

        batch_dim = 1
        M, K = hidden_states.shape
        E, _, N = w1.shape

        if global_num_experts == -1:
            global_num_experts = E

        # Note that the output tensor might be in workspace13
        intermediate_cache1 = _resize_cache(workspace2, (batch_dim, M * topk, N))
        intermediate_cache3 = _resize_cache(workspace2, (batch_dim, M * topk, K))
        activation_out_dim = self.adjust_N_for_activation(N, activation)
        intermediate_cache2 = _resize_cache(workspace13, (M * topk, activation_out_dim))

        gammas = routing_data.gate_scal if routing_data else None
        _constrain_sm12x_block_m(M * topk, E)

        matmul_ogs(
            hidden_states,
            w1,
            quant_config.w1_bias,
            routing_data,
            gather_indx=gather_indx,
            precision_config=quant_config.w1_precision,
            gammas=gammas if apply_router_weight_on_input else None,
            fused_activation=None,
            y=intermediate_cache1,
        )

        # w13 LoRA: gather the activation input from expert-sorted
        # intermediate_cache1, then add the LoRA delta in-place on that copy
        # before passing it to activation — exactly mirroring the old
        # decorator approach which modified the gathered tensor in-place.
        act_input = intermediate_cache1.view(-1, N)[gather_indx.dst_indx]

        sorted_token_ids_lora = None
        expert_ids_lora = None
        num_tokens_post_padded_lora = None
        token_lora_mapping = None
        lora_context = self._lora_context
        if lora_context is not None:
            (
                sorted_token_ids_lora,
                expert_ids_lora,
                num_tokens_post_padded_lora,
                token_lora_mapping,
            ) = self.apply_w13_lora(
                lora_context,
                y=act_input,
                x=hidden_states,
                topk_ids=global_topk_ids,
                topk_weights=topk_weights,
                expert_map=expert_map,
                w1=w1,
                w2=w2,
                num_tokens=M,
                top_k_num=topk,
            )

        self.activation(
            activation,
            intermediate_cache2,
            act_input,
        )

        # matmul_ogs grouped reduction fuses sum across multiple experts:
        # y[dst_indx // n_expts_act, :] += x
        # Set n_expts_act to 1 to unfuse the sum so we can do it manually via moe_sum.
        routing_data.n_expts_act = 1

        matmul_ogs(
            intermediate_cache2[gather_indx.src_indx],
            w2,
            quant_config.w2_bias,
            routing_data,
            scatter_indx=scatter_indx,
            precision_config=quant_config.w2_precision,
            gammas=None if apply_router_weight_on_input else gammas,
            y=intermediate_cache3,
        )

        # w2 LoRA: after matmul_ogs with scatter_indx, intermediate_cache3 is
        # in token-topk order, matching the (M, topk, K) layout add_lora_w2 expects.
        if lora_context is not None:
            self.apply_w2_lora(
                lora_context,
                y=intermediate_cache3.view(-1, topk, K),
                x=intermediate_cache2,
                topk_weights=topk_weights,
                sorted_token_ids_lora=sorted_token_ids_lora,
                expert_ids_lora=expert_ids_lora,
                num_tokens_post_padded_lora=num_tokens_post_padded_lora,
                token_lora_mapping=token_lora_mapping,
                num_tokens=M,
                w1=w1,
                w2=w2,
                top_k_num=topk,
            )

        # matmul_ogs leaves invalid (-1 / non-local EP) slots unwritten.
        # Reduce over topk skipping those slots.
        masked_moe_sum(intermediate_cache3.view(-1, topk, K), topk_ids, output)

_constrain_sm12x_block_m(num_rows, num_experts)

Pin block_m for the following matmul_ogs calls on SM12x.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
def _constrain_sm12x_block_m(num_rows: int, num_experts: int) -> None:
    """Pin block_m for the following matmul_ogs calls on SM12x."""
    if not _is_sm12x():
        return
    import triton_kernels.matmul_ogs_details.opt_flags as opt_flags

    opt_flags.update_opt_flags_constraints(
        {"block_m": _sm12x_block_m(num_rows, num_experts)}
    )

_patch_legacy_routing_for_nonpow2_topk()

Monkey-patch the legacy (v3.5.1) triton_kernels routing path to support non-power-of-2 top_k (e.g. DeepSeek-V4 top_k=6).

The bundled _routing_compute_indx does tl.arange(0, N_EXPTS_ACT * BLOCK_M), which fails to compile when N_EXPTS_ACT (top_k) is not a power of 2 (6 * 32 = 192). This installs a pow2-safe variant that pads the tl.arange to the next power of 2, strides by the real per-block size, and masks the padded tail so it neither loads the next block's gates nor writes any output. For power-of-2 top_k it is identical to the original.

A matching sort_tokens is installed that threads the padded size into the patched kernel. Only needed on the legacy path; the v3.6+ SparseMatrix path is handled by _patch_make_bitmatrix_metadata.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
def _patch_legacy_routing_for_nonpow2_topk() -> None:
    """Monkey-patch the legacy (v3.5.1) triton_kernels routing path to support
    non-power-of-2 top_k (e.g. DeepSeek-V4 top_k=6).

    The bundled ``_routing_compute_indx`` does ``tl.arange(0, N_EXPTS_ACT *
    BLOCK_M)``, which fails to compile when ``N_EXPTS_ACT`` (top_k) is not a
    power of 2 (6 * 32 = 192). This installs a pow2-safe variant that pads the
    ``tl.arange`` to the next power of 2, strides by the real per-block size,
    and masks the padded tail so it neither loads the next block's gates nor
    writes any output. For power-of-2 top_k it is identical to the original.

    A matching ``sort_tokens`` is installed that threads the padded size into
    the patched kernel. Only needed on the legacy path; the v3.6+ SparseMatrix
    path is handled by ``_patch_make_bitmatrix_metadata``.
    """
    import triton
    import triton.language as tl

    # Import via the `triton_kernels` alias (set up by has_triton_kernels) so
    # we patch the SAME module object that `make_routing_data` consumes. The
    # `vllm.third_party.triton_kernels.routing` path is a *different* module
    # object under the import alias, so patching it would have no effect.
    try:
        import triton_kernels.routing as _routing
        from triton_kernels.routing_details import _routing_compute as _rc
    except ImportError:
        return

    _keyed_add = _rc._keyed_add
    _expt_data_compute = _rc._expt_data_compute

    @triton.jit
    def _routing_compute_indx_pow2(
        pid_m,
        GatherIndx,
        ScatterIndx,
        GateScal,
        ExptScal,
        ExptIndx,
        PartialOffs,
        stride_pm,
        stride_pn,
        TokensStart,
        n_tokens,
        BLOCK_M: tl.constexpr,
        N_EXPTS_ACT: tl.constexpr,
        BLOCK_SIZE_PADDED: tl.constexpr,
    ):
        if isinstance(n_tokens, tl.tensor) and n_tokens.dtype.is_ptr():
            n_tokens = tl.load(n_tokens)
        n_gates = n_tokens * N_EXPTS_ACT
        BLOCK_SIZE: tl.constexpr = N_EXPTS_ACT * BLOCK_M
        tl.static_assert(BLOCK_SIZE_PADDED <= 32768)
        local_offs = tl.arange(0, BLOCK_SIZE_PADDED)
        offs = pid_m * BLOCK_SIZE + local_offs
        expert = tl.load(
            ExptIndx + offs,
            mask=(local_offs < BLOCK_SIZE) & (offs < n_gates),
            other=-1,
        ).to(tl.uint32)
        kv_pairs = ((expert << 16) | local_offs).to(tl.uint32)
        kv_pairs = tl.sort(kv_pairs, 0)
        expert = kv_pairs >> 16
        offs = pid_m * BLOCK_SIZE + (kv_pairs & 0xFFFF)
        mask = expert != 0xFFFF
        gate_scal = tl.load(ExptScal + offs, mask=mask)
        x = kv_pairs & 0xFFFF0000 | 0x00000001
        run_lengths = tl.associative_scan(x, 0, _keyed_add)
        exclusive_run_lengths = (run_lengths - 1) & 0xFFFF
        gates = tl.load(PartialOffs + pid_m * stride_pm + expert * stride_pn, mask=mask)
        gates += tl.load(TokensStart + expert, mask=mask)
        gates += exclusive_run_lengths
        tl.store(ScatterIndx + offs, gates, mask=mask)
        tl.store(GatherIndx + gates, offs, mask=mask)
        tl.store(GateScal + gates, gate_scal, mask=mask)

    @triton.jit
    def _combined_routing_compute_pow2(
        GatherIndx,
        ScatterIndx,
        GateScal,
        ExptScal,
        ExptIndx,
        PartialOffs,
        stride_pm,
        stride_pn,
        TokensStart,
        n_tokens,
        BLOCK_M: tl.constexpr,
        N_EXPTS_ACT: tl.constexpr,
        Hist,
        MDTileStarts,
        tile_starts_stridem,
        MDTileInfo,
        tile_info_stridem,
        first_tile_dim_log2,
        SIZES: tl.constexpr,
        BLOCK: tl.constexpr,
        blocks2a,
        BLOCK_SIZE_PADDED: tl.constexpr,
    ):
        pid = tl.program_id(0)
        if pid < blocks2a:
            _expt_data_compute(
                Hist,
                MDTileStarts,
                tile_starts_stridem,
                MDTileInfo,
                tile_info_stridem,
                first_tile_dim_log2,
                SIZES,
                BLOCK,
            )
        else:
            pid -= blocks2a
            _routing_compute_indx_pow2(
                pid,
                GatherIndx,
                ScatterIndx,
                GateScal,
                ExptScal,
                ExptIndx,
                PartialOffs,
                stride_pm,
                stride_pn,
                TokensStart,
                n_tokens,
                BLOCK_M,
                N_EXPTS_ACT,
                BLOCK_SIZE_PADDED,
            )

    def _sort_tokens_pow2(expt_scal, expt_indx, n_expts_tot, bitmatrix):
        import torch

        HIST_BLOCK_M = 32
        INDX_OFFS_BLOCK_M = 512
        MEMSET_BLOCK = 1024
        cdiv = triton.cdiv
        device = expt_scal.device
        dtype = expt_scal.dtype
        n_tokens_raw, _ = bitmatrix.shape
        n_tokens_pad, n_expts_act = expt_scal.shape
        n_gates_pad = n_tokens_pad * n_expts_act
        # pad per-block gate count (HIST_BLOCK_M * top_k) up to a pow2.
        block_size_padded = triton.next_power_of_2(HIST_BLOCK_M * n_expts_act)

        hist, partial_hist = bitmatrix.sum(partials_block_size=HIST_BLOCK_M)
        hist = hist[:n_expts_tot]
        expt_offs = torch.empty(n_expts_tot, dtype=torch.int32, device=device)
        combined_indx = torch.empty(n_gates_pad * 2, dtype=torch.int32, device=device)
        topk_indx = combined_indx[:n_gates_pad]
        gate_indx = combined_indx[n_gates_pad:]
        gate_scal = torch.empty(n_gates_pad, dtype=dtype, device=device)

        (
            token_offs_combined,
            token_offs_raw,
            token_offs_pad,
            block_pid_map,
            blocks1a,
            blocks2a,
            MEMSET_BLOCK_A,
            HIST2_BLOCK_M,
            block_m_log2_start,
            block_m_num,
        ) = _routing._compute_expt_data_internal(hist, n_expts_tot, n_gates_pad)

        blocks1b = cdiv(n_gates_pad * 2, MEMSET_BLOCK) + n_expts_tot + 1
        blocks2b = cdiv(n_tokens_pad, HIST_BLOCK_M)

        _rc._combined_routing_memset[(blocks1a + blocks1b,)](
            combined_indx,
            n_gates_pad * 2,
            -1,
            MEMSET_BLOCK,
            hist,
            expt_offs,
            hist.shape[0],
            n_expts_tot,
            partial_hist,
            partial_hist.shape[0],
            partial_hist.stride(0),
            partial_hist.stride(1),
            token_offs_combined,
            token_offs_combined.stride(0),
            blocks1a,
            block_pid_map,
            block_m_log2_start,
            SIZES=block_m_num,
            BLOCK_A=MEMSET_BLOCK_A,
            BLOCK_N=512,
            BLOCK_M=INDX_OFFS_BLOCK_M,
        )

        indx_offs = partial_hist
        _combined_routing_compute_pow2[(blocks2a + blocks2b,)](
            topk_indx,
            gate_indx,
            gate_scal,
            expt_scal,
            expt_indx,
            indx_offs,
            indx_offs.stride(0),
            indx_offs.stride(1),
            expt_offs,
            n_tokens_raw,
            HIST_BLOCK_M,
            n_expts_act,
            hist,
            token_offs_pad,
            token_offs_pad.stride(0),
            block_pid_map,
            block_pid_map.stride(0),
            block_m_log2_start,
            block_m_num,
            HIST2_BLOCK_M,
            blocks2a,
            block_size_padded,
        )
        return (
            hist,
            topk_indx,
            gate_indx,
            gate_scal,
            token_offs_raw,
            token_offs_pad,
            block_pid_map,
        )

    # `routing_from_bitmatrix` looks up `sort_tokens` via the routing module
    # global, so replacing it here redirects the legacy path to the pow2 kernel.
    _routing.sort_tokens = _sort_tokens_pow2

_patch_make_bitmatrix_metadata()

Monkey-patch make_bitmatrix_metadata to support non-power-of-2 top_k.

triton's tl.arange requires a power-of-2 range. The original kernel computes BLOCK_SIZE = BLOCK_PER_TOK * TOKS_PER_ROW (= 32 * top_k). For DeepSeek-V4 with top_k=6 this gives 192, which is not a power of 2 and causes a compile error at the first forward pass.

Fix: define a drop-in replacement kernel that accepts an extra constexpr BLOCK_SIZE_PADDED (next power of 2 >= BLOCK_SIZE) and uses it for the tl.arange call while keeping the actual BLOCK_SIZE as the stride between thread-blocks so that all flat indices into NonzeroIndx stay correct. Elements beyond BLOCK_SIZE are masked out (col_indx = 0xffff) and ignored.

This function is called once at module load time and patches the function inside the triton_kernels tensor module so that SparseMatrix.post_init picks up the fixed version transparently.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
def _patch_make_bitmatrix_metadata() -> None:
    """Monkey-patch make_bitmatrix_metadata to support non-power-of-2 top_k.

    triton's tl.arange requires a power-of-2 range.  The original kernel
    computes BLOCK_SIZE = BLOCK_PER_TOK * TOKS_PER_ROW (= 32 * top_k).  For
    DeepSeek-V4 with top_k=6 this gives 192, which is not a power of 2 and
    causes a compile error at the first forward pass.

    Fix: define a drop-in replacement kernel that accepts an extra constexpr
    BLOCK_SIZE_PADDED (next power of 2 >= BLOCK_SIZE) and uses it for the
    tl.arange call while keeping the actual BLOCK_SIZE as the stride between
    thread-blocks so that all flat indices into NonzeroIndx stay correct.
    Elements beyond BLOCK_SIZE are masked out (col_indx = 0xffff) and ignored.

    This function is called once at module load time and patches the function
    inside the triton_kernels tensor module so that SparseMatrix.__post_init__
    picks up the fixed version transparently.
    """
    import torch
    import triton
    import triton.language as tl

    try:
        from triton_kernels.tensor_details import bitmatrix as _bm
        from triton_kernels.tensor_details.bitmatrix import (
            BitmatrixMetadata,
            _keyed_add,
            cdiv,
        )
        from triton_kernels.tensor_details.bitmatrix_details.sum_bitmatrix_rows import (  # noqa: E501
            sum_bitmatrix_rows,
        )
    except ImportError:
        return

    @triton.jit
    def _stage2_pow2(
        ColSortedIndx,
        RowSortedIndx,
        NonzeroIndx,
        n_tokens,
        ColPartialSum,
        stride_pm,
        stride_pn,
        ColOffs,
        TOKS_PER_ROW: tl.constexpr,
        BLOCK_PER_TOK: tl.constexpr,
        BLOCK_SIZE_PADDED: tl.constexpr,
    ):
        # Actual number of elements per block (may not be a power of 2).
        BLOCK_SIZE: tl.constexpr = BLOCK_PER_TOK * TOKS_PER_ROW
        tl.static_assert(BLOCK_SIZE_PADDED <= 32768)
        if isinstance(n_tokens, tl.tensor) and n_tokens.dtype.is_ptr():
            n_tokens = tl.load(n_tokens)
        nonzero_indx_size = n_tokens * TOKS_PER_ROW
        pid_m = tl.program_id(0)
        # Use BLOCK_SIZE_PADDED (a power of 2) for tl.arange, but stride by
        # the actual BLOCK_SIZE so flat positions in NonzeroIndx are correct.
        # Elements with offs_local >= BLOCK_SIZE have offs_global beyond the
        # valid range, get col_indx = 0xffff, and are filtered by the mask
        # below without producing any output.
        offs_local = tl.arange(0, BLOCK_SIZE_PADDED)
        offs_global = pid_m * BLOCK_SIZE + offs_local
        mask = offs_global < nonzero_indx_size
        col_indx = tl.load(NonzeroIndx + offs_global, mask=mask, other=-1).to(tl.uint32)
        kv_pairs = ((col_indx << 16) | offs_local).to(tl.uint32)
        kv_pairs = tl.sort(kv_pairs, 0)
        col_indx = kv_pairs >> 16
        offs_global = pid_m * BLOCK_SIZE + (kv_pairs & 0xFFFF)
        mask = col_indx != 0xFFFF
        x = kv_pairs & 0xFFFF0000 | 0x00000001
        cols_and_inclusive_run_lengths = tl.associative_scan(x, 0, _keyed_add)
        exclusive_run_lengths = (cols_and_inclusive_run_lengths - 1) & 0xFFFF
        row_sorted_indx = tl.load(
            ColPartialSum + pid_m * stride_pm + col_indx * stride_pn, mask=mask
        )
        row_sorted_indx += tl.load(ColOffs + col_indx, mask=mask)
        row_sorted_indx += exclusive_run_lengths
        tl.store(RowSortedIndx + offs_global, row_sorted_indx, mask=mask)
        tl.store(ColSortedIndx + row_sorted_indx, offs_global, mask=mask)

    def _make_bitmatrix_metadata_pow2_safe(nonzero_indx, bitmatrix):
        assert nonzero_indx.ndim == 2
        PARTIAL_BLOCK_M = 32
        col_sum, col_partial_sum = sum_bitmatrix_rows(
            bitmatrix, partials_block_size=PARTIAL_BLOCK_M
        )
        device = bitmatrix.device
        n_indx = nonzero_indx.numel()
        n_cols = bitmatrix.shape[1]
        col_offs = torch.empty(n_cols, dtype=torch.int32, device=device)
        combined_indx = torch.empty(n_indx * 2, dtype=torch.int32, device=device)
        col_sorted_indx = combined_indx[:n_indx]
        row_sorted_indx = combined_indx[n_indx:]
        MEMSET_BLOCK = 1024
        memset_grid = (cdiv(n_indx * 2, MEMSET_BLOCK) + n_cols + 1,)
        _bm._bitmatrix_metadata_compute_stage1[memset_grid](
            combined_indx,
            n_indx * 2,
            -1,
            MEMSET_BLOCK,
            col_sum,
            col_offs,
            col_sum.shape[0],
            col_partial_sum,
            col_partial_sum.shape[0],
            col_partial_sum.stride(0),
            col_partial_sum.stride(1),
            BLOCK_M=512,
            BLOCK_N=512,
        )
        toks_per_row = nonzero_indx.shape[-1]
        block_size = PARTIAL_BLOCK_M * toks_per_row
        # Next power of 2 >= block_size (required by tl.arange).
        block_size_padded = 1 << (max(block_size, 1) - 1).bit_length()
        compute_grid = (cdiv(bitmatrix.shape_max[0], PARTIAL_BLOCK_M),)
        _stage2_pow2[compute_grid](
            col_sorted_indx,
            row_sorted_indx,
            nonzero_indx,
            bitmatrix.shape[0],
            col_partial_sum,
            col_partial_sum.stride(0),
            col_partial_sum.stride(1),
            col_offs,
            TOKS_PER_ROW=toks_per_row,
            BLOCK_PER_TOK=PARTIAL_BLOCK_M,
            BLOCK_SIZE_PADDED=block_size_padded,
        )
        return BitmatrixMetadata(
            col_sum=col_sum,
            col_sorted_indx=col_sorted_indx,
            row_sorted_indx=row_sorted_indx,
        )

    # The most reliable patch point: SparseMatrix.__post_init__ looks up
    # make_bitmatrix_metadata via its own __globals__ dict (the tensor.py
    # module dict).  Patching through __globals__ works regardless of how
    # sys.modules maps "triton_kernels.tensor" vs
    # "vllm.third_party.triton_kernels.tensor".
    from triton_kernels.tensor import SparseMatrix as _SparseMatrix

    _SparseMatrix.__post_init__.__globals__["make_bitmatrix_metadata"] = (
        _make_bitmatrix_metadata_pow2_safe
    )
    # Also patch the bitmatrix module itself in case it is imported directly.
    _bm.make_bitmatrix_metadata = _make_bitmatrix_metadata_pow2_safe

_sm12x_block_m(num_rows, num_experts)

triton_kernels' tokens-per-expert block_m heuristic, capped at 32.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
def _sm12x_block_m(num_rows: int, num_experts: int) -> int:
    """triton_kernels' tokens-per-expert block_m heuristic, capped at 32."""
    tokens_per_expt = max(1, num_rows // num_experts)
    return max(16, min(triton.next_power_of_2(tokens_per_expt), _SM12X_MAX_BLOCK_M))

_tk38_routing_data(col_sum, order, flat_w, topk)

Build 3.8 routing from per-expert counts and the stable expert order.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
def _tk38_routing_data(
    col_sum: torch.Tensor,
    order: torch.Tensor,
    flat_w: torch.Tensor,
    topk: int,
) -> tuple["RoutingData", torch.Tensor, torch.Tensor]:
    """Build 3.8 routing from per-expert counts and the stable expert order."""
    nrows = order.shape[0]
    ragged = make_ragged_tensor_metadata(col_sum, nrows)
    gather_tok = (order // topk).to(torch.int32)
    routing = RoutingData(ragged, flat_w[order], gather_tok, topk, nrows)
    return routing, gather_tok, gather_tok

pack_bitmatrix(bitmatrix, topk_ids, n_rows, bm_cols, n_expts_act, BLOCK_SIZE_M, BLOCK_SIZE_K)

Packs topk_ids into a bitmatrix. code reference: https://github.com/triton-lang/triton/blob/dd1bbc52b34d202dfe5ffea1e04fb16166c5c04e/python/triton_kernels/bench/distributed.py#L264

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
@triton.jit
def pack_bitmatrix(
    bitmatrix,
    topk_ids,
    n_rows,  # n_rows in bitmatrix / topk_ids
    bm_cols: tl.constexpr,  # n int32_t bitpacks in bitmatrix
    n_expts_act,  # num_topk
    BLOCK_SIZE_M: tl.constexpr,
    BLOCK_SIZE_K: tl.constexpr,
):
    """Packs topk_ids into a bitmatrix.
    code reference:
    https://github.com/triton-lang/triton/blob/dd1bbc52b34d202dfe5ffea1e04fb16166c5c04e/python/triton_kernels/bench/distributed.py#L264
    """
    pid_m = tl.program_id(0)
    offsets_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
    offsets_k = tl.arange(0, BLOCK_SIZE_K)
    offsets = offsets_m[:, None] * n_expts_act + offsets_k[None, :]
    mask = (offsets_m < n_rows)[:, None] & (offsets_k < n_expts_act)[None, :]
    indices = tl.load(topk_ids + offsets, mask=mask, other=-1)
    valid = indices >= 0
    div = indices // 32
    rem = indices % 32
    one = tl.cast(1, tl.uint32)

    # Iterate through all the relevant bitmatrix columns.
    for i in range(bm_cols):
        # When BLOCK_SIZE_K=32, offs is just the column index.
        offs = tl.arange(0, BLOCK_SIZE_K // 32) + i * (BLOCK_SIZE_K // 32)
        # All topks that need to go into this column has the correct bit set.
        # Other bits are 0. x is a 2D tensor.
        # Guard with `valid` to prevent negative indices from producing
        # spurious bits (on HIP, -1 // 32 == 0 and 1 << (-1 % 32) sets
        # bit 31).
        x = tl.where(
            valid[:, :, None] & (div[:, :, None] == offs[None, None, :]),
            (one << rem)[:, :, None],
            0,
        )
        # Reduce x to get a single int32_t bitpack.
        y = tl.reduce_or(x, axis=1)
        bitmatrix_ptrs = bitmatrix + offsets_m[:, None] * bm_cols + offs[None, :]
        tl.store(bitmatrix_ptrs, y, mask=offsets_m[:, None] < n_rows)

routing_data_from_sparse_topk(sparse_topk, n_expts)

Build routing structures from the SparseMatrix returned by triton_kernels.topk, reusing its precomputed bitmatrix metadata.

make_routing_data re-packs a bitmatrix from the topk ids and constructs a second SparseMatrix, recomputing metadata the topk call already produced; when the topk ids are used as-is (no expert-map remapping) that work is redundant.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
def routing_data_from_sparse_topk(
    sparse_topk,  # SparseMatrix
    n_expts: int,
) -> tuple["RoutingData", "GatherIndx", "ScatterIndx"]:
    """Build routing structures from the ``SparseMatrix`` returned by
    ``triton_kernels.topk``, reusing its precomputed bitmatrix metadata.

    ``make_routing_data`` re-packs a bitmatrix from the topk ids and
    constructs a second ``SparseMatrix``, recomputing metadata the topk
    call already produced; when the topk ids are used as-is (no expert-map
    remapping) that work is redundant.
    """
    if triton_kernels_version == "3.8":
        # topk ids have no -1 slots, so the topk metadata matches make_routing_data.
        mask_metadata = sparse_topk.mask_metadata
        return _tk38_routing_data(
            mask_metadata.col_sum,
            mask_metadata.col_sorted_indx,
            sparse_topk.vals.reshape(-1).to(torch.float32),
            sparse_topk.indx.shape[1],
        )

    dispatch_indx = sparse_topk.mask_metadata.row_sorted_indx
    combine_indx = sparse_topk.mask_metadata.col_sorted_indx
    ragged_batch_metadata = make_ragged_tensor_metadata(
        sparse_topk.mask_metadata.col_sum,
        dispatch_indx.shape[0],
    )
    n_expts_act = sparse_topk.indx.shape[1]
    # Unlike make_routing_data, no bfloat16 cast: gate_scal inherits the
    # gating dtype, which is bfloat16 for all callers of this path.
    gate_scal = sparse_topk.vals.flatten()[combine_indx]
    routing_data = RoutingData(
        gate_scal,
        ragged_batch_metadata.block_sizes,
        n_expts,
        n_expts_act,
        ragged_batch_metadata,
    )
    gather_indx = GatherIndx(combine_indx, dispatch_indx)
    scatter_indx = ScatterIndx(dispatch_indx, combine_indx)
    return routing_data, gather_indx, scatter_indx

triton_kernel_fused_experts(output_tensor, hidden_states, w1, w2, routing_data, gather_indx, scatter_indx, topk, activation=MoEActivation.SWIGLUOAI, quant_config=None, swiglu_alpha=1.702, swiglu_limit=7.0, apply_router_weight_on_input=False, global_num_experts=-1, expert_map=None, intermediate_cache=None, a1q_scale=None)

Triton implementation of fused expert computation using OAI kernels.

Source code in vllm/model_executor/layers/fused_moe/experts/gpt_oss_triton_kernels_moe.py
def triton_kernel_fused_experts(
    output_tensor: torch.Tensor,
    hidden_states: torch.Tensor,
    w1,  # Tensor or triton_kernels.Tensor
    w2,  # Tensor or triton_kernels.Tensor
    routing_data,  # RoutingData
    gather_indx,  # GatherIndx
    scatter_indx,  # ScatterIndx
    topk: int,
    activation: MoEActivation = MoEActivation.SWIGLUOAI,
    quant_config: FusedMoEQuantConfig | None = None,
    swiglu_alpha: float = 1.702,
    swiglu_limit: float = 7.0,
    apply_router_weight_on_input: bool = False,
    global_num_experts: int = -1,
    expert_map: torch.Tensor | None = None,
    intermediate_cache: torch.Tensor | None = None,
    a1q_scale: torch.Tensor | None = None,
) -> torch.Tensor:
    """Triton implementation of fused expert computation using OAI kernels."""
    assert activation == MoEActivation.SWIGLUOAI, (
        "Only SWIGLUOAI activation is supported"
    )

    if triton_kernels_version == "3.8":
        # 3.8 has no in-kernel scatter+topk-reduce, so the two matmuls are
        # followed by an external index_add combine.
        assert quant_config is not None
        M, K = hidden_states.shape[-2:]
        a_ragged = routing_data.ragged
        gather_tok = routing_data.gather_tok
        gammas = routing_data.gate_scal
        act = FusedActivation(
            FnSpecs(
                "swiglu",
                triton_kernels.swiglu.swiglu_fn,
                ("alpha", "limit"),
                reduction_n=2,
            ),
            (swiglu_alpha, swiglu_limit),
        )
        inter = matmul(
            hidden_states,
            w1,
            quant_config.w1_bias,
            a_ragged,
            None,
            gather_tok,
            None,
            quant_config.w1_precision,
            gammas=gammas if apply_router_weight_on_input else None,
            fused_activation=act,
        )
        y = matmul(
            inter,
            w2,
            quant_config.w2_bias,
            a_ragged,
            None,
            None,
            None,
            quant_config.w2_precision,
            gammas=None if apply_router_weight_on_input else gammas,
        )
        acc = torch.zeros((M, K), dtype=torch.float32, device=hidden_states.device)
        acc.index_add_(0, gather_tok.to(torch.int64), y.to(torch.float32))
        out = output_tensor.view(M, K)
        out.copy_(acc.to(out.dtype))
        return out
    assert quant_config is not None

    # type check, uint8 means mxfp4
    assert hidden_states.dtype == torch.bfloat16
    assert quant_config.w1_bias is None or quant_config.w1_bias.dtype == torch.float32
    assert quant_config.w2_bias is None or quant_config.w2_bias.dtype == torch.float32

    # Shape check, only check non-mxfp4
    assert hidden_states.ndim == 2
    assert hidden_states.shape[-1] == w1.shape[-2]
    assert w2.shape[-1] == w1.shape[1]

    batch_dim = 1
    M, K = hidden_states.shape[-2:]
    E, _, N = w1.shape

    if global_num_experts == -1:
        global_num_experts = E

    if intermediate_cache is None:
        intermediate_cache = torch.empty(
            (batch_dim, M * topk, N // 2),
            device=hidden_states.device,
            dtype=hidden_states.dtype,
        )

    # Add batch_dim to output buffer because matmul_ogs expects 3D output
    intermediate_cache = _resize_cache(
        intermediate_cache, (batch_dim, M * topk, N // 2)
    )
    output_tensor = _resize_cache(output_tensor, (batch_dim, M, K))

    act = (
        FusedActivation(
            FnSpecs(
                "swiglu",
                triton_kernels.swiglu.swiglu_fn,
                ("alpha", "limit"),
                reduction_n=2,
            ),
            (swiglu_alpha, swiglu_limit),
        )
        if triton_kernels_version != "3.5.1"
        else FusedActivation(
            FnSpecs("swiglu", triton_kernels.swiglu.swiglu_fn, ("alpha", "limit")),
            (swiglu_alpha, swiglu_limit),
            2,
        )
    )
    gammas = routing_data.gate_scal if routing_data else None
    _constrain_sm12x_block_m(M * topk, E)

    matmul_ogs(
        hidden_states,
        w1,
        quant_config.w1_bias,
        routing_data,
        gather_indx=gather_indx,
        precision_config=quant_config.w1_precision,
        gammas=gammas if apply_router_weight_on_input else None,
        fused_activation=act,
        y=intermediate_cache,
    )

    matmul_ogs(
        intermediate_cache.view(M * topk, N // 2),
        w2,
        quant_config.w2_bias,
        routing_data,
        scatter_indx=scatter_indx,
        precision_config=quant_config.w2_precision,
        gammas=None if apply_router_weight_on_input else gammas,
        y=output_tensor,
    )
    output_tensor = output_tensor.view(M, K)
    return output_tensor