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
11 changes: 11 additions & 0 deletions mlx/random.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright © 2023-2024 Apple Inc.

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <sstream>

Expand All @@ -14,6 +16,15 @@ namespace mlx::core::random {

KeySequence::KeySequence(uint64_t seed) : key_(key(seed)) {}

uint64_t KeySequence::default_seed() {
static const uint64_t time_seed =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
static std::atomic<uint64_t> count{0};
return time_seed + count++;
}

void KeySequence::seed(uint64_t seed) {
key_ = key((seed));
}
Expand Down
12 changes: 4 additions & 8 deletions mlx/random.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

#pragma once

#include <chrono>
#include <optional>

#include "mlx/api.h"
Expand All @@ -21,16 +20,13 @@ class MLX_API KeySequence {

// Each thread has its own random key to avoid race condition.
static KeySequence& default_() {
static auto time_seed = []() {
auto now = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch())
.count();
}();
static thread_local KeySequence ks(time_seed);
static thread_local KeySequence ks(default_seed());
return ks;
}

// Seed for a new default key. Each call returns a different seed.
static uint64_t default_seed();

private:
array key_;
};
Expand Down
10 changes: 1 addition & 9 deletions python/src/random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
#include <nanobind/stl/variant.h>
#include <nanobind/stl/vector.h>

#include <chrono>

#include "mlx/ops.h"
#include "mlx/random.h"
#include "python/src/random.h"
Expand Down Expand Up @@ -42,14 +40,8 @@ class PyKeySequence {

nb::list& state() {
if (!state_) {
static auto time_seed = []() {
auto now = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch())
.count();
}();
state_ = nb::list();
state_->append(mx::random::key(time_seed));
state_->append(mx::random::key(mx::random::KeySequence::default_seed()));
}
return *state_;
}
Expand Down
20 changes: 20 additions & 0 deletions python/tests/test_threads.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,26 @@ def vmap_worker():
t.join()
self.assertEqual(errors, [])

def test_default_random_key_per_thread(self):
# Threads that do not call seed() must not get the same numbers.
n_threads = 4
results = [None] * n_threads

def draw(i):
results[i] = mx.random.uniform(shape=(8,)).tolist()

threads = [threading.Thread(target=draw, args=(i,)) for i in range(n_threads)]
for t in threads:
t.start()
for t in threads:
t.join()

main_result = mx.random.uniform(shape=(8,)).tolist()
all_results = results + [main_result]
for i in range(len(all_results)):
for j in range(i + 1, len(all_results)):
self.assertNotEqual(all_results[i], all_results[j])


if __name__ == "__main__":
mlx_tests.MLXTestRunner()
22 changes: 22 additions & 0 deletions tests/random_tests.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright © 2023 Apple Inc.

#include <numeric>
#include <thread>

#include "doctest/doctest.h"

Expand Down Expand Up @@ -36,6 +37,27 @@ TEST_CASE("test global rng") {
CHECK_EQ(y.item<uint32_t>(), b.item<uint32_t>());
}

TEST_CASE("test default key per thread") {
// Threads that do not call seed() must not get the same bits.
constexpr int n_threads = 4;
std::vector<uint32_t> results(n_threads);
std::vector<std::thread> threads;
for (int i = 0; i < n_threads; ++i) {
threads.emplace_back([&results, i]() {
results[i] =
random::bits({}, 4, std::nullopt, Device::cpu).item<uint32_t>();
});
}
for (auto& t : threads) {
t.join();
}
for (int i = 0; i < n_threads; ++i) {
for (int j = i + 1; j < n_threads; ++j) {
CHECK_NE(results[i], results[j]);
}
}
}

TEST_CASE("test random split") {
auto [key, subkey] = random::split(random::key(0));
CHECK(array_equal(key, array({4146024105u, 967050713u})).item<bool>());
Expand Down
Loading