[BUG] RandomBits::is_equivalent() ignores width_
Describe the bug RandomBits::is_equivalent() currently compares only shape_, which incorrectly treats two RandomBits primitives with the same shape but different width_ as equivalent. Since width_ affects output dtype/bit-width, this is a correctness bug and can lead to incorrect reuse decisions in optimization/caching code that relies on primitive equivalence.
To Reproduce
I added a minimal doctest regression that constructs two RandomBits primitives with identical shape and different widths and checks they are not equivalent.
Create a file poc.cpp in the tests directory with the following code:
#include <doctest/doctest.h>
#include "mlx/primitives.h"
#include "mlx/stream.h"
using namespace mlx::core;
TEST_CASE("RandomBits::is_equivalent must consider width") {
Stream s(0, Device::cpu);
Shape shape{32, 32};
RandomBits rb_u8(s, shape, /*width=*/1);
RandomBits rb_u32(s, shape, /*width=*/4);
CHECK_FALSE(rb_u8.is_equivalent(static_cast<const Primitive&>(rb_u32)));
RandomBits rb_u8_2(s, shape, /*width=*/1);
CHECK(rb_u8.is_equivalent(static_cast<const Primitive&>(rb_u8_2)));
}
Update CMakeLists.txt target sources to include poc.cpp
target_sources(
tests
PRIVATE allocator_tests.cpp
array_tests.cpp
arg_reduce_tests.cpp
autograd_tests.cpp
blas_tests.cpp
compile_tests.cpp
custom_vjp_tests.cpp
creations_tests.cpp
device_tests.cpp
einsum_tests.cpp
export_import_tests.cpp
eval_tests.cpp
fft_tests.cpp
load_tests.cpp
ops_tests.cpp
random_tests.cpp
scheduler_tests.cpp
utils_tests.cpp
vmap_tests.cpp
linalg_tests.cpp
poc.cpp
${METAL_TEST_SOURCES})
Rebuild and rerun the tests. When you do you will see:
/Users/daniel/Code/C++/mlx/tests/poc.cpp:8:
TEST CASE: RandomBits::is_equivalent must consider width
/Users/daniel/Code/C++/mlx/tests/poc.cpp:16: ERROR: CHECK_FALSE( rb_u8.is_equivalent(static_cast<const Primitive&>(rb_u32)) ) is NOT correct!
values: CHECK_FALSE( true )
Expected behavior Creating a RandomBits object uses a shape and width. Shape is the dimensions of the array, while width is the size of each element, and the comparison is_equivalent should compare both shape and width because the domain values available for a 1 byte width vs a 4 byte width is significantly different
Desktop (please complete the following information):
- OS Version: MacOS 26.2
- MacBook Air M2
I pasted a patch