test_activation.py 2.29 KB
Newer Older
Woosuk Kwon's avatar
Woosuk Kwon committed
1
2
import torch
import torch.nn.functional as F
3
from transformers.activations import get_activation
Woosuk Kwon's avatar
Woosuk Kwon committed
4
from vllm import activation_ops
Woosuk Kwon's avatar
Woosuk Kwon committed
5
6
7
8
9
10
11
12


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


@torch.inference_mode()
13
def run_silu_and_mul(
Woosuk Kwon's avatar
Woosuk Kwon committed
14
15
16
17
18
19
20
21
22
23
24
    num_tokens: int,
    d: int,
    dtype: torch.dtype,
) -> None:
    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)


25
def test_silu_and_mul() -> None:
26
    for dtype in [torch.half, torch.bfloat16, torch.float]:
Woosuk Kwon's avatar
Woosuk Kwon committed
27
        for num_tokens in [7, 83, 2048]:
28
            for d in [512, 4096, 5120, 13824]:
Woosuk Kwon's avatar
Woosuk Kwon committed
29
                print(f'Testing dtype={dtype}, num_tokens={num_tokens}, d={d}')
30
                run_silu_and_mul(num_tokens, d, dtype)
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72


@torch.inference_mode()
def run_gelu_new(
    num_tokens: int,
    d: int,
    dtype: torch.dtype,
) -> None:
    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)


def test_gelu_new() -> None:
    for dtype in [torch.half, torch.bfloat16, torch.float]:
        for num_tokens in [7, 83, 2048]:
            for d in [512, 4096, 5120, 13824]:
                print(f'Testing dtype={dtype}, num_tokens={num_tokens}, d={d}')
                run_gelu_new(num_tokens, d, dtype)


@torch.inference_mode()
def run_gelu_fast(
    num_tokens: int,
    d: int,
    dtype: torch.dtype,
) -> None:
    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)


def test_gelu_fast() -> None:
    for dtype in [torch.half, torch.bfloat16, torch.float]:
        for num_tokens in [7, 83, 2048]:
            for d in [512, 4096, 5120, 13824]:
                print(f'Testing dtype={dtype}, num_tokens={num_tokens}, d={d}')
                run_gelu_fast(num_tokens, d, dtype)