Skip to content

vllm.ir.ops.rotary_embedding

vLLM IR ops for rotary positional embedding (RoPE).

The rotary dimension is the width of cos_sin_cache, matching the vLLM C kernel. Keeping it out of the signature lets fusion patterns match partial rotary layers.

Functions:

_rotate(x, cos, sin, is_neox)

Rotate contiguous halves (NeoX) or interleaved pairs (GPT-J).

Source code in vllm/ir/ops/rotary_embedding.py
def _rotate(x: Tensor, cos: Tensor, sin: Tensor, is_neox: bool) -> Tensor:
    """Rotate contiguous halves (NeoX) or interleaved pairs (GPT-J)."""
    cos = cos.unsqueeze(-2).to(x.dtype)
    sin = sin.unsqueeze(-2).to(x.dtype)

    if is_neox:
        x1, x2 = torch.chunk(x, 2, dim=-1)
    else:
        x1 = x[..., ::2]
        x2 = x[..., 1::2]

    o1 = x1 * cos - x2 * sin
    o2 = x2 * cos + x1 * sin

    if is_neox:
        return torch.cat((o1, o2), dim=-1)
    return torch.stack((o1, o2), dim=-1).flatten(-2)

rotary_embedding(positions, query, key, head_size, cos_sin_cache, is_neox)

Rotate the first cos_sin_cache.shape[-1] channels of each head.

Source code in vllm/ir/ops/rotary_embedding.py
@register_op(activations=["query", "key"], allow_inplace=True)
def rotary_embedding(
    positions: Tensor,
    query: Tensor,
    key: Tensor,
    head_size: int,
    cos_sin_cache: Tensor,
    is_neox: bool,
) -> tuple[Tensor, Tensor]:
    """Rotate the first `cos_sin_cache.shape[-1]` channels of each head."""
    cos, sin = _lookup_cos_sin(positions, query, cos_sin_cache)
    return (
        _apply_rope(query, cos, sin, head_size, is_neox),
        _apply_rope(key, cos, sin, head_size, is_neox),
    )

rotary_embedding_query_only(positions, query, head_size, cos_sin_cache, is_neox)

RoPE over query only, for layers that reuse another layer's KV cache.

Source code in vllm/ir/ops/rotary_embedding.py
@register_op(activations=["query"], allow_inplace=True)
def rotary_embedding_query_only(
    positions: Tensor,
    query: Tensor,
    head_size: int,
    cos_sin_cache: Tensor,
    is_neox: bool,
) -> Tensor:
    """RoPE over query only, for layers that reuse another layer's KV cache."""
    cos, sin = _lookup_cos_sin(positions, query, cos_sin_cache)
    return _apply_rope(query, cos, sin, head_size, is_neox)