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
14 changes: 9 additions & 5 deletions mlx/backend/cpu/primitives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>
#include <numeric>
#include <sstream>
#include <type_traits>
Expand Down Expand Up @@ -271,9 +272,12 @@ void RandomBits::eval_cpu(const std::vector<array>& inputs, array& out) {
num_keys,
kshape = keys.shape(),
kstrides = keys.strides()]() mutable {
auto store = [](char* cptr, size_t loc, uint32_t v) {
std::memcpy(cptr + sizeof(v) * loc, &v, sizeof(v));
};
auto copy_remaining = [&](char* cptr, size_t loc, uint32_t v) {
if (4 * loc + 4 <= bytes_per_key) {
reinterpret_cast<uint32_t*>(cptr)[loc] = v;
store(cptr, loc, v);
} else {
std::copy(
reinterpret_cast<char*>(&v),
Expand All @@ -286,7 +290,6 @@ void RandomBits::eval_cpu(const std::vector<array>& inputs, array& out) {
auto half_size = out_skip / 2;
bool even = out_skip % 2 == 0;
for (int i = 0; i < num_keys; ++i, cptr += bytes_per_key) {
auto ptr = reinterpret_cast<uint32_t*>(cptr);
// Get ith key
auto kidx = 2 * i;
auto k1_elem = elem_to_loc(kidx, kshape, kstrides);
Expand All @@ -295,12 +298,13 @@ void RandomBits::eval_cpu(const std::vector<array>& inputs, array& out) {

std::pair<uintptr_t, uintptr_t> count{0, half_size + !even};
for (; count.first + 1 < half_size; count.first++, count.second++) {
std::tie(ptr[count.first], ptr[count.second]) =
random::threefry2x32_hash(key, count);
auto [first, second] = random::threefry2x32_hash(key, count);
store(cptr, count.first, first);
store(cptr, count.second, second);
}
if (count.first < half_size) {
auto rb = random::threefry2x32_hash(key, count);
ptr[count.first++] = rb.first;
store(cptr, count.first++, rb.first);
copy_remaining(cptr, count.second, rb.second);
}
if (!even) {
Expand Down
16 changes: 16 additions & 0 deletions tests/random_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,22 @@ TEST_CASE("test random split") {
CHECK(array_equal(keys, expected).item<bool>());
}

TEST_CASE("test random bits with keys at unaligned offsets") {
auto keys = random::split(random::key(0), 4);
for (int width : {1, 2}) {
CAPTURE(width);
auto fn = [width](array k) {
return random::bits({3}, width, k, Device::cpu);
};
auto out = vmap(fn)(keys);
for (int i = 0; i < keys.shape(0); ++i) {
CAPTURE(i);
auto expected = random::bits({3}, width, take(keys, i, 0), Device::cpu);
CHECK(array_equal(take(out, i, 0), expected).item<bool>());
}
}
}

TEST_CASE("test random bits") {
// Test shapes, types, and sizes
{
Expand Down
Loading