test_rand.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import random
  2. import pytest
  3. import torch
  4. from aphrodite.modeling.layers.ops.rand import seeded_uniform
  5. from aphrodite.modeling.utils import set_random_seed
  6. @pytest.mark.parametrize("dtype",
  7. [torch.float32, torch.float16, torch.bfloat16])
  8. @pytest.mark.parametrize("use_3d", [True, False])
  9. def test_seeded_uniform(dtype: torch.dtype, use_3d: bool):
  10. device = "cuda"
  11. for seed in range(512):
  12. set_random_seed(seed)
  13. rows = random.randint(1, 512)
  14. cols = random.randint(1, 64000)
  15. if use_3d:
  16. third_dim = random.randint(2, 10)
  17. dims = [rows, third_dim, cols]
  18. else:
  19. dims = [rows, cols]
  20. seeds = torch.randint(torch.iinfo(torch.long).min,
  21. torch.iinfo(torch.long).max, (rows, ),
  22. device=device)
  23. # Test that the same seed produces the same output
  24. out = seeded_uniform(*dims, seeds=seeds, dtype=dtype, device=device)
  25. out2 = seeded_uniform(*dims, seeds=seeds, dtype=dtype, device=device)
  26. torch.testing.assert_close(out, out2)
  27. # del to save memory
  28. del out2
  29. out3 = seeded_uniform(*dims, seeds=seeds, dtype=dtype, device=device)
  30. torch.testing.assert_close(out, out3)
  31. # del to save memory
  32. del out3
  33. # Initialize out tensor with garbage to ensure that it is overwritten
  34. out_with_tensor = seeded_uniform(
  35. *dims,
  36. out=torch.full(
  37. (*dims, ),
  38. -1,
  39. dtype=dtype,
  40. device=device,
  41. ),
  42. seeds=seeds,
  43. dtype=dtype,
  44. )
  45. torch.testing.assert_close(out, out_with_tensor)