| 65 | self.assertEqual(mx.random.uniform().dtype, mx.random.uniform(dtype=None).dtype) |
| 66 | |
| 67 | def test_normal_and_laplace(self): |
| 68 | # Same tests for normal and laplace. |
| 69 | for distribution_sampler in [mx.random.normal, mx.random.laplace]: |
| 70 | key = mx.random.key(0) |
| 71 | a = distribution_sampler(key=key) |
| 72 | self.assertEqual(a.shape, ()) |
| 73 | self.assertEqual(a.dtype, mx.float32) |
| 74 | |
| 75 | b = distribution_sampler(key=key) |
| 76 | self.assertEqual(a.item(), b.item()) |
| 77 | |
| 78 | a = distribution_sampler(shape=(2, 3)) |
| 79 | self.assertEqual(a.shape, (2, 3)) |
| 80 | |
| 81 | ## Generate in float16 or bfloat16 |
| 82 | for t in [mx.float16, mx.bfloat16]: |
| 83 | a = distribution_sampler(dtype=t) |
| 84 | self.assertEqual(a.dtype, t) |
| 85 | |
| 86 | # Generate with a given mean and standard deviation |
| 87 | loc = 1.0 |
| 88 | scale = 2.0 |
| 89 | |
| 90 | a = distribution_sampler(shape=(3, 2), loc=loc, scale=scale, key=key) |
| 91 | b = scale * distribution_sampler(shape=(3, 2), key=key) + loc |
| 92 | self.assertTrue(mx.allclose(a, b)) |
| 93 | |
| 94 | a = distribution_sampler( |
| 95 | shape=(3, 2), loc=loc, scale=scale, dtype=mx.float16, key=key |
| 96 | ) |
| 97 | b = ( |
| 98 | scale * distribution_sampler(shape=(3, 2), dtype=mx.float16, key=key) |
| 99 | + loc |
| 100 | ) |
| 101 | self.assertTrue(mx.allclose(a, b)) |
| 102 | |
| 103 | self.assertEqual( |
| 104 | distribution_sampler().dtype, distribution_sampler(dtype=None).dtype |
| 105 | ) |
| 106 | |
| 107 | # Test not getting -inf or inf with half precison |
| 108 | for hp in [mx.float16, mx.bfloat16]: |
| 109 | a = abs(distribution_sampler(shape=(10000,), loc=0, scale=1, dtype=hp)) |
| 110 | self.assertTrue(mx.all(a < mx.inf)) |
| 111 | |
| 112 | def test_multivariate_normal(self): |
| 113 | key = mx.random.key(0) |