Repository navigation
Conversation
The Cython template substituted p instead of P = min(p, 1-p) into the recurrence of the inversion algorithm, which gave a wrong distribution for p > 0.5 whenever the normal approximation was not used. The constants of the inversion algorithm were written with 15 decimal places, so with approximate=False a small (1-P)**n was rounded, or written as zero, in which case the generated loop never terminated. Use P in the Cython template, write the constants with repr(float(x)), and register an availability_check that raises NotImplementedError at code generation when (1-P)**n is not a normal double; the numpy target is not affected. Add a test that compares the sampled distribution with the exact pmf, and a test for the underflow check. Fixes brian-team#1890 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The three failing jobs (Python 3.15, non-standalone, run 38100815108) crash in I reproduced the same crash on master (8216baf) by drawing Details, root cause and a proposed fix are in #1893. |
|
Thanks for the PR @AxelNoun. I'll have to postpone the review a bit, since I am currently wrapping up things for a release and this issue deserves a thorough look. PS: ignore the CI errors with "Illegal instruction", they are due to incompatible cached binaries that will soon be resolved. |
|
Thanks, no rush. Note that the three Python 3.15 failures on this PR are not the "Illegal instruction" ones: they are heap corruptions from #1893 (details in my comment above), so they may persist after the cache fix. |
Ok, thanks, I had overlooked your comment (and the related issue)… |
No problem at all. Following up on this: #1896 (the fix for #1893) is in 2.11.0, so I merged master into this branch. The three Python 3.15 jobs that crashed in |
antonsoo
left a comment
There was a problem hiding this comment.
Codex-run validation of 92f09d4f against 26d8f102, with the native extensions rebuilt from each checkout (Linux, Python 3.13.9, NumPy 2.5.4, Cython 3.3.0).
I checked the effect through PoissonInput into a decaying membrane state, beyond direct sampler calls:
import numpy as np
import brian2 as b
target = "cython" # also checked numpy and cpp_standalone
if target == "cpp_standalone":
b.set_device(target, directory=None)
else:
b.prefs.codegen.target = target
b.start_scope()
b.seed(20261101)
b.defaultclock.dt = 1*b.ms
g = b.NeuronGroup(10000, "dv/dt = -v/(10*ms) : volt", method="exact")
drive = b.PoissonInput(g, "v", N=10, rate=800*b.Hz, weight=.01*b.mV)
mon = b.StateMonitor(g, "v", record=True, when="end")
b.Network(g, drive, mon).run(200*b.ms)
v = np.asarray(mon.v/b.mV)
a = np.exp(-.1)
events = np.column_stack([v[:, 0], v[:, 1:]-a*v[:, :-1]])/.01
print("events mean/variance:", events.mean(), events.var(), "expected", 8, 1.6)
print("final mean mV:", v[:, -1].mean(), "expected", .01*8*(1-a**200)/(1-a))| Measurement | Base Cython | PR Cython | Expected |
|---|---|---|---|
| Events per step, mean | 9.107068 | 7.9995175 | 8 |
| Events per step, variance | 0.0956044 | 1.5999003 | 1.6 |
| Final mean voltage, mV | 0.9570359 | 0.8407351 | 0.8406666 |
The PR's full voltage trajectory is byte-identical to NumPy and C++ standalone for the same seed; the already-correct C++/NumPy trajectories are unchanged from base. This checks the discrete simulation's moments, not biological accuracy.
Additional scheduled BinomialFunction checks used 100,000 draws per case, including the normal-approximation boundary (n=20, p=.75 versus .749), endpoints, rare events and n=1022, p=.5, approximate=False. All 14 cases agree with independent binomial/normal moments on each target; all 7 already-correct Cython and 11 already-correct C++ controls remain byte-identical to base. The float32 Cython workload also passes. The n=1023 and 2000, p=.5, exact cases raise the intended error through actual scheduled code generation, and the documented NumPy alternative runs.
The selected test_functions/test_poissoninput suites pass via brian2.test on NumPy, Cython and C++ standalone. I found no blocker in these paths. CUDA/GeNN and a full repository suite were not run.
Closes #1890.
This addresses the three problems of the code generated by
BinomialFunctionfor the inversion algorithm, described in #1890: the Cython template usespinstead ofP = min(p, 1-p)(wrong distribution forp > 0.5, including the defaultapproximate=Truepath whenn*(1-p) <= 5); the constants are written with 15 decimal places, so withapproximate=Falsea smallqn = (1-P)**nis rounded, or written as zero, in which case the generated loop never terminates; andqnunderflows in double precision for largen*P.Changes
brian2/input/binomial.py:Pin the Cython template, as the C++ template does.P,q,qnand the bound) withrepr(float(x)), the shortest literal that converts back to the same double, asNodeRenderer.render_Constantdoes.LOCandSCALEof the normal approximation are unchanged: in that branch both are larger than 1.5, so 15 decimal places already give at least 16 significant digits.qnis not a normal double, pass anavailability_check(the mechanism used byC99Check) to the generated code implementations. It raises aNotImplementedErrorat code generation that explains the cause and suggestsapproximate=Trueor the numpy target; the numpy implementation (np.random.binomial) is not affected. The check is registered for every entry ofBinomialFunction.implementations, which also includes the targets added by brian2cuda and brian2genn (not tested with these packages)._pre_calc_constants, which both packages import, is unchanged; their own templates still write the constants with 15 decimal places.brian2/tests/test_functions.py:test_binomial_distribution(standalone compatible) draws 10 000 samples from each of B(10, 0.8), B(2, 0.9), B(10, 0.2) and B(50, 0.5, approximate=False). It checks that all samples are integers in[0, n], and that the count of each value with an expected count of at least 5, and the sample mean, lie within 6 standard deviations of their expectation. For correct samples, the probability that any of these checks fails is below 4e-6 (union bound over exact binomial tail probabilities); the seed is fixed, so the outcome is deterministic for a given random number generator.test_binomial_inversion_underflow(codegen independent) checks thatget_coderaisesNotImplementedErrorforcythonandcppwithn=2000, p=0.5, that the numpy implementation still samples, and thatn=1000, p=0.5(qn = 9.3e-302) still generates code.The existing tests do not check the distribution:
test_binomialonly checksvar > 0, andtest_repeated_function_dependenciesusesBinomialFunction(10, 0.6), which goes through the affected Cython branch, without assertions on the values.Validation
Cython and C++ standalone were run on Linux (WSL Ubuntu 24.04, gcc 13.3, Python 3.12.3, Cython 3.1.3, numpy 2.5.3) with the Python sources of this branch and the compiled extensions of the 2.10.1 wheel; the numpy target and the codegen-independent tests also ran on Windows (Python 3.12.11, numpy 2.5.3). macOS was not tested.
brian2.test(["cython"], test_codegen_independent=True, test_standalone="cpp_standalone", test_in_parallel=[], additional_args=["-k", "test_functions or test_poissoninput or fundamentalunits"]), wherefundamentalunitsonly keeps the doctest suite non-empty: with this branch, 8 codegen-independent, 41 Cython and 37 C++ standalone tests pass, with no failures. With only the new tests applied to 240e2f0,test_binomial_inversion_underflowfails (DID NOT RAISE),test_binomial_distributionfails with Cython (B(10, 0.8): all 10 000 samples are 9 or 10) and with C++ standalone (B(50, 0.5)), and all other selected tests pass. In this environment the doctest suite fails to collectbrian2/units/unitsafefunctions.py(AttributeError: 'builtin_function_or_method' object has no attribute '__code__'), identically on 240e2f0.-k "binomial or repeated_function_dependencies or fundamentalunits": the 7 selected tests pass with this branch.test_binomial_inversion_underflowfails.8.00088 1.5984592256with Cython on this branch, the same output as the numpy target.seed(20261010), 240e2f0 then this branch (exact value in parentheses):NotImplementedErrorat code generationnaccepted forp = 0.5: mean 510.9848 (511), variance 255.6231 (255.5) with this branchPoissonInputcase, and 4 with Cython, all withp <= 0.5. numpy, Cython and C++ standalone now return identical samples for each of the 12 parameter sets that the Cython and C++ targets accept (all withn*min(p, 1-p) <= 30, where numpy uses the same inversion algorithm)..pre-commit-config.yaml):ruff formatleaves both files unchanged andruff checkreports nothing onbinomial.py(brian2/testsis excluded from the hook).Backward compatibility
p > 0.5, and forapproximate=Falsewhenqnwas too small to be written accurately with 15 decimal places. These results were biased.approximate=Falseandqn < 5e-16, which was written as zero, the generated code did not terminate. It now samples whenqnis a normal double (see B(100, 0.3) and B(1022, 0.5) above); otherwise, code generation for Cython and C++ raises aNotImplementedError.Open question
For the underflow case I chose an explicit error. The alternatives are a fallback to the normal approximation, which silently changes the distribution that was requested, or a port of BTPE (Kachitvichyanukul and Schmeiser, 1988, https://doi.org/10.1145/42372.42381) to the Cython and C++ templates, which adds code to maintain. I can switch to either, or restrict the check to the
cythonandcpptargets, if you prefer.I used an AI assistant (Claude Code) to investigate the bug, write the fix and the tests, run the validation and measurements, and draft this description.