Skip to content

vllm.models.deepseek_v41.amd.akr_kernels

The DeepSeek-V4.1 routes' only door to amd_kernels.

Calls only the shape-agnostic op entries of amd_kernels.<category> (and the MXFP8 dense linears of amd_kernels.gemm.mxfp8_common.gemm), never a shape package, so another shape needs no change here. Each entry reads its shape from the tensors; where <op>_blocker returns a reason the call is not covered: the reason is logged once and the wrapper returns None (or False), having launched nothing, and the caller runs its stock path. Imports are lazy, so vLLM imports without amd_kernels.

Classes:

  • IndexerBuffers –

    Static outputs shared by every indexer layer of one device (the layers

  • Mxfp8Weight –

    A linear's MXFP8 weight in the entries' layout: AITER's (16, 16)

Functions:

  • bf16_dual_gemm_weight –

    kv_score (fp32 columns, optional) and weights_proj (bf16 columns) as

  • fused_ep_context –

    The expert-parallel pools of this process (a collective).

  • fused_ep_weights –

    Views of the layer's MegaMoE tensors, which AITER already shuffled into

  • mhc_gate_finish –

    (post, comb, layer input, next pre[, codes, scales]) of the seam the

  • mxfp8_dense –

    x @ W.T in bf16 where the dense entry has a winning row for x's row

  • mxfp8_dense_weight –

    mxfp8_weight for a shape the dense entry has tuned rows for.

  • mxfp8_gate_up_swiglu –

    Gate_up GEMM, clamped SwiGLU (limit 10) and MXFP8 out: (codes, scales).

  • mxfp8_grouped_gemm –

    (codes, scales) of the grouped GEMM with the MXFP8 epilogue.

  • mxfp8_grouped_gemm_bf16 –

    bf16 output of the grouped GEMM (wo_b's input without the quantize round trip

  • mxfp8_grouped_weight –

    wo_a's AITER-preshuffled weight [G * N, K] and its 32 x 32 block scales

  • mxfp8_weight –

    The stock linear's preshuffled weight as is (no copy) and its scales in

  • postmix_gates_gemm –

    (new residual, partial layer input, gate partials, stream mean or None).

  • rmsnorm_dual_mxfp8 –

    (codes, scales, kv). pad_scale: the scales are the first rows of a

IndexerBuffers

Static outputs shared by every indexer layer of one device (the layers run one after another on one stream).

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
class IndexerBuffers:
    """Static outputs shared by every indexer layer of one device (the layers
    run one after another on one stream)."""

    def __init__(self, device: torch.device, max_rows: int, topk: int) -> None:
        i32 = torch.int32
        self.slots = torch.zeros(max_rows * topk, dtype=i32, device=device)
        self.indptr = torch.zeros(max_rows + 1, dtype=i32, device=device)
        self.lens = torch.zeros(max_rows, dtype=i32, device=device)
        self.topk = topk
        self.max_rows = max_rows
        self.scores: dict[int, torch.Tensor] = {}

    def scores_for(self, max_ctx: int) -> torch.Tensor | None:
        cols = _indexer().mxfp4_indexer_scores_cols(max_ctx)
        if cols is None:
            return None
        buf = self.scores.get(cols)
        if buf is None:
            buf = torch.empty(
                self.max_rows, cols, dtype=torch.float32, device=self.slots.device
            )
            self.scores[cols] = buf
        return buf

Mxfp8Weight

A linear's MXFP8 weight in the entries' layout: AITER's (16, 16) preshuffle and shuffled E8M0 scales [N, K / 32].

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
class Mxfp8Weight:
    """A linear's MXFP8 weight in the entries' layout: AITER's (16, 16)
    preshuffle and shuffled E8M0 scales `[N, K / 32]`."""

    def __init__(self, weight: torch.Tensor, scale: torch.Tensor) -> None:
        self.weight = weight
        self.scale = scale
        self.n, self.k = weight.shape

bf16_dual_gemm_weight(wa, wb)

kv_score (fp32 columns, optional) and weights_proj (bf16 columns) as one weight; None where the entry has no such shape.

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def bf16_dual_gemm_weight(wa: torch.Tensor | None, wb: torch.Tensor):
    """kv_score (fp32 columns, optional) and weights_proj (bf16 columns) as
    one weight; None where the entry has no such shape."""
    gemm = _gemm()
    if (wb.shape[1], wb.shape[0]) not in gemm.bf16_gemm_f32_bf16_shapes():
        return None
    if wb.dtype != BF16 or (wa is not None and wa.dtype != BF16):
        return None
    return gemm.bf16_gemm_f32_bf16_shuffle_weight(wa, wb)

fused_ep_context(experts)

The expert-parallel pools of this process (a collective).

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def fused_ep_context(experts) -> Any:
    """The expert-parallel pools of this process (a collective)."""
    from vllm.distributed import get_ep_group

    ep = get_ep_group()
    return _moe().expert_parallel(
        ep.rank_in_group,
        ep.world_size,
        ep.cpu_group,
        torch.device("cuda", torch.accelerator.current_device_index()),
        hidden=experts.hidden_size,
        inter=experts.intermediate_size,
        top_k=experts.top_k,
        experts_per_rank=experts.num_local_experts,
    )

fused_ep_weights(experts)

Views of the layer's MegaMoE tensors, which AITER already shuffled into the kernel's layout (no copy).

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def fused_ep_weights(experts) -> Any:
    """Views of the layer's MegaMoE tensors, which AITER already shuffled into
    the kernel's layout (no copy)."""
    u8 = torch.uint8
    return _moe().fused_ep_expert_weights(
        experts.w13_weight.data.view(u8),
        experts.w13_weight_scale.data.view(u8),
        experts.w2_weight.data.view(u8),
        experts.w2_weight_scale.data.view(u8),
        world=experts.ep_size,
        top_k=experts.top_k,
        hidden=experts.hidden_size,
        inter=experts.intermediate_size,
        shuffled=True,
    )

mhc_gate_finish(partials, x1, hc_scale, hc_base, norm, layer, *, quant)

(post, comb, layer input, next pre[, codes, scales]) of the seam the gate partials belong to; layer supplies the mHC constants.

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def mhc_gate_finish(partials, x1, hc_scale, hc_base, norm, layer, *, quant: bool):
    """(post, comb, layer input, next pre[, codes, scales]) of the seam the
    gate partials belong to; `layer` supplies the mHC constants."""
    return _norm().mhc_gate_finish(
        partials,
        x1,
        hc_scale,
        hc_base,
        norm.weight,
        rms_eps=layer.rms_norm_eps,
        hc_pre_eps=layer.hc_eps,
        hc_sinkhorn_eps=layer.hc_eps,
        hc_post_mult=layer.hc_post_alpha,
        norm_eps=norm.variance_epsilon,
        sinkhorn_repeat=layer.hc_sinkhorn_iters,
        quant=quant,
    )

mxfp8_dense(x, w)

x @ W.T in bf16 where the dense entry has a winning row for x's row count, else None.

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def mxfp8_dense(
    x: torch.Tensor | QuantizedActivation, w: Mxfp8Weight
) -> torch.Tensor | None:
    """`x @ W.T` in bf16 where the dense entry has a winning row for `x`'s row
    count, else None."""
    gemm = _linear()
    if isinstance(x, QuantizedActivation):
        if gemm.mxfp8_linear_blocker(x.data.shape[0], w.n, w.k, BF16, True):
            return None
        return gemm.mxfp8_gemm(x.data, x.scale, w.weight, w.scale, BF16)
    if gemm.mxfp8_linear_blocker(x.shape[0], w.n, w.k, BF16, False):
        return None
    return gemm.mxfp8_linear(x, w.weight, w.scale, BF16)

mxfp8_dense_weight(linear)

mxfp8_weight for a shape the dense entry has tuned rows for.

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def mxfp8_dense_weight(linear) -> Mxfp8Weight | None:
    """`mxfp8_weight` for a shape the dense entry has tuned rows for."""
    w = getattr(linear, "weight", None)
    if w is None or tuple(w.shape) not in _linear().tuned_shapes(BF16):
        return None
    weight = mxfp8_weight(linear)
    if weight is not None:
        _linear().warmup_mxfp8_gemm_weight(weight.weight, weight.scale, 1024, BF16)
    return weight

mxfp8_gate_up_swiglu(x, w)

Gate_up GEMM, clamped SwiGLU (limit 10) and MXFP8 out: (codes, scales).

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def mxfp8_gate_up_swiglu(x, w: Mxfp8Weight):
    """Gate_up GEMM, clamped SwiGLU (limit 10) and MXFP8 out: (codes, scales)."""
    gemm = _gemm()
    if isinstance(x, QuantizedActivation):
        m, prequant = x.data.shape[0], True
    else:
        m, prequant = x.shape[0], False
    reason = gemm.mxfp8_gate_up_swiglu_mxfp8_blocker(m, w.n, w.k, prequant)
    if not _covered("gate_up_swiglu", reason):
        return None
    if prequant:
        return gemm.mxfp8_gate_up_swiglu_mxfp8_prequant(
            x.data, x.scale, w.weight, w.scale
        )
    return gemm.mxfp8_gate_up_swiglu_mxfp8(x, w.weight, w.scale)

mxfp8_grouped_gemm(x, w)

(codes, scales) of the grouped GEMM with the MXFP8 epilogue.

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def mxfp8_grouped_gemm(x: QuantizedActivation, w: GroupedWeight):
    """(codes, scales) of the grouped GEMM with the MXFP8 epilogue."""
    return _gemm().mxfp8_grouped_gemm_mxfp8(x.data, x.scale, w.weight, w.scale)

mxfp8_grouped_gemm_bf16(x, w)

bf16 output of the grouped GEMM (wo_b's input without the quantize round trip of the MXFP8 epilogue).

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def mxfp8_grouped_gemm_bf16(x: QuantizedActivation, w: GroupedWeight) -> torch.Tensor:
    """bf16 output of the grouped GEMM (wo_b's input without the quantize round trip
    of the MXFP8 epilogue)."""
    return _gemm().mxfp8_grouped_gemm(x.data, x.scale, w.weight, w.scale)

mxfp8_grouped_weight(wo_a, groups, n)

wo_a's AITER-preshuffled weight [G * N, K] and its 32 x 32 block scales as [G, N / 32, K / 32] (views, no copy).

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def mxfp8_grouped_weight(wo_a, groups: int, n: int) -> GroupedWeight | None:
    """wo_a's AITER-preshuffled weight `[G * N, K]` and its 32 x 32 block scales
    as `[G, N / 32, K / 32]` (views, no copy)."""
    w = getattr(wo_a, "weight_preshuffled", None)
    scale = getattr(wo_a, "weight_scale", None)
    if w is None or scale is None or w.dtype != torch.float8_e4m3fn:
        return None
    k = w.shape[1]
    if (groups, n, k) not in _gemm().mxfp8_grouped_gemm_shapes():
        return None
    if tuple(scale.shape) != (groups * n // 32, k // 32):
        return None
    _gemm().warmup_mxfp8_grouped_gemm(w.device, groups, n, k)
    scale = scale.view(torch.uint8).view(groups, n // 32, k // 32)
    return GroupedWeight(w, scale, groups, n, k)

mxfp8_weight(linear)

The stock linear's preshuffled weight as is (no copy) and its scales in the entries' layout; None for a weight that is not MXFP8.

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def mxfp8_weight(linear) -> Mxfp8Weight | None:
    """The stock linear's preshuffled weight as is (no copy) and its scales in
    the entries' layout; None for a weight that is not MXFP8."""
    from aiter.ops.shuffle import shuffle_scale_a16w4

    w = getattr(linear, "weight", None)
    if (
        w is None
        or w.dtype != torch.float8_e4m3fn
        or w.dim() != 2
        or getattr(linear, "weight_scale", None) is None
    ):
        return None
    scale = _row_scales(linear)
    shuffled = getattr(linear, "weight_preshuffled", None)
    if shuffled is None:
        return Mxfp8Weight(*_linear().preshuffle_mxfp8_weight(w.data, scale))
    return Mxfp8Weight(shuffled, shuffle_scale_a16w4(scale, 1, False))

postmix_gates_gemm(x, w, residual, post_mix, comb_mix, pre_mix, fn_packed, *, routed=None, aux_mean=False)

(new residual, partial layer input, gate partials, stream mean or None).

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def postmix_gates_gemm(
    x: QuantizedActivation,
    w: Mxfp8Weight,
    residual,
    post_mix,
    comb_mix,
    pre_mix,
    fn_packed,
    *,
    routed=None,
    aux_mean=False,
):
    """(new residual, partial layer input, gate partials, stream mean or None)."""
    return _gemm().mxfp8_postmix_gates_gemm(
        x.data,
        x.scale,
        w.weight,
        w.scale,
        residual,
        post_mix.contiguous(),
        comb_mix.contiguous(),
        pre_mix.contiguous(),
        fn_packed,
        None if routed is None else routed.contiguous(),
        aux_mean=aux_mean,
    )

rmsnorm_dual_mxfp8(q, kv, q_weight, kv_weight, eps, pad_scale=False)

(codes, scales, kv). pad_scale: the scales are the first rows of a buffer with a multiple of 32 rows, which the wq_b entry moves to its layout in one launch (any other storage works, with more launches).

Source code in vllm/models/deepseek_v41/amd/akr_kernels.py
def rmsnorm_dual_mxfp8(q, kv, q_weight, kv_weight, eps, pad_scale: bool = False):
    """(codes, scales, kv). `pad_scale`: the scales are the first rows of a
    buffer with a multiple of 32 rows, which the `wq_b` entry moves to its
    layout in one launch (any other storage works, with more launches)."""
    norm = _norm()
    if not _covered("rmsnorm_dual_mxfp8", norm.rmsnorm_dual_mxfp8_blocker(q, kv)):
        return None
    kwargs = {}
    if pad_scale:
        rows = q.shape[0]
        kwargs["scale"] = torch.empty(
            ((rows + 31) // 32 * 32, q.shape[1] // 32),
            dtype=torch.uint8,
            device=q.device,
        )[:rows]
    return norm.rmsnorm_dual_mxfp8(q, kv, q_weight, kv_weight, eps, **kwargs)