test_int8_quant.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import pytest
  2. import torch
  3. from aphrodite._custom_ops import scaled_int8_quant
  4. from tests.kernels.quant_utils import ref_dynamic_per_token_quant
  5. from tests.kernels.utils import opcheck
  6. DTYPES = [torch.half, torch.bfloat16, torch.float]
  7. HIDDEN_SIZES = [16, 67, 768, 2048, 5120, 5137, 8192,
  8. 8193] # Arbitrary values for testing
  9. NUM_TOKENS = [1, 7, 83, 4096] # Arbitrary values for testing
  10. SEEDS = [0]
  11. SCALE = [0.1, 0.5, 0.8, 1.2, 2.1]
  12. def opcheck_int8_quant(output, input, scale=None):
  13. if scale is not None:
  14. opcheck(torch.ops._C.static_scaled_int8_quant, (output, input, scale))
  15. else:
  16. scale = torch.empty((input.numel() // input.shape[-1], 1),
  17. device=input.device,
  18. dtype=torch.float32)
  19. opcheck(torch.ops._C.dynamic_scaled_int8_quant, (output, input, scale))
  20. @pytest.mark.parametrize("num_tokens", NUM_TOKENS)
  21. @pytest.mark.parametrize("hidden_size", HIDDEN_SIZES)
  22. @pytest.mark.parametrize("dtype", DTYPES)
  23. @pytest.mark.parametrize("seed", SEEDS)
  24. @torch.inference_mode()
  25. def test_dynamic_scaled_int8_quant(num_tokens: int, hidden_size: int,
  26. dtype: torch.dtype, seed: int) -> None:
  27. torch.random.manual_seed(seed)
  28. torch.cuda.manual_seed(seed)
  29. x = torch.rand(num_tokens, hidden_size, dtype=dtype, device="cuda") * 1000
  30. # reference
  31. ref_out, ref_scales = ref_dynamic_per_token_quant(x, torch.int8)
  32. # kernel
  33. ops_out, ops_scales = scaled_int8_quant(x)
  34. torch.testing.assert_close(ops_scales, ref_scales)
  35. torch.testing.assert_close(
  36. ops_out, ref_out, atol=1,
  37. rtol=0.0) # big atol to account for rounding errors
  38. opcheck_int8_quant(ops_out, x)
  39. @pytest.mark.parametrize("num_tokens", NUM_TOKENS)
  40. @pytest.mark.parametrize("hidden_size", HIDDEN_SIZES)
  41. @pytest.mark.parametrize("dtype", DTYPES)
  42. @pytest.mark.parametrize("seed", SEEDS)
  43. @pytest.mark.parametrize("scale", SCALE)
  44. @torch.inference_mode()
  45. def test_static_scaled_int8_quant(num_tokens: int, hidden_size: int,
  46. dtype: torch.dtype, seed: int,
  47. scale: float) -> None:
  48. torch.random.manual_seed(seed)
  49. torch.cuda.manual_seed(seed)
  50. int8_traits = torch.iinfo(torch.int8)
  51. x = torch.rand(num_tokens, hidden_size, dtype=dtype, device="cuda") * 1000
  52. scale = torch.tensor([scale], dtype=torch.float32, device="cuda")
  53. out1 = (x / scale).round().clamp(int8_traits.min,
  54. int8_traits.max).to(torch.int8)
  55. out2, _ = scaled_int8_quant(x, scale)
  56. torch.testing.assert_close(
  57. out1, out2, atol=1,
  58. rtol=0.0) # big atol to account for rounding errors
  59. opcheck_int8_quant(out2, x, scale)