Skip to content

Move Cython random number generation to C++ mechanism - #1745

Open
Legend101Zz wants to merge 16 commits into
brian-team:masterfrom
Legend101Zz:feat/rng-cython
Open

Legend101Zz wants to merge 16 commits into
brian-team:masterfrom
Legend101Zz:feat/rng-cython

Conversation

@Legend101Zz

@Legend101Zz Legend101Zz commented Dec 17, 2025 •

Copy link
Copy Markdown
Contributor

Fixes #1664

Random Number Generation Update (Runtime Mode)

Random number generation in runtime mode now uses the same C++ algorithm as C++ standalone mode. As a result:

  • Simulations run with seed(X) will now produce identical results in both runtime and standalone modes.
  • Simulations using the same seed will produce different results compared to earlier Brian2 versions when run in runtime mode.
  • C++ standalone mode results remain unchanged.
  • The get_random_state() and set_random_state() methods now return simplified values, making them easier to use.

cc: @mstimberg

@mstimberg mstimberg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Many thanks for this PR – I'm not 100% sure about the approach to do (and store/restore) seeds, but let's discuss this during our meeting 😊

@Legend101Zz

Copy link
Copy Markdown
Contributor Author

@mstimberg sorry for the long wait on this , finally got back to it and now tried the Pre-compiled RNG approch to prevent each code object from having it's own RNG , let's see if this works :)

@Legend101Zz

Copy link
Copy Markdown
Contributor Author

@mstimberg finally all tests pass :)

@Legend101Zz
Legend101Zz requested a review from mstimberg January 24, 2026 18:30

@mstimberg mstimberg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was in the process of updating the documentation when I realized something, and I have to think more about how to handle this. With this PR, Cython's random number generation is basically identical to C++ standalone mode, but there is one difference: using the seed function means setting both numpy's seed and the Cython RNG seed, whereas standalone mode will not set numpy's seed. This means, calling e.g. seed(1234) in Cython runtime mode is equivalent to the following in C++ standalone mode:

np.random.seed(1234)
seed(1234)

This is actually something that I've sometimes seen in code, but it is not a good thing, since it means that the two sources of randomness use identical random number streams. It's not something that you'd usually notice, but introducing these correlations isn't great. In an – admittedly contrived – example:

G = NeuronGroup(10, "v : 1")
np.random.seed(1234)
seed(1234)
G.v = np.random.rand(10)
G.run_regularly("v -= rand()")
run(defaultclock.dt)

Here, the initial values and the random values subtracted from v in the first time step will be identical, leading to the value of 0 for v in all neurons… Not sure how to best handle this, I will think about this some more (and/or maybe open a discussion about it on the discourse forum).

@Legend101Zz

Copy link
Copy Markdown
Contributor Author

I was in the process of updating the documentation when I realized something, and I have to think more about how to handle this. With this PR, Cython's random number generation is basically identical to C++ standalone mode, but there is one difference: using the seed function means setting both numpy's seed and the Cython RNG seed, whereas standalone mode will not set numpy's seed. This means, calling e.g. seed(1234) in Cython runtime mode is equivalent to the following in C++ standalone mode:

np.random.seed(1234)
seed(1234)

This is actually something that I've sometimes seen in code, but it is not a good thing, since it means that the two sources of randomness use identical random number streams. It's not something that you'd usually notice, but introducing these correlations isn't great. In an – admittedly contrived – example:

G = NeuronGroup(10, "v : 1")
np.random.seed(1234)
seed(1234)
G.v = np.random.rand(10)
G.run_regularly("v -= rand()")
run(defaultclock.dt)

Here, the initial values and the random values subtracted from v in the first time step will be identical, leading to the value of 0 for v in all neurons… Not sure how to best handle this, I will think about this some more (and/or maybe open a discussion about it on the discourse forum).

@mstimberg thanks for sharing this is really interesting. One thought is to add an explicit parameter, something like:

def seed(self, seed=None, include_numpy=False):

so users can opt into seeding NumPy as well (possibly with a warning).

The main concern I see is backward compatibility: existing code that relied on seed() implicitly seeding NumPy would suddenly start producing different results, and that change would happen silently.

That’s why I’m wondering if a staged (two-step) approach might work better.

Instead of seeding NumPy with the raw seed S, we could seed it with a deterministic function of S, say f(S).

This keeps both RNGs reproducible while ensuring they’re statistically independent.

To avoid a silent breaking change, we could introduce this gradually with a deprecation-style parameter.

def seed(self, seed=None, include_numpy='deprecated'):
    from brian2.random.cythonrng import seed as rng_seed
    rng_seed(seed)

    if seed is not None:
        if include_numpy == 'deprecated':
            # STAGE 1: preserve current behavior but warn
            import numpy as np
            np.random.seed(seed)
            logger.warn(
                "Seeding NumPy with the same value as Brian2 is deprecated. "
                "In future versions, NumPy will use a derived independent seed."
            )

        elif include_numpy is True:
            # STAGE 2 / OPT-IN: derived deterministic seed
            numpy_seed = (seed + 0x9E3779B9) & 0xFFFFFFFF. 
            # note 0x9E3779B9 is a well-known constant (golden ratio × 2^32) used in hash functions
            import numpy as np
            np.random.seed(numpy_seed)

This way:

• Existing users get the same behavior (with a warning)
• New behavior is opt-in initially
• Eventually the derived seed can become default

also If we adopt the derived-seed approach, we could update the Standalone code generator to inject the same NumPy seeding logic into the generated Python script.

@AxelNoun

Copy link
Copy Markdown
Contributor

While investigating #1893 (Cython target: restore(restore_random_state=True) uses a dangling pointer after a rand/randn buffer refill), I tested this PR at 62829a7. Since it removes the buffers, it fixes #1893 as well: the reproduction script from #1893 no longer crashes and restores exactly for the offsets reported there (0, 19500 and 19990 prior randn draws), and restoring the state from a file in a new process no longer segfaults as it does on master.

One problem remains. RandomGenerator::get_state() and operator<< in brian2/devices/cpp_standalone/brianlib/randomgenerator.h (lines 122 and 146) write stored_gauss with the default stream precision of 6 significant digits, so after an odd number of randn() calls the restored generator returns a rounded value on its next randn() call. For example, with seed(20261014) and the state stored after three randn() values, the fourth value is -1.4027538012180303 without a restore and -1.40275 after it. The script from #1893 shows the same with odd offsets (1 and 19991 give identical=False). Since the generator is not reseeded between tests, test_restore_with_random_state itself fails on this branch if the tests run before it in the same process leave an odd number of randn() draws.

Writing the value with max_digits10 (17) significant digits fixes it (change to brian2/devices/cpp_standalone/brianlib/randomgenerator.h). set_state() and operator>> need no change, and operator<< restores the precision of the caller's stream afterwards:

@@ -5,6 +5,7 @@
 #include <random>
 #include <cmath>
 #include <iostream>
+#include <limits>
 #include <sstream>
 #include <string>
 
@@ -119,6 +120,9 @@
      */
      std::string get_state() const {
          std::ostringstream oss;
+         // Write the cached value with enough digits to read it back exactly
+         // (the default precision of 6 significant digits would round it)
+         oss.precision(std::numeric_limits<double>::max_digits10);
          oss << gen << " " << stored_gauss << " " << has_stored_gauss;
          return oss.str();
      }
@@ -143,7 +147,12 @@
  */
 inline std::ostream &operator<<(std::ostream &out, const RandomGenerator &rng)
 {
-    return out << rng.gen << " " << rng.stored_gauss << " " << rng.has_stored_gauss;
+    // Write the cached value with enough digits to read it back exactly, and
+    // leave the precision of the stream unchanged afterwards
+    const std::streamsize precision = out.precision(std::numeric_limits<double>::max_digits10);
+    out << rng.gen << " " << rng.stored_gauss << " " << rng.has_stored_gauss;
+    out.precision(precision);
+    return out;
 }
 
 /**

operator<< also writes results/random_generator_state in C++ standalone mode (brian2/devices/cpp_standalone/templates/objects.cpp, lines 331-335), so that file becomes exact too: read back with operator>>, it now reproduces the next draws of the simulation (Brian itself does not read this file at the moment). Checked on Linux (gcc 13.3, Python 3.12, Cython 3.1.3, numpy 2.5.3): after 0, 1, 2, 3 and 19991 prior randn() calls, the draws after a restore are bit-identical through both get_state()/set_state() and operator<</operator>>; the random streams themselves do not change, and the existing random and store/restore tests still pass for the Cython target and for C++ standalone. I have not tested Windows or macOS.

I would also suggest adding the regression tests below to brian2/tests/test_network.py (public API only). They check that the random state is restored exactly after several assignments of 19949 values (an odd number) with rand() and with randn(), in a minimal case with three randn() values, and from a file in a new Python process, i.e. that the stored state does not refer to memory of the process that stored it. On 62829a7 with the Cython target, the three randn cases fail (one rounded value each, e.g. -2.32554 instead of -2.325544580499431) and the two rand cases pass; with the change above, all five pass for the Cython and numpy targets, with float64 and with float32. On current master, four of them fail because of #1893 (the new-process ones with a segfault in the child process); only the minimal randn case passes there, since the rounding is specific to this branch.

Tests (diff of brian2/tests/test_network.py against 62829a7)
@@ -37,6 +37,7 @@
     restore,
     run,
     second,
+    seed,
     start_scope,
     stop,
     store,
@@ -1531,6 +1532,127 @@
     assert_equal(old_v, group.v)
 
 
+# Number of values drawn by each rand() or randn() assignment in the tests below.
+# Earlier versions of the Cython target drew random numbers from numpy in batches
+# of 20000 values and stored the memory address of the current batch with the
+# random state (see issue #1893). With this number, every assignment after the
+# first one needed a new batch. The number is odd, so that randn(), which
+# generates normally distributed values in pairs, has a value left over when the
+# state is stored.
+_RANDOM_GROUP_SIZE = 20000 - 51
+
+
+@pytest.mark.skipif(
+    not isinstance(get_device(), RuntimeDevice),
+    reason="Getting/setting random number state only supported for runtime device.",
+)
+@pytest.mark.parametrize("func", ["rand", "randn"])
+def test_restore_random_state_after_many_draws(func):
+    seed(20261014)
+    group = NeuronGroup(_RANDOM_GROUP_SIZE, "x : 1")
+    net = Network(group)
+    group.x = f"{func}()"
+    net.store()
+    expected = []
+    for _ in range(3):
+        group.x = f"{func}()"
+        expected.append(np.array(group.x[:]))
+
+    net.restore(restore_random_state=True)
+    for values in expected:
+        group.x = f"{func}()"
+        assert_equal(group.x[:], values)
+
+
+@pytest.mark.skipif(
+    not isinstance(get_device(), RuntimeDevice),
+    reason="Getting/setting random number state only supported for runtime device.",
+)
+def test_restore_random_state_after_odd_number_of_randn():
+    # randn() generates normally distributed values in pairs and keeps the second
+    # value of a pair for its next call. After an odd number of values, this value
+    # is part of the random state and has to be restored exactly, not rounded.
+    seed(20261014)
+    group = NeuronGroup(3, "x : 1")
+    net = Network(group)
+    group.x = "randn()"
+    net.store()
+    group.x = "randn()"
+    expected = np.array(group.x[:])
+
+    net.restore(restore_random_state=True)
+    group.x = "randn()"
+    assert_equal(group.x[:], expected)
+
+
+# Run in a new Python process by
+# test_restore_random_state_from_file_in_new_process: restores the stored state
+# and saves the values of the next assignment
+_RESTORE_RANDOM_STATE_SCRIPT = """
+import sys
+
+brian2_dir, prefs_file, size, state_file, func, values_file = sys.argv[1:]
+sys.path.insert(0, brian2_dir)
+import numpy as np
+from brian2 import Network, NeuronGroup, prefs
+
+with open(prefs_file, encoding="utf-8") as f:
+    prefs.read_preference_file(f)
+group = NeuronGroup(int(size), "x : 1", name="random_state_group")
+net = Network(group)
+net.restore(filename=state_file, restore_random_state=True)
+group.x = f"{func}()"
+np.save(values_file, group.x[:])
+"""
+
+
+@pytest.mark.skipif(
+    not isinstance(get_device(), RuntimeDevice),
+    reason="Getting/setting random number state only supported for runtime device.",
+)
+@pytest.mark.parametrize("func", ["rand", "randn"])
+def test_restore_random_state_from_file_in_new_process(func):
+    # The stored state has to be complete in itself, without any reference to
+    # the memory of the process that stored it
+    import subprocess
+    import sys
+
+    import brian2
+
+    seed(20261014)
+    group = NeuronGroup(_RANDOM_GROUP_SIZE, "x : 1", name="random_state_group")
+    net = Network(group)
+    group.x = f"{func}()"
+    with tempfile.TemporaryDirectory() as tmpdir:
+        prefs_file = os.path.join(tmpdir, "preferences")
+        state_file = os.path.join(tmpdir, "state.pkl")
+        values_file = os.path.join(tmpdir, "values.npy")
+        # Same code generation targets and floating point type in the new process
+        with open(prefs_file, "w", encoding="utf-8") as f:
+            f.write(prefs.as_file)
+        net.store(filename=state_file)
+        group.x = f"{func}()"
+        expected = np.array(group.x[:])
+
+        result = subprocess.run(
+            [
+                sys.executable,
+                "-c",
+                _RESTORE_RANDOM_STATE_SCRIPT,
+                os.path.dirname(os.path.dirname(brian2.__file__)),
+                prefs_file,
+                str(_RANDOM_GROUP_SIZE),
+                state_file,
+                func,
+                values_file,
+            ],
+            capture_output=True,
+            text=True,
+        )
+        assert result.returncode == 0, result.stderr
+        assert_equal(np.load(values_file), expected)
+
+
 @pytest.mark.codegen_independent
 def test_store_restore_restore_synapses():
     group = NeuronGroup(10, "x : 1", threshold="False", reset="", name="group")

With both changes, the branch still merges cleanly into current master (8216baf), and the new tests also pass on the merged tree.

@Legend101Zz, I can open a PR with these two changes against feat/rng-cython in your fork if that helps, or you can take them over directly, whichever you prefer.

I used Claude Code (an AI assistant) to investigate this, run the tests and draft this comment.

@Legend101Zz

Copy link
Copy Markdown
Contributor Author

Hi @AxelNoun , thanks for raising this concern and for taking the time to investigate it!

I've been AFK recently, so I haven't had a chance to properly go through your findings yet. Could you give me a couple of days to review everything and get back to you?

On a side note, the work for this PR was essentially complete, but we couldn't merge it because of a backward compatibility issue it would have introduced. I don't quite remember the exact details anymore (my memory isn't the best 😅), but perhaps @mstimberg could help us here `:)

Anyway, let me go through your investigation properly, and I'll get back to you. Thanks again for looking into this!

@AxelNoun

AxelNoun commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Thanks @Legend101Zz, no rush at all.

One update since my comment: as @mstimberg preferred in #1893, the short-term fix for the dangling buffer pointer is now a separate PR, #1896 (the runtime device owns the buffers and stores their content). This branch still merges cleanly into current master, but if #1896 goes in first, merging will conflict in cython_generator.py and device.py (checked with git merge-tree against 62829a7). Since this branch removes the buffers, the resolution should mostly keep this branch's side, with two details: the tests added by #1896 import RANDOM_BUFFER_SIZE from brian2.devices.device, so the constant would need to stay (or the tests use 20000 directly), and test_restore_random_state_without_buffer_content only makes sense with the buffers. The stored_gauss precision fix from my previous comment is independent of #1896 and still needed here.

On the backward compatibility question: the open point in this thread seems to be the seeding one, i.e. @mstimberg's review of 30 January (with this branch, seed(S) seeds numpy and the C++ generator with the same value, so both produce the same stream) and your proposal of 2 February (a derived numpy seed with a deprecation step), which has no answer yet. A related point, from reading set_random_state on this branch: states stored by current master have no "rng_state" key, so restoring one with restore_random_state=True would raise a KeyError. Marcel will know whether either of these is the issue you remember.

@Legend101Zz

Copy link
Copy Markdown
Contributor Author

Hi @AxelNoun — really sorry for going MIA for the past month, and thanks a lot for the detailed follow-up and for getting #1896 merged in the meantime!

You're right on the backward-compatibility side: we were initially hesitant to merge because we were worried about regressions and breaking older user code / saved states. Looking back at it more carefully though, a lot of those concerns are either expected anyway (since Cython is switching to a different RNG mechanism, so exact Cython random streams and np.random.seed() coupling will naturally differ from older versions) or straightforward to handle cleanly:

  1. Old stored states (KeyError on "rng_state"): Since older Brian2 versions didn't use the C++ generator, we can't reproduce the old buffered Cython stream anyway — but we definitely shouldn't crash with a KeyError (especially since numpy-target states still have "numpy_state"). Doing an if "rng_state" in state: check and logging a warning (similar to how Store the Cython random number buffers by value in the random state (fixes restore after a buffer refill) #1896 handles older state files) avoids that regression cleanly.

  2. stored_gauss precision: Totally agree your max_digits10 fix in randomgenerator.h is needed here (and nice that it also makes results/random_generator_state in standalone exact).

  3. Merging with Store the Cython random number buffers by value in the random state (fixes restore after a buffer refill) #1896: Since Store the Cython random number buffers by value in the random state (fixes restore after a buffer refill) #1896 is now in master, I can rebase/merge onto master, resolve the conflicts in cython_generator.py and device.py, drop test_restore_random_state_without_buffer_content, and update the remaining tests from Store the Cython random number buffers by value in the random state (fixes restore after a buffer refill) #1896 so they don't depend on RANDOM_BUFFER_SIZE (along with the stored_gauss fix and the "rng_state" fallback warning).

The one real remaining regression/design question seems to be the seed(S) behavior from @mstimberg's Jan 30 review: right now RuntimeDevice.seed(S) seeds both the C++ RandomGenerator and np.random with the exact same S, causing identical uniform streams between np.random.rand() and Cython rand(), whereas stopping np.random.seed would affect prefs.codegen.target = "numpy" and user scripts relying on seed() for NumPy reproducibility.

@mstimberg — do you have a preference on how we should handle seed(S) (e.g. a derived seed for NumPy, only seeding NumPy differently, or something else)? Once we're aligned on that, I'm happy to rebase on master and fold in @AxelNoun's stored_gauss fix and the "rng_state" guard to get this ready.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Move Cython random number generation to C++ mechanism

3 participants