Skip to content

vllm.models.inkling2.nvidia.ops.trtllm_bmm

TRT-LLM-gen batched expert GEMMs (FlashInfer cubins) for the Inkling2 MoE.

The GEMMs read expert-sorted activation rows whose expert segments are padded to the token tile, with block scales in the R8c4 (tile < 128) or R128c4 layout (block_scales), and row-shuffled expert weights. Outputs are bf16; NVFP4 outputs are scaled by an fp32 factor per row.

Classes:

  • ExpertPlan –

    Token tile, launched tiles (an upper bound) and the kernel of each

Functions:

  • bmm –

    bf16 [plan.rows, N] expert GEMM of the tile-padded act rows.

  • configs –

    Kernel name -> (config index, B scale layout) of the (format, token

  • expert_plan –

    Plan for tokens routed to topk of all experts, num_experts

  • load_kernels –

    Loads the kernels of every batch size's plan by running them on no

  • operand –

    torch.empty((rows, *shape)), allocated with enough rows to span

ExpertPlan dataclass

Token tile, launched tiles (an upper bound) and the kernel of each projection for a batch.

Source code in vllm/models/inkling2/nvidia/ops/trtllm_bmm.py
@dataclass(frozen=True)
class ExpertPlan:
    """Token tile, launched tiles (an upper bound) and the kernel of each
    projection for a batch."""

    tile: int
    max_ctas: int
    kernels: tuple[int, int]

    @property
    def rows(self) -> int:
        return self.tile * self.max_ctas

bmm(act, act_scale, row_scale, weight, weight_scale, ones, tiles, plan, projection)

bf16 [plan.rows, N] expert GEMM of the tile-padded act rows.

tiles holds the expert and row limit of each of the plan.max_ctas tiles, then the number of tiles and of padded rows. ones (one per expert) is the GEMM's output scale.

Source code in vllm/models/inkling2/nvidia/ops/trtllm_bmm.py
def bmm(
    act: torch.Tensor,
    act_scale: torch.Tensor,
    row_scale: torch.Tensor | None,
    weight: torch.Tensor,
    weight_scale: torch.Tensor,
    ones: torch.Tensor,
    tiles: torch.Tensor,
    plan: ExpertPlan,
    projection: int,
) -> torch.Tensor:
    """bf16 `[plan.rows, N]` expert GEMM of the tile-padded `act` rows.

    `tiles` holds the expert and row limit of each of the `plan.max_ctas`
    tiles, then the number of tiles and of padded rows. `ones` (one per
    expert) is the GEMM's output scale.
    """
    nvfp4 = weight.dtype == torch.uint8
    n = weight.shape[1]
    out = operand(plan.rows, n, dtype=torch.bfloat16, device=act.device)
    m = plan.max_ctas
    _module()[0].bmm_run(
        nvfp4,
        plan.tile,
        plan.kernels[projection],
        weight,
        weight_scale,
        act,
        act_scale,
        row_scale,
        ones,
        out,
        tiles[:m],
        tiles[m : 2 * m],
        tiles[2 * m : 2 * m + 1],
        tiles[2 * m + 1 :],
        m,
    )
    return out

configs(nvfp4, tile_n) cached

Kernel name -> (config index, B scale layout) of the (format, token tile) GEMMs.

Source code in vllm/models/inkling2/nvidia/ops/trtllm_bmm.py
@functools.cache
def configs(nvfp4: bool, tile_n: int) -> dict[str, tuple[int, int]]:
    """Kernel name -> (config index, B scale layout) of the (format, token
    tile) GEMMs."""
    module, include_dir = _module()
    names = _config_names(include_dir)
    flat = list(module.bmm_configs(nvfp4, tile_n))
    return {names[i]: (i, layout) for i, layout in zip(flat[::2], flat[1::2])}

expert_plan(tokens, topk, num_experts, nvfp4, shapes, tile=None) cached

Plan for tokens routed to topk of all experts, num_experts of them local, with (N, K) weight shapes of the two projections.

Source code in vllm/models/inkling2/nvidia/ops/trtllm_bmm.py
@functools.cache
def expert_plan(
    tokens: int,
    topk: int,
    num_experts: int,
    nvfp4: bool,
    shapes: tuple[tuple[int, int], tuple[int, int]],
    tile: int | None = None,
) -> ExpertPlan:
    """Plan for `tokens` routed to `topk` of all experts, `num_experts`
    of them local, with (N, K) weight `shapes` of the two projections."""
    if tile is None:
        tile = next(t for max_tokens, t in _TILES if tokens <= max_tokens)
    # Tiles if the local rows fill as many experts as possible, then pile up.
    rows = tokens * topk
    max_ctas = min(num_experts, rows) + (rows - min(num_experts, rows)) // tile
    if not use_sm100_kernels():
        # No TRT-LLM-gen kernels (Hopper): only `route`'s layout.
        return ExpertPlan(tile, max_ctas, (0, 0))
    names = configs(nvfp4, tile)
    keys = _KERNELS[(nvfp4, tile)]
    kernels = []
    for projection, (n, k) in enumerate(shapes):
        # The projection's kernel, else the other's (an unrolled K loop, say,
        # needs K to be a multiple of its double K tile).
        for key in (keys[projection], keys[1 - projection]):
            ((index, layout),) = (v for name, v in names.items() if key in name)
            assert layout == (3 if tile >= 128 else 1)  # R128c4 / R8c4 activations
            size = _module()[0].bmm_workspace_size(
                nvfp4, tile, index, n, k, num_experts, max_ctas
            )
            if size == 0:
                kernels.append(index)
                break
        else:
            raise AssertionError(f"no Inkling2 expert GEMM for {(n, k)}, tile {tile}")
    return ExpertPlan(tile, max_ctas, (kernels[0], kernels[1]))

load_kernels(weights, weight_scales, topk)

Loads the kernels of every batch size's plan by running them on no tiles: loading is not allowed while a CUDA graph is captured.

Source code in vllm/models/inkling2/nvidia/ops/trtllm_bmm.py
def load_kernels(
    weights: tuple[torch.Tensor, torch.Tensor],
    weight_scales: tuple[torch.Tensor, torch.Tensor],
    topk: int,
) -> None:
    """Loads the kernels of every batch size's plan by running them on no
    tiles: loading is not allowed while a CUDA graph is captured."""
    nvfp4 = weights[0].dtype == torch.uint8
    num_experts = weights[0].shape[0]
    pack = 2 if nvfp4 else 1
    shapes = tuple((w.shape[1], w.shape[2] * pack) for w in weights)
    device = weights[0].device
    ones = torch.ones(num_experts, dtype=torch.float32, device=device)
    for _, tile in _TILES:
        plan = expert_plan(1, topk, num_experts, nvfp4, shapes, tile)
        tiles = torch.zeros(2 * plan.max_ctas + 2, dtype=torch.int32, device=device)
        for projection, (weight, scale) in enumerate(zip(weights, weight_scales)):
            k = weight.shape[2]
            act = operand(plan.rows, k, dtype=weight.dtype, device=device)
            act_scale = operand(
                plan.rows, scale.shape[2], dtype=scale.dtype, device=device
            )
            row_scale = (
                operand(plan.rows, dtype=torch.float32, device=device)
                if nvfp4
                else None
            )
            bmm(act, act_scale, row_scale, weight, scale, ones, tiles, plan, projection)

operand(rows, *shape, dtype, device)

torch.empty((rows, *shape)), allocated with enough rows to span MIN_OPERAND_BYTES.

Source code in vllm/models/inkling2/nvidia/ops/trtllm_bmm.py
def operand(
    rows: int, *shape: int, dtype: torch.dtype, device: torch.device
) -> torch.Tensor:
    """`torch.empty((rows, *shape))`, allocated with enough rows to span
    `MIN_OPERAND_BYTES`."""
    row_bytes = math.prod(shape) * dtype.itemsize
    alloc_rows = max(rows, -(-MIN_OPERAND_BYTES // row_bytes))
    return torch.empty((alloc_rows, *shape), dtype=dtype, device=device)[:rows]