test_layernorm.py 1.72 KB
Newer Older
1
import pytest
2
3
4
import torch
import torch.nn as nn

Woosuk Kwon's avatar
Woosuk Kwon committed
5
from vllm import layernorm_ops
6

7
8
9
10
11
DTYPES = [torch.half, torch.bfloat16, torch.float]
HIDDEN_SIZES = [67, 768, 2048, 5120, 8192]  # Arbitrary values for testing
NUM_TOKENS = [7, 83, 4096]  # Arbitrary values for testing
SEEDS = [0]

12
13
14
15
16

class RefRMSNorm(nn.Module):

    def __init__(self, hidden_size, eps=1e-6):
        super().__init__()
17
        weight = torch.empty(hidden_size)
18
        weight.normal_(mean=1.0, std=0.1)
19
20
21
22
        self.weight = nn.Parameter(weight)
        self.variance_epsilon = eps

    def forward(self, hidden_states):
23
24
25
        input_dtype = hidden_states.dtype
        hidden_states = hidden_states.to(torch.float32)
        variance = hidden_states.pow(2).mean(-1, keepdim=True)
26
27
        hidden_states = hidden_states * torch.rsqrt(variance +
                                                    self.variance_epsilon)
28
        return self.weight * hidden_states.to(input_dtype)
29
30


31
32
33
34
@pytest.mark.parametrize("num_tokens", NUM_TOKENS)
@pytest.mark.parametrize("hidden_size", HIDDEN_SIZES)
@pytest.mark.parametrize("dtype", DTYPES)
@pytest.mark.parametrize("seed", SEEDS)
35
@torch.inference_mode()
36
def test_rms_norm(
37
38
39
    num_tokens: int,
    hidden_size: int,
    dtype: torch.dtype,
40
    seed: int,
41
) -> None:
42
43
44
45
46
47
    torch.random.manual_seed(seed)
    torch.cuda.manual_seed(seed)

    scale = float(hidden_size**-0.5)
    x = torch.empty(num_tokens, hidden_size, dtype=dtype, device="cuda")
    x.uniform_(-scale, scale)
48
49
50
51
52
53
54
55
56
57
    ref = RefRMSNorm(hidden_size).to(dtype).cuda()

    out = torch.empty_like(x)
    layernorm_ops.rms_norm(
        out,
        x,
        ref.weight.data,
        ref.variance_epsilon,
    )
    ref_out = ref(x)
58
    assert torch.allclose(out, ref_out, atol=1e-2, rtol=1e-5)