test_pos_encoding.py 4.84 KB
Newer Older
1
2
3
4
5
6
from typing import Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F

Woosuk Kwon's avatar
Woosuk Kwon committed
7
from vllm import pos_encoding_ops
8
9
10


def rotate_half(x: torch.Tensor) -> torch.Tensor:
11
12
    x1 = x[..., :x.shape[-1] // 2]
    x2 = x[..., x.shape[-1] // 2:]
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    return torch.cat((-x2, x1), dim=-1)


def apply_rotary_pos_emb(
    q: torch.Tensor,
    k: torch.Tensor,
    cos: torch.Tensor,
    sin: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
    q_embed = (q * cos) + (rotate_half(q) * sin)
    k_embed = (k * cos) + (rotate_half(k) * sin)
    return q_embed, k_embed


class RefRotaryEmbeddingNeox(nn.Module):
    """Reference implementation of the GPT-NeoX style rotary embedding."""

    def __init__(
        self,
        dim: int,
        max_position_embeddings: int = 2048,
        base: int = 10000,
    ) -> None:
        super().__init__()
37
        self.rotary_dim = dim
38
39
40
        self.max_position_embeddings = max_position_embeddings

        # Create cos and sin embeddings.
41
        inv_freq = 1.0 / (base**(torch.arange(0, dim, 2) / dim))
42
43
44
45
46
47
48
49
50
51
        t = torch.arange(max_position_embeddings).float()
        freqs = torch.einsum("i,j->ij", t, inv_freq.float())
        emb = torch.cat((freqs, freqs), dim=-1)
        cos = emb.cos().to(dtype=inv_freq.dtype)
        sin = emb.sin().to(dtype=inv_freq.dtype)
        self.register_buffer("cos_cached", cos, persistent=False)
        self.register_buffer("sin_cached", sin, persistent=False)

    def forward(
        self,
52
53
54
        positions: torch.Tensor,  # [num_tokens]
        query: torch.Tensor,  # [num_tokens, num_heads, head_size]
        key: torch.Tensor,  # [num_tokens, num_heads, head_size]
55
    ) -> Tuple[torch.Tensor, torch.Tensor]:
56

57
58
59
60
        query_rot = query[..., :self.rotary_dim]
        query_pass = query[..., self.rotary_dim:]
        key_rot = key[..., :self.rotary_dim]
        key_pass = key[..., self.rotary_dim:]
61
62
63

        query_rot = query_rot.transpose(0, 1)
        key_rot = key_rot.transpose(0, 1)
64
65
        cos = F.embedding(positions, self.cos_cached)
        sin = F.embedding(positions, self.sin_cached)
66
67
68
69
70
71
72
        query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
        query_rot = query_rot.transpose(0, 1).contiguous()
        key_rot = key_rot.transpose(0, 1).contiguous()

        query = torch.cat((query_rot, query_pass), dim=-1)
        key = torch.cat((key_rot, key_pass), dim=-1)

73
74
75
76
77
        # Output query/key shape: [num_tokens, num_tokens, head_size]
        return query, key


@torch.inference_mode()
78
def run_rotary_embedding_neox(
79
80
81
82
    num_tokens: int,
    num_heads: int,
    head_size: int,
    max_position: int,
83
    rotary_dim: int,
84
85
86
    dtype: torch.dtype,
    base: int = 10000,
) -> None:
87
88
89
90
91
92
93
94
95
    positions = torch.randint(0, max_position, (num_tokens, ), device='cuda')
    query = torch.randn(num_tokens,
                        num_heads * head_size,
                        dtype=dtype,
                        device='cuda')
    key = torch.randn(num_tokens,
                      num_heads * head_size,
                      dtype=dtype,
                      device='cuda')
96
97

    # Create the rotary embedding.
98
    inv_freq = 1.0 / (base**(torch.arange(0, rotary_dim, 2) / rotary_dim))
99
100
101
102
103
104
105
    t = torch.arange(max_position).float()
    freqs = torch.einsum('i,j -> ij', t, inv_freq.float())
    cos = freqs.cos()
    sin = freqs.sin()
    cos_sin_cache = torch.cat((cos, sin), dim=-1)
    cos_sin_cache = cos_sin_cache.to(dtype=dtype, device='cuda')

Woosuk Kwon's avatar
Woosuk Kwon committed
106
107
108
    # Run the kernel. The kernel is in-place, so we need to clone the inputs.
    out_query = query.clone()
    out_key = key.clone()
109
    pos_encoding_ops.rotary_embedding_neox(
Woosuk Kwon's avatar
Woosuk Kwon committed
110
        positions,
111
112
        out_query,
        out_key,
113
        head_size,
114
115
116
117
118
        cos_sin_cache,
    )

    # Run the reference implementation.
    ref_rotary_embedding = RefRotaryEmbeddingNeox(
119
        dim=rotary_dim,
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
        max_position_embeddings=max_position,
        base=base,
    ).to(dtype=dtype, device='cuda')
    ref_query, ref_key = ref_rotary_embedding(
        positions,
        query.view(num_tokens, num_heads, head_size),
        key.view(num_tokens, num_heads, head_size),
    )
    ref_query = ref_query.view(num_tokens, num_heads * head_size)
    ref_key = ref_key.view(num_tokens, num_heads * head_size)

    # Compare the results.
    assert torch.allclose(out_query, ref_query, atol=1e-3, rtol=1e-5)
    assert torch.allclose(out_key, ref_key, atol=1e-3, rtol=1e-5)


136
def test_rotary_embedding_neox() -> None:
137
    for dtype in [torch.half, torch.bfloat16, torch.float]:
138
139
        for head_size in [32, 64, 80, 96, 128, 160, 192, 256]:
            print(f'Running tests for head_size={head_size} and dtype={dtype}')
140
            run_rotary_embedding_neox(
141
142
143
144
                num_tokens=2145,
                num_heads=5,
                head_size=head_size,
                max_position=8192,
145
                rotary_dim=head_size,
146
147
                dtype=dtype,
            )