test_activation.py 2.27 KB
Newer Older
1
import pytest
Woosuk Kwon's avatar
Woosuk Kwon committed
2
3
import torch
import torch.nn.functional as F
4
from transformers.activations import get_activation
5

Woosuk Kwon's avatar
Woosuk Kwon committed
6
from vllm import activation_ops
Woosuk Kwon's avatar
Woosuk Kwon committed
7

8
9
10
11
12
DTYPES = [torch.half, torch.bfloat16, torch.float]
NUM_TOKENS = [7, 83, 2048]  # Arbitrary values for testing
D = [512, 4096, 5120, 13824]  # Arbitrary values for testing
SEEDS = [0]

Woosuk Kwon's avatar
Woosuk Kwon committed
13
14
15
16
17
18

def ref_silu_and_mul(x: torch.Tensor) -> torch.Tensor:
    x1, x2 = x.chunk(chunks=2, dim=1)
    return F.silu(x1) * x2


19
20
21
22
@pytest.mark.parametrize("num_tokens", NUM_TOKENS)
@pytest.mark.parametrize("d", D)
@pytest.mark.parametrize("dtype", DTYPES)
@pytest.mark.parametrize("seed", SEEDS)
Woosuk Kwon's avatar
Woosuk Kwon committed
23
@torch.inference_mode()
24
def test_silu_and_mul(
Woosuk Kwon's avatar
Woosuk Kwon committed
25
26
27
    num_tokens: int,
    d: int,
    dtype: torch.dtype,
28
    seed: int,
Woosuk Kwon's avatar
Woosuk Kwon committed
29
) -> None:
30
31
    torch.random.manual_seed(seed)
    torch.cuda.manual_seed(seed)
Woosuk Kwon's avatar
Woosuk Kwon committed
32
33
34
35
36
37
38
    x = torch.randn(num_tokens, 2 * d, dtype=dtype, device='cuda')
    out = torch.empty(num_tokens, d, dtype=dtype, device='cuda')
    activation_ops.silu_and_mul(out, x)
    ref_out = ref_silu_and_mul(x)
    assert torch.allclose(out, ref_out, atol=1e-5, rtol=1e-5)


39
40
41
42
@pytest.mark.parametrize("num_tokens", NUM_TOKENS)
@pytest.mark.parametrize("d", D)
@pytest.mark.parametrize("dtype", DTYPES)
@pytest.mark.parametrize("seed", SEEDS)
43
@torch.inference_mode()
44
def test_gelu_new(
45
46
47
    num_tokens: int,
    d: int,
    dtype: torch.dtype,
48
    seed: int,
49
) -> None:
50
51
    torch.random.manual_seed(seed)
    torch.cuda.manual_seed(seed)
52
53
54
55
56
57
58
    x = torch.randn(num_tokens, d, dtype=dtype, device='cuda')
    out = torch.empty(num_tokens, d, dtype=dtype, device='cuda')
    activation_ops.gelu_new(out, x)
    ref_out = get_activation("gelu_new")(x)
    assert torch.allclose(out, ref_out, atol=1e-5, rtol=1e-5)


59
60
61
62
63
@pytest.mark.parametrize("num_tokens", NUM_TOKENS)
@pytest.mark.parametrize("d", D)
@pytest.mark.parametrize("dtype", DTYPES)
@pytest.mark.parametrize("seed", SEEDS)
def test_gelu_fast(
64
65
66
    num_tokens: int,
    d: int,
    dtype: torch.dtype,
67
    seed: int,
68
) -> None:
69
70
    torch.random.manual_seed(seed)
    torch.cuda.manual_seed(seed)
71
72
73
74
75
    x = torch.randn(num_tokens, d, dtype=dtype, device='cuda')
    out = torch.empty(num_tokens, d, dtype=dtype, device='cuda')
    activation_ops.gelu_fast(out, x)
    ref_out = get_activation("gelu_fast")(x)
    assert torch.allclose(out, ref_out, atol=1e-5, rtol=1e-5)