Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions mlx/random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,19 @@ array normal(
const std::optional<array>& scale,
const std::optional<array>& key,
StreamOrDevice s /* = {} */) {
auto out_shape = shape;
if (loc) {
out_shape = broadcast_shapes(out_shape, loc->shape());
}
if (scale) {
out_shape = broadcast_shapes(out_shape, scale->shape());
}
if (out_shape != shape) {
std::ostringstream msg;
msg << "[normal] Cannot generate random values of shape " << shape
<< " from broadcasted shape " << out_shape << ".";
throw std::invalid_argument(msg.str());
}
if (dtype == complex64) {
return complex_normal(shape, loc, scale, key, s);
} else if (!issubdtype(dtype, floating)) {
Expand Down
10 changes: 10 additions & 0 deletions python/tests/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,16 @@ def test_normal_and_laplace(self):
a = abs(distribution_sampler(shape=(10000,), loc=0, scale=1, dtype=hp))
self.assertTrue(mx.all(a < mx.inf))

def test_normal_loc_scale_shape(self):
msg = r"\[normal\] Cannot generate random values"
with self.assertRaisesRegex(ValueError, msg):
mx.random.normal(shape=(3,), loc=mx.zeros((2, 3)))
with self.assertRaisesRegex(ValueError, msg):
mx.random.normal(shape=(3,), scale=mx.ones((2, 3)))

x = mx.random.normal(shape=(2, 3), loc=mx.zeros((3,)), scale=mx.ones((2, 1)))
self.assertEqual(x.shape, (2, 3))

def test_multivariate_normal(self):
key = mx.random.key(0)
mean = mx.array([0, 0])
Expand Down
Loading