Skip to content

Fix BinomialFunction sampling in generated code (Cython bias for p > 0.5, exact constants, underflow check) - #1891

Open
AxelNoun wants to merge 2 commits into
brian-team:masterfrom
AxelNoun:fix/binomial-function-sampling
Open

AxelNoun wants to merge 2 commits into
brian-team:masterfrom
AxelNoun:fix/binomial-function-sampling

Conversation

@AxelNoun

Copy link
Copy Markdown
Contributor

Closes #1890.

This addresses the three problems of the code generated by BinomialFunction for the inversion algorithm, described in #1890: the Cython template uses p instead of P = min(p, 1-p) (wrong distribution for p > 0.5, including the default approximate=True path when n*(1-p) <= 5); the constants are written with 15 decimal places, so with approximate=False a small qn = (1-P)**n is rounded, or written as zero, in which case the generated loop never terminates; and qn underflows in double precision for large n*P.

Changes

brian2/input/binomial.py:

  • Use P in the Cython template, as the C++ template does.
  • Write the constants of the inversion algorithm (P, q, qn and the bound) with repr(float(x)), the shortest literal that converts back to the same double, as NodeRenderer.render_Constant does. LOC and SCALE of 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.
  • When qn is not a normal double, pass an availability_check (the mechanism used by C99Check) to the generated code implementations. It raises a NotImplementedError at code generation that explains the cause and suggests approximate=True or the numpy target; the numpy implementation (np.random.binomial) is not affected. The check is registered for every entry of BinomialFunction.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 that get_code raises NotImplementedError for cython and cpp with n=2000, p=0.5, that the numpy implementation still samples, and that n=1000, p=0.5 (qn = 9.3e-302) still generates code.

The existing tests do not check the distribution: test_binomial only checks var > 0, and test_repeated_function_dependencies uses BinomialFunction(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"]), where fundamentalunits only 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_underflow fails (DID NOT RAISE), test_binomial_distribution fails 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 collect brian2/units/unitsafefunctions.py (AttributeError: 'builtin_function_or_method' object has no attribute '__code__'), identically on 240e2f0.
  • float32, same setup, -k "binomial or repeated_function_dependencies or fundamentalunits": the 7 selected tests pass with this branch.
  • Windows, numpy target, same selection as the first item: 55 tests pass with this branch in float64 and in float32, 53 on 240e2f0; with only the new tests, test_binomial_inversion_underflow fails.
  • The reproduction from BinomialFunction: wrong samples with Cython for p > 0.5, and non-terminating generated code with approximate=False #1890 prints 8.00088 1.5984592256 with Cython on this branch, the same output as the numpy target.
  • Sampling, 100 000 draws per case with seed(20261010), 240e2f0 then this branch (exact value in parentheses):
    • Cython, B(10, 0.8): mean 9.1069 then 8.0009 (8), variance 0.0955 then 1.5985 (1.6)
    • Cython, B(2, 0.9): minimum 1 then 0, mean 1.8107 then 1.8003 (1.8)
    • Cython, B(10, 0.6, approximate=False): mean 7.4120 then 6.0024 (6)
    • Cython and C++ standalone, B(50, 0.5, approximate=False): mean 24.2416 then 24.9973 (25), variance 8.6993 then 12.5090 (12.5)
    • Cython and C++ standalone, B(100, 0.3, approximate=False): no termination within 120 s, then mean 29.9940 (30)
    • Cython and C++ standalone, B(2000, 0.5, approximate=False): no termination within 120 s, then NotImplementedError at code generation
    • Cython and C++ standalone, B(1022, 0.5, approximate=False), the largest n accepted for p = 0.5: mean 510.9848 (511), variance 255.6231 (255.5) with this branch
  • With the same seed and target, the samples of this branch are identical to those of 240e2f0 (0 differences out of 100 000) in the 13 compared cases where 240e2f0 was correct: 9 with C++ standalone, including B(1000, 0.001), a typical PoissonInput case, and 4 with Cython, all with p <= 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 with n*min(p, 1-p) <= 30, where numpy uses the same inversion algorithm).
  • ruff 0.14.2 (the version pinned in .pre-commit-config.yaml): ruff format leaves both files unchanged and ruff check reports nothing on binomial.py (brian2/tests is excluded from the hook).

Backward compatibility

  • Results change for Cython simulations that used the inversion branch with p > 0.5, and for approximate=False when qn was too small to be written accurately with 15 decimal places. These results were biased.
  • With approximate=False and qn < 5e-16, which was written as zero, the generated code did not terminate. It now samples when qn is a normal double (see B(100, 0.3) and B(1022, 0.5) above); otherwise, code generation for Cython and C++ raises a NotImplementedError.
  • In the other cases, each constant changes by at most 5e-16, half the rounding step of 15 decimal places, so a sample can only change if the uniform random number falls between the old and the new cumulative probability. No sample changed in the 1.3 million draws compared above.

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 cython and cpp targets, 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.

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]>
@AxelNoun

Copy link
Copy Markdown
Contributor Author

The three failing jobs (Python 3.15, non-standalone, run 38100815108) crash in test_network.py::test_restore_with_random_state with heap corruption under the Cython target. This is unrelated to this PR: the test uses neither BinomialFunction nor any code changed here.

I reproduced the same crash on master (8216baf) by drawing randn values before running the body of the test, so that the Cython randn buffer index is close to its end (20000) at store(): with 19990 prior draws the process aborts with double free or corruption (top), with 19500 the restored run silently differs, with 0 the test passes. In CI the buffer position depends on which tests pytest-xdist scheduled earlier in the same worker, and adding tests in this PR changes that scheduling.

Details, root cause and a proposed fix are in #1893.

@mstimberg

Copy link
Copy Markdown
Member

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.

@AxelNoun

Copy link
Copy Markdown
Contributor Author

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.

@mstimberg

Copy link
Copy Markdown
Member

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)…

@AxelNoun

Copy link
Copy Markdown
Contributor Author

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 test_restore_with_random_state pass now, and so does the rest of the CI. The changes of the PR itself are the same as before (brian2/input/binomial.py and its tests).

@antonsoo antonsoo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

BinomialFunction: wrong samples with Cython for p > 0.5, and non-terminating generated code with approximate=False

3 participants