Repository navigation
Store the Cython random number buffers by value in the random state (fixes restore after a buffer refill) - #1896
Merged
mstimberg merged 1 commit intoOct 20, 2026
Conversation
RuntimeDevice.rand_buffer and randn_buffer held the address of a buffer of 20000 random numbers allocated by the generated Cython code, and get_random_state stored this address. When the buffer was refilled between store() and restore(restore_random_state=True), the restored address referred to freed memory: the restored run read wrong values, and the next refill freed the same block a second time. The device now owns the buffers (float64 arrays of RANDOM_BUFFER_SIZE values), the generated code refills them in place, and the random state contains their values. A state stored by an earlier version (an address instead of the values) is never dereferenced: if its index is non-zero, a warning is logged and the buffer is refilled from the restored numpy state. Fixes brian-team#1893 Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1893.
As discussed in #1893, the runtime device now owns the
rand()/randn()buffers of the Cython target and stores their content, instead of the address of a buffer allocated (and freed) by the generated code. This removes the dangling pointer that maderestore(restore_random_state=True)read freed memory, or free a block twice, when a buffer was refilled betweenstore()andrestore().Changes
brian2/devices/device.py:RANDOM_BUFFER_SIZE = 20000(moved fromcython_generator.py).RuntimeDevice.rand_bufferandrandn_bufferarenp.zeros(RANDOM_BUFFER_SIZE, dtype=np.float64)arrays instead of a size-1intparray holding a pointer.get_random_stateis unchanged apart from a comment: it now copies the numbers themselves.set_random_statecopies into the existing arrays, since the generated code refers to their data. A state stored by an earlier version (size-1 array holding an address) is never dereferenced: if its index is non-zero, a warning is logged and the index is set to 0, so that the buffer is refilled from the restored numpy state; with index 0 the restore is exact and nothing is logged.brian2/codegen/generators/cython_generator.pyandtemplates/common_group.pyx:_rand/_randnrefill the device's buffer in place withmemcpyfrom a freshnumpy.random.rand(n)/randn(n)array, and no longer callfree(), clearOWNDATAor store an address. The numbers drawn are the same as before (see below).freecimport and thePyArray_CLEARFLAGSdeclaration incommon_group.pyx. Brian's own code no longer uses them, but I did not want to remove names that user-provided Cython implementations might rely on; I can remove them if you prefer.brian2/tests/test_network.py(runtime targets only, skipped for standalone liketest_restore_with_random_state):test_restore_random_state_after_buffer_refills[rand|randn]: stores the state with 51 numbers left in the buffer, then makes three assignments ofRANDOM_BUFFER_SIZE - 51values, each of which refills the buffer, restores, and checks that the three assignments are reproduced exactly.seed()empties the buffers first, so the test does not depend on the tests that ran before it.test_restore_random_state_from_file_in_new_process[rand|randn]: stores the state to a file, then restores it in a new Python process (same preferences, passed throughprefs.as_file) and compares the next assignment.test_restore_random_state_without_buffer_content(codegen independent): a state in the old format with a non-zerorandindex logs one warning and resets that index, while therandnbuffer with index 0 is restored silently.Validation
Linux (WSL Ubuntu 24.04, kernel 6.18), gcc 13.3, Python 3.13.14, numpy 2.5.4, Cython 3.3.0, on master 9f803d0 with the extensions built from source (
setup.py build_ext --inplace). Windows and macOS were not tested locally.RANDOM_BUFFER_SIZEwritten out as 20000, since master does not define it), all five runtime tests fail with Cython: the in-process tests report 51 mismatched elements out of 19949 (the numbers left in the buffer atstore(), read back from freed memory), and the child process of the file tests is killed by a segmentation fault (return code -11).test_restore_random_state_without_buffer_contentalso fails, since master logs no warning. With this branch, the 11 selected runs (codegen independent, Cython, numpy) pass, with the defaultfloat_dtypeand withfloat_dtype=float32.brian2.test(["cython", "numpy"], test_codegen_independent=True, test_in_parallel=[...]), long tests excluded): with this branch, 56 doctests, 436 codegen-independent, 305 Cython and 308 numpy tests pass; on master, 56, 435, 301 and 304 (the difference is the new tests). The only failure,test_base.py::test_version, occurs on both, because the tests ran from a source copy withoutsetuptools_scm. In this run,test_restore_with_random_statepassed on master: whether it crashes depends on the tests that ran before it in the same worker.randndraws beforestore()): master givesidentical=Trueat 0, an abort (double free or corruption) at 19500 andidentical=Falseat 19990; this branch givesidentical=Trueat all three.rand(), 50 000randn(), 500 steps of a noisyNeuronGroup(5e5xidraws) and a 1000-neuronPoissonGroupgive bit-identical values and spikes on master and on this branch..pre-commit-config.yaml):ruff formatleaves the three Python files unchanged andruff checkreports nothing ondevice.pyandcython_generator.py.Compatibility and cost
restore_random_state=Trueby an earlier version:ValueError: could not broadcast input array from shape (20000,) into shape (1,). Restores withoutrestore_random_state=Truedo not read the random state (Network.restore), so they are not affected in either direction.store()in memory shows no measurable difference;store(filename=...)writes 323 kB instead of 3 kB and took 1.5 to 3.5 ms instead of 0.4 to 0.6 ms (per-process medians, 8 processes per version).NeuronGroupdrawing 1e7randnvalues per run (500 refills) took a median of 0.274 s per run with this branch against 0.272 s on master (+0.8 %; 10 processes per version in random order, pinned to one core, 9 runs each). Without pinning, the timings of both versions were bimodal (about 0.27 s or 0.37 s), so unpinned comparisons on this machine were not conclusive.buffer[index:]; I kept the simpler version, but can change it if the state size matters.Relation with #1745
#1745 replaces the buffers by a shared C++ generator and also removes the dangling pointer. As you wrote in #1893, this fix can go in first; the new tests could then serve as acceptance tests for #1745 (except the old-format one). On its head (62829a7), the
randtests pass and eachrandntest fails on one element, becauseget_statewritesstored_gausswith 6 significant digits (details in #1893).This should also remove the flaky heap corruption in
test_restore_with_random_stateseen in the Python 3.15 jobs of #1891.I used an AI assistant (Claude Code) to write the fix and the tests, run the validation and draft this description.