test_layernorm.py 2.25 KB
Newer Older
1
import pytest
2
3
import torch

4
from tests.kernels.utils import opcheck
5
from vllm.model_executor.layers.layernorm import RMSNorm
6

7
8
DTYPES = [torch.half, torch.bfloat16, torch.float]
NUM_TOKENS = [7, 83, 4096]  # Arbitrary values for testing
9
10
HIDDEN_SIZES = [768, 769, 770, 771, 5120, 5124, 5125, 5126, 8192,
                8199]  # Arbitrary values for testing
11
ADD_RESIDUAL = [False, True]
12
SEEDS = [0]
13
14
15
CUDA_DEVICES = [
    f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)
]
16

17

18
19
@pytest.mark.parametrize("num_tokens", NUM_TOKENS)
@pytest.mark.parametrize("hidden_size", HIDDEN_SIZES)
20
@pytest.mark.parametrize("add_residual", ADD_RESIDUAL)
21
22
@pytest.mark.parametrize("dtype", DTYPES)
@pytest.mark.parametrize("seed", SEEDS)
23
@pytest.mark.parametrize("device", CUDA_DEVICES)
24
@torch.inference_mode()
25
def test_rms_norm(
26
27
    num_tokens: int,
    hidden_size: int,
28
    add_residual: bool,
29
    dtype: torch.dtype,
30
    seed: int,
31
    device: str,
32
) -> None:
33
    torch.random.manual_seed(seed)
34
35
36
37
    if torch.cuda.is_available():
        torch.cuda.manual_seed(seed)
    torch.set_default_device(device)
    layer = RMSNorm(hidden_size).to(dtype=dtype)
38
39
    layer.weight.data.normal_(mean=1.0, std=0.1)
    scale = 1 / (2 * hidden_size)
40
    x = torch.randn(num_tokens, hidden_size, dtype=dtype)
41
42
43
44
45
    x *= scale
    residual = torch.randn_like(x) * scale if add_residual else None

    # NOTE(woosuk): The reference implementation should be executed first
    # because the custom kernel is in-place.
46
    ref_out = layer.forward_native(x, residual)
47
48
49
50
51
    out = layer(x, residual)
    # NOTE(woosuk): LayerNorm operators (including RMS) typically have larger
    # numerical errors than other operators because they involve reductions.
    # Therefore, we use a larger tolerance.
    if add_residual:
52
53
        torch.testing.assert_close(out[0], ref_out[0], atol=1e-2, rtol=1e-2)
        torch.testing.assert_close(out[1], ref_out[1], atol=1e-2, rtol=1e-2)
54
    else:
55
        torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2)
56
57
58
59
60
61
62

    if residual is not None:
        opcheck(torch.ops._C.fused_add_rms_norm,
                (x, residual, layer.weight.data, layer.variance_epsilon))
    else:
        opcheck(torch.ops._C.rms_norm,
                (out, x, layer.weight.data, layer.variance_epsilon))