Skip to content

vllm.models.inkling2.nvidia.ops.grouped_gemm

BF16 grouped GEMM over expert-sorted rows (the expert LoRA projections).

Functions:

  • grouped_gemm –

    out[r] (+)= x[r] @ weight[e].T for this rank's expert-sorted rows.

grouped_gemm(x, weight, perm, offsets, num_rows, topk, gather, out=None)

out[r] (+)= x[r] @ weight[e].T for this rank's expert-sorted rows.

Same row contract as ops.moe.expert_gemm: rows [offsets[0], offsets[-1]) are this rank's, expert e's rows are [offsets[e], offsets[e + 1]); with gather row r reads x[perm[r] // topk]. weight is BF16 [E, N, K]. Without out, returns a new [num_rows, N] tensor whose rows outside this rank's range are uninitialized; with out, adds into it (FP32 accumulation either way).

Source code in vllm/models/inkling2/nvidia/ops/grouped_gemm.py
def grouped_gemm(
    x: torch.Tensor,
    weight: torch.Tensor,
    perm: torch.Tensor,
    offsets: torch.Tensor,
    num_rows: int,
    topk: int,
    gather: bool,
    out: torch.Tensor | None = None,
) -> torch.Tensor:
    """`out[r] (+)= x[r] @ weight[e].T` for this rank's expert-sorted rows.

    Same row contract as `ops.moe.expert_gemm`: rows `[offsets[0],
    offsets[-1])` are this rank's, expert `e`'s rows are `[offsets[e],
    offsets[e + 1])`; with `gather` row `r` reads `x[perm[r] // topk]`.
    `weight` is BF16 `[E, N, K]`. Without `out`, returns a new
    `[num_rows, N]` tensor whose rows outside this rank's range are
    uninitialized; with `out`, adds into it (FP32 accumulation either way).
    """
    num_experts, n, k = weight.shape
    accumulate = out is not None
    if out is None:
        out = x.new_empty(num_rows, n)
    assert out.is_contiguous() and out.shape == (num_rows, n)
    block_m, block_n, block_k = 64, min(128, max(16, triton.next_power_of_2(n))), 64
    # Every non-empty expert holds at least one row.
    max_blocks = triton.cdiv(num_rows, block_m) + min(num_experts, num_rows) - 1
    if max_blocks > 0:
        _grouped_gemm_kernel[(triton.cdiv(n, block_n), max_blocks)](
            x,
            weight,
            out,
            perm,
            offsets,
            n,
            k,
            num_experts,
            triton.next_power_of_2(num_experts),
            topk,
            gather,
            accumulate,
            block_m,
            block_n,
            block_k,
            num_warps=4,
            num_stages=3,
        )
    return out