test_activation.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Test suite for the activation kernel."""
  2. import pytest
  3. import torch
  4. import torch.nn.functional as F
  5. from transformers.activations import get_activation
  6. from aphrodite import activation_ops
  7. DTYPES = [torch.half, torch.bfloat16, torch.float]
  8. NUM_TOKENS = [7, 38, 2048]
  9. D = [512, 4096, 5120, 13824] # arbitrary values for testing
  10. SEEDS = [0]
  11. def ref_silu_and_mul(x: torch.Tensor) -> torch.Tensor:
  12. x1, x2 = x.chunk(chunks=2, dim=1)
  13. return F.silu(x1) * x2
  14. @pytest.mark.parametrize("num_tokens", NUM_TOKENS)
  15. @pytest.mark.parametrize("d", D)
  16. @pytest.mark.parametrize("dtype", DTYPES)
  17. @pytest.mark.parametrize("seed", SEEDS)
  18. @torch.inference_mode()
  19. def test_silu_and_mul(
  20. num_tokens: int,
  21. d: int,
  22. dtype: torch.dtype,
  23. seed: int,
  24. ) -> None:
  25. torch.random.manual_seed(seed)
  26. torch.cuda.manual_seed(seed)
  27. x = torch.randn(num_tokens, 2 * d, dtype=dtype, device="cuda")
  28. out = torch.empty(num_tokens, d, dtype=dtype, device="cuda")
  29. activation_ops.silu_and_mul(out, x)
  30. ref_out = ref_silu_and_mul(x)
  31. assert torch.allclose(out, ref_out, atol=1e-5, rtol=1e-5)
  32. @pytest.mark.parametrize("num_tokens", NUM_TOKENS)
  33. @pytest.mark.parametrize("d", D)
  34. @pytest.mark.parametrize("dtype", DTYPES)
  35. @pytest.mark.parametrize("seed", SEEDS)
  36. @torch.inference_mode()
  37. def test_gelu_new(
  38. num_tokens: int,
  39. d: int,
  40. dtype: torch.dtype,
  41. seed: int,
  42. ) -> None:
  43. torch.random.manual_seed(seed)
  44. torch.cuda.manual_seed(seed)
  45. x = torch.randn(num_tokens, d, dtype=dtype, device='cuda')
  46. out = torch.empty(num_tokens, d, dtype=dtype, device='cuda')
  47. activation_ops.gelu_new(out, x)
  48. ref_out = get_activation("gelu_new")(x)
  49. assert torch.allclose(out, ref_out, atol=1e-5, rtol=1e-5)
  50. @pytest.mark.parametrize("num_tokens", NUM_TOKENS)
  51. @pytest.mark.parametrize("d", D)
  52. @pytest.mark.parametrize("dtype", DTYPES)
  53. @pytest.mark.parametrize("seed", SEEDS)
  54. def test_gelu_fast(
  55. num_tokens: int,
  56. d: int,
  57. dtype: torch.dtype,
  58. seed: int,
  59. ) -> None:
  60. torch.random.manual_seed(seed)
  61. torch.cuda.manual_seed(seed)
  62. x = torch.rand(num_tokens, d, dtype=dtype, device='cuda')
  63. out = torch.empty(num_tokens, d, dtype=dtype, device='cuda')
  64. activation_ops.gelu_fast(out, x)
  65. ref_out = get_activation("gelu_fast")(x)
  66. assert torch.allclose(out, ref_out, atol=1e-5, rtol=1e-5)