Skip to content

vllm.models.hy_v4_flash.nvidia.indexpool_ops

Coarse IndexPool mathematics, independent of cache allocation.

Every decode step runs these per DSA layer, so each stage is a single Triton kernel instead of a chain of eager elementwise ops.

Functions:

  • pool_quantize_write –

    Gate-pool raw keys, RoPE, FWHT, FP8-quantize and write pool pages.

  • quantize_query –

    RoPE, FWHT and FP8-quantize indexer queries, padding heads with zeros.

  • select_expand_groups –

    Pick each row's top pool groups and expand them to sorted token indices.

_fwht32(x, BM)

Hadamard butterflies with strides 1..16 inside each 32-wide row.

Source code in vllm/models/hy_v4_flash/nvidia/indexpool_ops.py
@triton.jit
def _fwht32(x, BM: tl.constexpr):
    """Hadamard butterflies with strides 1..16 inside each 32-wide row."""
    x = _butterfly(x, BM, 1)
    x = _butterfly(x, BM, 2)
    x = _butterfly(x, BM, 4)
    x = _butterfly(x, BM, 8)
    return _butterfly(x, BM, 16)

_pool_lanes(value_row, Ape, lanes, mask, R, BM)

Softmax over the R group members, then the weighted value sum.

Each member row holds 128 values followed by 128 gate logits.

Source code in vllm/models/hy_v4_flash/nvidia/indexpool_ops.py
@triton.jit
def _pool_lanes(value_row, Ape, lanes, mask, R: tl.constexpr, BM: tl.constexpr):
    """Softmax over the `R` group members, then the weighted value sum.

    Each member row holds 128 values followed by 128 gate logits.
    """
    gate_row = value_row + 128
    peak = tl.full((BM, 32), float("-inf"), tl.float32)
    for r in tl.static_range(R):
        logit = tl.load(gate_row + r * 256 + lanes, mask, 0)
        peak = tl.maximum(peak, logit + tl.load(Ape + r * 128 + lanes))
    total = tl.zeros((BM, 32), tl.float32)
    for r in tl.static_range(R):
        logit = tl.load(gate_row + r * 256 + lanes, mask, 0)
        total += tldevice.exp(logit + tl.load(Ape + r * 128 + lanes) - peak)
    pooled = tl.zeros((BM, 32), tl.float32)
    for r in tl.static_range(R):
        logit = tl.load(gate_row + r * 256 + lanes, mask, 0)
        weight = tldevice.exp(logit + tl.load(Ape + r * 128 + lanes) - peak) / total
        pooled += tl.load(value_row + r * 256 + lanes, mask, 0) * weight
    return pooled

_rotate_fwht_quantize(a0, a1, even, odd, frequency, BM)

RoPE the last 64 lanes, then FWHT and power-of-two FP8 quantize.

Inputs are fp32 holding BF16 values: a0/a1 are lanes 0..63 and even/odd the interleaved rotary pairs. The butterflies run in the same order as the reference radix-2 transform, so results are bitwise identical to it.

Source code in vllm/models/hy_v4_flash/nvidia/indexpool_ops.py
@triton.jit
def _rotate_fwht_quantize(a0, a1, even, odd, frequency, BM: tl.constexpr):
    """RoPE the last 64 lanes, then FWHT and power-of-two FP8 quantize.

    Inputs are fp32 holding BF16 values: `a0`/`a1` are lanes 0..63 and
    `even`/`odd` the interleaved rotary pairs. The butterflies run in the
    same order as the reference radix-2 transform, so results are bitwise
    identical to it.
    """
    cos = tldevice.cos(frequency)
    sin = tldevice.sin(frequency)
    r0 = (even * cos + -odd * sin).to(tl.bfloat16).to(tl.float32)
    r1 = (odd * cos + even * sin).to(tl.bfloat16).to(tl.float32)
    a0 = _fwht32(a0, BM)
    a1 = _fwht32(a1, BM)
    r0 = _fwht32(r0, BM)
    r1 = _fwht32(r1, BM)
    c0, c1 = a0 + a1, a0 - a1
    d0, d1 = r0 + r1, r0 - r1
    norm: tl.constexpr = 0.08838834764831845
    y0 = (c0 + d0) * norm
    y1 = (c1 + d1) * norm
    y2 = (c0 - d0) * norm
    y3 = (c1 - d1) * norm
    amax = tl.maximum(
        tl.maximum(tl.max(tl.abs(y0), 1), tl.max(tl.abs(y1), 1)),
        tl.maximum(tl.max(tl.abs(y2), 1), tl.max(tl.abs(y3), 1)),
    )
    ratio = tldevice.div_rn(tl.maximum(amax, 1e-4), 448.0)
    scale = tldevice.exp2(tldevice.ceil(tldevice.log2(ratio)))
    inverse = (1.0 / scale)[:, None]
    q0 = tl.clamp(y0 * inverse, -448.0, 448.0).to(tl.float8e4nv)
    q1 = tl.clamp(y1 * inverse, -448.0, 448.0).to(tl.float8e4nv)
    q2 = tl.clamp(y2 * inverse, -448.0, 448.0).to(tl.float8e4nv)
    q3 = tl.clamp(y3 * inverse, -448.0, 448.0).to(tl.float8e4nv)
    return q0, q1, q2, q3, scale

pool_quantize_write(projection, ape, norm_weight, eps, positions, parameters, cache, table, owners, groups, active, mx_scales)

Gate-pool raw keys, RoPE, FWHT, FP8-quantize and write pool pages.

Parameters:

  • projection

    (Tensor) –

    [slots, ratio, 256] FP32 value projections followed by gate projections.

  • ape

    (Tensor) –

    [ratio, 128] intra-group position bias.

  • norm_weight

    (Tensor) –

    [128] key RMSNorm weight.

  • eps

    (float) –

    RMSNorm epsilon.

  • positions

    (Tensor) –

    [slots] or [3, slots] group positions.

  • parameters

    (dict[str, Any]) –

    Layer RoPE parameters.

  • cache

    (Tensor) –

    [blocks, page, 132] UINT8 pool pages.

  • table

    (Tensor) –

    [requests, blocks] block table.

  • owners

    (Tensor) –

    [slots] request of each slot.

  • groups

    (Tensor) –

    [slots] pool group of each slot.

  • active

    (Tensor) –

    [slots] whether each slot is written.

  • mx_scales

    (bool) –

    Store scales as four UE8M0 bytes instead of FP32.

Source code in vllm/models/hy_v4_flash/nvidia/indexpool_ops.py
def pool_quantize_write(
    projection: torch.Tensor,
    ape: torch.Tensor,
    norm_weight: torch.Tensor,
    eps: float,
    positions: torch.Tensor,
    parameters: dict[str, Any],
    cache: torch.Tensor,
    table: torch.Tensor,
    owners: torch.Tensor,
    groups: torch.Tensor,
    active: torch.Tensor,
    mx_scales: bool,
) -> None:
    """Gate-pool raw keys, RoPE, FWHT, FP8-quantize and write pool pages.

    Args:
        projection: `[slots, ratio, 256]` FP32 value projections followed
            by gate projections.
        ape: `[ratio, 128]` intra-group position bias.
        norm_weight: `[128]` key RMSNorm weight.
        eps: RMSNorm epsilon.
        positions: `[slots]` or `[3, slots]` group positions.
        parameters: Layer RoPE parameters.
        cache: `[blocks, page, 132]` UINT8 pool pages.
        table: `[requests, blocks]` block table.
        owners: `[slots]` request of each slot.
        groups: `[slots]` pool group of each slot.
        active: `[slots]` whether each slot is written.
        mx_scales: Store scales as four UE8M0 bytes instead of FP32.

    """
    slots, ratio, dim = projection.shape
    assert dim == 2 * INDEX_DIM and projection.is_contiguous()
    assert cache.dtype == torch.uint8 and cache.stride(0) % 4 == 0
    if slots == 0:
        return
    page = cache.shape[1]
    block = 16
    _pool_quantize_write_kernel[(triton.cdiv(slots, block),)](
        projection,
        ape.contiguous(),
        norm_weight,
        positions,
        Cache=cache,
        CacheWords=cache.view(torch.int32),
        Table=table,
        Owners=owners,
        Groups=groups,
        Active=active,
        slots=slots,
        CACHE_BLOCK=cache.stride(0),
        TABLE_ROW=table.stride(0),
        TABLE_COLS=table.shape[1],
        R=ratio,
        PAGE=page,
        EPS=eps,
        MX=mx_scales,
        BM=block,
        enable_fp_fusion=False,
        **_rope_arguments(positions, parameters, projection.device),
    )

quantize_query(query, head_weights, positions, parameters, padded_heads)

RoPE, FWHT and FP8-quantize indexer queries, padding heads with zeros.

Parameters:

  • query

    (Tensor) –

    [tokens, heads, 128] BF16 with unit-stride heads.

  • head_weights

    (Tensor) –

    [tokens, heads] per-head scoring weights.

  • positions

    (Tensor) –

    [tokens] or [3, tokens] positions.

  • parameters

    (dict[str, Any]) –

    Layer RoPE parameters.

  • padded_heads

    (int) –

    Head count the MQA logits kernel expects.

Returns:

  • Tensor –

    FP8 queries of shape [tokens, padded_heads, 128].

  • Tensor –

    FP32 weights of shape [tokens, padded_heads] with each head's quantization scale folded in.

Source code in vllm/models/hy_v4_flash/nvidia/indexpool_ops.py
def quantize_query(
    query: torch.Tensor,
    head_weights: torch.Tensor,
    positions: torch.Tensor,
    parameters: dict[str, Any],
    padded_heads: int,
) -> tuple[torch.Tensor, torch.Tensor]:
    """RoPE, FWHT and FP8-quantize indexer queries, padding heads with zeros.

    Args:
        query: `[tokens, heads, 128]` BF16 with unit-stride heads.
        head_weights: `[tokens, heads]` per-head scoring weights.
        positions: `[tokens]` or `[3, tokens]` positions.
        parameters: Layer RoPE parameters.
        padded_heads: Head count the MQA logits kernel expects.

    Returns:
        FP8 queries of shape `[tokens, padded_heads, 128]`.
        FP32 weights of shape `[tokens, padded_heads]` with each head's
            quantization scale folded in.

    """
    tokens, heads, dim = query.shape
    assert dim == INDEX_DIM and query.stride(2) == 1 and query.stride(1) == dim
    assert head_weights.stride(-1) == 1
    quant = torch.empty(
        (tokens, padded_heads, dim), dtype=torch.float8_e4m3fn, device=query.device
    )
    weights = torch.empty(
        (tokens, padded_heads), dtype=torch.float32, device=query.device
    )
    rows = tokens * padded_heads
    if rows:
        block = 16
        _quantize_query_kernel[(triton.cdiv(rows, block),)](
            query,
            head_weights,
            positions,
            Quant=quant.view(torch.uint8),
            Weights=weights,
            tokens=tokens,
            QUERY_TOKEN=query.stride(0),
            HEAD_WEIGHT_TOKEN=head_weights.stride(0),
            HEADS=heads,
            PADDED_HEADS=padded_heads,
            WEIGHT_SCALE=heads**-0.5 * INDEX_DIM**-0.5,
            BM=block,
            enable_fp_fusion=False,
            **_rope_arguments(positions, parameters, query.device),
        )
    return quant, weights

select_expand_groups(logits, upper, budget, logical, active, ratio, out, topk)

Pick each row's top pool groups and expand them to sorted token indices.

Parameters:

  • logits

    (Tensor) –

    [rows, width] FP32 group scores.

  • upper

    (Tensor) –

    [rows] number of complete groups visible to each row.

  • budget

    (int) –

    Maximum number of recalled groups.

  • logical

    (Tensor) –

    [rows] logical query positions (negative when padded).

  • active

    (Tensor) –

    [rows] whether each row is a live query.

  • ratio

    (int) –

    Tokens per group.

  • out

    (Tensor) –

    [rows, budget * ratio + ratio] INT32 destination. Live indices are packed in ascending order, followed by -1 padding.

  • topk

    (SparseIndexerTopk) –

    The sparse indexer top-k stage that selects the groups.

Source code in vllm/models/hy_v4_flash/nvidia/indexpool_ops.py
def select_expand_groups(
    logits: torch.Tensor,
    upper: torch.Tensor,
    budget: int,
    logical: torch.Tensor,
    active: torch.Tensor,
    ratio: int,
    out: torch.Tensor,
    topk: SparseIndexerTopk,
) -> None:
    """Pick each row's top pool groups and expand them to sorted token indices.

    Args:
        logits: `[rows, width]` FP32 group scores.
        upper: `[rows]` number of complete groups visible to each row.
        budget: Maximum number of recalled groups.
        logical: `[rows]` logical query positions (negative when padded).
        active: `[rows]` whether each row is a live query.
        ratio: Tokens per group.
        out: `[rows, budget * ratio + ratio]` INT32 destination. Live indices
            are packed in ascending order, followed by `-1` padding.
        topk: The sparse indexer top-k stage that selects the groups.

    """
    rows, width = logits.shape
    out_width = budget * ratio + ratio
    assert out.shape == (rows, out_width) and out.stride(1) == 1
    if rows == 0:
        return
    assert logits.stride(1) == 1
    count = min(budget, width)
    # Selects within each row's first `upper` groups, -1 past them. A 32-byte
    # row pitch suits every backend's output stride.
    indices = out.new_empty(rows, round_up(count, 8))[:, :count]
    topk.forward(logits, upper, 1, indices, count, width)
    _expand_groups_kernel[(rows,)](
        indices,
        logical,
        active,
        out,
        COUNT=count,
        INDEX_ROW=indices.stride(0),
        COUNT_P2=triton.next_power_of_2(count),
        RATIO=ratio,
        OUT_WIDTH=out_width,
        OUT_P2=triton.next_power_of_2(out_width),
        OUT_ROW=out.stride(0),
        num_warps=4,
    )