Download flysim/tests/test_engine.py from nynefold/flysim-malecns: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/datasets/nynefold/flysim-malecns/resolve/main/flysim/tests/test_engine.py
- Command line
-
hf download hf://datasets/nynefold/flysim-malecns/flysim/tests/test_engine.py
-
curl -L -o test_engine.py https://huggingface.co/datasets/nynefold/flysim-malecns/resolve/main/flysim/tests/test_engine.py
18 kB
| """Engine tests on tiny networks: exact dynamics, Brian2 step order, and equality with a | |
| naive implementation written independently of the kernel.""" | |
| import math | |
| import numpy as np | |
| import pytest | |
| from flysim.engine import ( | |
| CpuEngine, | |
| InputSchedule, | |
| ModelParams, | |
| SynapseMatrix, | |
| poisson_schedule, | |
| trial_rng, | |
| ) | |
| from flysim.engine.inputs import merge | |
| P = ModelParams() | |
| # First draw of trial 0 of one condition, pinned so a change to the seeding scheme | |
| # cannot pass silently. | |
| PINNED_DRAW = 1489115183 | |
| def _matrix(edges: list[tuple[int, int, int]], n: int) -> SynapseMatrix: | |
| pre, post, w = zip(*edges, strict=True) if edges else ((), (), ()) | |
| return SynapseMatrix.from_edges(np.array(pre), np.array(post), np.array(w), n) | |
| def _inputs(at: dict[int, list[int]]) -> InputSchedule: | |
| """{neuron: [steps]} -> schedule.""" | |
| pairs = sorted((s, n) for n, steps in at.items() for s in steps) | |
| return InputSchedule( | |
| targets=np.array(sorted(at), dtype=np.int32), | |
| steps=np.array([s for s, _ in pairs], dtype=np.int64), | |
| neurons=np.array([n for _, n in pairs], dtype=np.int32), | |
| ) | |
| KERNELS = ("plain", "skip_rest", "vec") | |
| def _run(matrix, schedule, steps, dtype=np.float32, params=P, skip_rest=False, kernel=None): | |
| eng = CpuEngine(dtype, skip_rest=skip_rest, kernel=kernel) | |
| eng.load(matrix, params) | |
| eng.schedule_inputs(schedule) | |
| eng.advance_to(steps) | |
| return eng | |
| def _spike_steps(eng, neuron): | |
| s, n = eng.spikes_since(0) | |
| return s[n == neuron].tolist() | |
| def test_params_match_the_preregistration(): | |
| assert P.rfc_steps == 22 | |
| assert P.delay_steps == 18 | |
| assert P.w_input == pytest.approx(68.75) | |
| def test_input_spike_fires_next_step_and_reset_discards_same_step_input(): | |
| # Input at every step 0..9: an input fires the neuron in the next step, and the | |
| # input arriving in the spiking step is wiped by the reset (Brian2 order). | |
| eng = _run(_matrix([], 1), _inputs({0: list(range(10))}), 12) | |
| assert _spike_steps(eng, 0) == [1, 3, 5, 7, 9] | |
| def test_delay_and_exact_propagator(): | |
| # 0 spikes at step 1, so its synapse onto 1 lands at step 1 + 18 = 19. | |
| w = 100 | |
| eng = _run(_matrix([(0, 1, w)], 2), _inputs({0: [0]}), 19, dtype=np.float64) | |
| assert eng.g[1] == 0 and eng.v[1] == P.v_0 | |
| eng.advance_to(20) | |
| g0 = P.w_syn * w | |
| assert eng.g[1] == pytest.approx(g0) | |
| # From the end of step 19, neuron 1 follows the closed-form solution. | |
| for k in range(1, 200): | |
| eng.advance_to(20 + k) | |
| t = k * P.dt | |
| u = g0 * P.tau / (P.tau - P.t_mbr) * (math.exp(-t / P.tau) - math.exp(-t / P.t_mbr)) | |
| assert eng.v[1] - P.v_0 == pytest.approx(u, rel=1e-9, abs=1e-12) | |
| assert eng.g[1] == pytest.approx(g0 * math.exp(-t / P.tau), rel=1e-9) | |
| assert _spike_steps(eng, 1) == [] | |
| def test_refractory_period_is_22_steps_and_drops_input(): | |
| # 0 spikes at every odd step; each spike gives 1 a huge kick 18 steps later, at | |
| # odd steps from 19. 1 spikes at 20 and is refractory for steps 21-41; the kicks | |
| # in that window are dropped (Brian2's conditional write), so it is at rest at | |
| # step 42 and only the kick at 43 fires it, at 44. Period: 24 steps. | |
| eng = _run(_matrix([(0, 1, 20000)], 2), _inputs({0: list(range(0, 400, 2))}), 120) | |
| assert _spike_steps(eng, 1) == [20, 44, 68, 92, 116] | |
| def test_input_to_refractory_neuron_is_dropped_not_deferred(): | |
| # 1 spikes at 20 (kick from 0's spike at 1). A second, smaller kick lands at 25, | |
| # inside the refractory window: Brian2 drops it, so 1 stays exactly at rest. | |
| m = _matrix([(0, 1, 20000), (2, 1, 20000)], 3) | |
| eng = _run(m, _inputs({0: [0], 2: [5]}), 60, dtype=np.float64) | |
| assert _spike_steps(eng, 1) == [20] | |
| assert eng.v[1] == P.v_0 and eng.g[1] == 0 | |
| def test_inhibition_and_stimulated_neurons_have_no_refractory_period(): | |
| m = _matrix([(0, 2, 30000), (1, 2, -30000)], 3) | |
| both = _run(m, _inputs({0: [0], 1: [0]}), 100) | |
| only_exc = _run(m, _inputs({0: [0]}), 100) | |
| assert _spike_steps(only_exc, 2) == [20] | |
| assert _spike_steps(both, 2) == [] | |
| # 0 Hz targets still lose their refractory period (Brian2's poi() sets rfc = 0). | |
| eng = _run(m, InputSchedule(np.array([0, 1], np.int32), np.zeros(0, np.int64), | |
| np.zeros(0, np.int32)), 1) | |
| assert eng.rfc.tolist() == [0, 0, P.rfc_steps] | |
| def _naive(matrix: SynapseMatrix, schedule: InputSchedule, steps: int, dtype) -> list[tuple]: | |
| """Straightforward per-step implementation of the same schedule, no shortcuts.""" | |
| f = np.dtype(dtype).type | |
| n = matrix.n | |
| a, b, c = (f(x) for x in P.coefficients()) | |
| v = np.full(n, P.v_0, dtype) | |
| g = np.zeros(n, dtype) | |
| last = np.full(n, -(10**9)) | |
| rfc = np.full(n, P.rfc_steps) | |
| rfc[schedule.targets] = 0 | |
| history: list[np.ndarray] = [] | |
| out = [] | |
| for s in range(steps): | |
| active = (s - last) >= rfc | |
| v_new = f(P.v_0) + (v - f(P.v_0)) * a + g * b | |
| v = np.where(active, v_new, v).astype(dtype) | |
| g = np.where(active, g * c, g).astype(dtype) | |
| spk = np.flatnonzero(active & (v > f(P.v_th))) | |
| last[spk] = s | |
| history.append(spk) | |
| # Brian2's not_refractory after the thresholder: writes to v and g are | |
| # conditional on it. | |
| writable = active.copy() | |
| writable[spk] = False | |
| if s >= P.delay_steps: | |
| for j in history[s - P.delay_steps]: | |
| lo, hi = matrix.indptr[j], matrix.indptr[j + 1] | |
| for post, w in zip(matrix.indices[lo:hi], matrix.weights[lo:hi], strict=True): | |
| if writable[post]: | |
| g[post] += f(P.w_syn) * f(w) | |
| for k in np.flatnonzero(schedule.steps == s): | |
| if writable[schedule.neurons[k]]: | |
| v[schedule.neurons[k]] += f(P.w_input) | |
| v[spk] = f(P.v_rst) | |
| g[spk] = 0 | |
| out += [(s, int(i)) for i in spk] | |
| return out | |
| def test_kernel_matches_naive_implementation(dtype, kernel): | |
| rng = np.random.default_rng(1) | |
| n, n_edges = 300, 6000 | |
| pre = rng.integers(0, n, n_edges) | |
| post = rng.integers(0, n, n_edges) | |
| w = rng.integers(1, 40, n_edges) * np.where(rng.random(n_edges) < 0.25, -1, 1) | |
| m = SynapseMatrix.from_edges(pre, post, w, n) | |
| sched = poisson_schedule(rng, np.arange(20), 150.0, 0, 1500, P.dt) | |
| eng = _run(m, sched, 1500, dtype=dtype, kernel=kernel) | |
| s, i = eng.spikes_since(0) | |
| ours = list(zip(s.tolist(), i.tolist(), strict=True)) | |
| assert len(ours) > 1000 # the network is actually active | |
| assert ours == _naive(m, sched, 1500, dtype) | |
| def test_chunked_advance_and_log_growth_change_nothing(kernel): | |
| rng = np.random.default_rng(2) | |
| n = 200 | |
| m = SynapseMatrix.from_edges(rng.integers(0, n, 4000), rng.integers(0, n, 4000), | |
| rng.integers(1, 30, 4000), n) | |
| sched = poisson_schedule(rng, np.arange(15), 200.0, 0, 3000, P.dt) | |
| whole = _run(m, sched, 3000) # plain kernel, in one go | |
| chunked = CpuEngine(kernel=kernel) | |
| chunked.load(m, P) | |
| chunked._log = np.empty(n + 1, np.int32) # force repeated growth | |
| chunked.schedule_inputs(sched) | |
| seen_s, seen_n = [], [] | |
| for stop in range(100, 3001, 100): # 10 ms chunks, as the live runs step | |
| before = chunked.step | |
| chunked.advance_to(stop) | |
| s, i = chunked.spikes_since(before) | |
| seen_s.append(s) | |
| seen_n.append(i) | |
| ws, wn = whole.spikes_since(0) | |
| np.testing.assert_array_equal(np.concatenate(seen_s), ws) | |
| np.testing.assert_array_equal(np.concatenate(seen_n), wn) | |
| np.testing.assert_array_equal(chunked.snapshot().v, whole.snapshot().v) | |
| def test_reset_restores_rest_and_inputs_cannot_go_back_in_time(): | |
| eng = _run(_matrix([(0, 1, 5)], 2), _inputs({0: [0, 5]}), 50) | |
| with pytest.raises(ValueError): | |
| eng.schedule_inputs(_inputs({0: [10]})) | |
| eng.reset() | |
| assert eng.step == 0 and np.all(eng.v == P.v_0) and np.all(eng.g == 0) | |
| assert eng.spikes_since(0)[0].size == 0 | |
| assert eng.rfc.tolist() == [P.rfc_steps] * 2 | |
| def test_seeding_is_stable_and_keyed(): | |
| a = trial_rng("E1", "E1/sugar/100Hz", 3).random(4) | |
| b = trial_rng("E1", "E1/sugar/100Hz", 3).random(4) | |
| np.testing.assert_array_equal(a, b) | |
| assert not np.array_equal(a, trial_rng("E1", "E1/sugar/100Hz", 4).random(4)) | |
| assert not np.array_equal(a, trial_rng("E1", "E1/sugar/50Hz", 3).random(4)) | |
| assert trial_rng("E1", "E1/sugar/100Hz", 0).integers(0, 2**31) == PINNED_DRAW | |
| def test_named_seed_namespaces_keep_the_recorded_seeds(): | |
| """The public names of the chain tests and the live worker map to the namespace | |
| strings the recorded runs were seeded with (draws pinned before the renaming).""" | |
| assert trial_rng("chain-tests", "LC9/100Hz", 0).integers(0, 2**31) == 1436011335 | |
| assert trial_rng("chain-tests", "control-55/03", 7).integers(0, 2**31) == 707105761 | |
| assert trial_rng("live", "LC4/35Hz", 12).integers(0, 2**31) == 249271961 | |
| def test_poisson_rate_and_schedule_merge(): | |
| rng = trial_rng("test", "rate", 0) | |
| s = poisson_schedule(rng, np.arange(50), 100.0, 0, 10000, P.dt) | |
| rate = len(s.steps) / 50 / 1.0 | |
| assert 90 < rate < 110 | |
| s2 = poisson_schedule(rng, np.array([60, 61]), 0.0, 0, 10000, P.dt) | |
| assert len(s2.steps) == 0 | |
| merged = merge(s, s2) | |
| assert set(merged.targets.tolist()) == set(range(50)) | {60, 61} | |
| assert np.all(np.diff(merged.steps) >= 0) | |
| def _sparse_net(seed: int, n: int = 3000, n_edges: int = 30000) -> SynapseMatrix: | |
| """Mostly quiet network: activity spreads from a few stimulated neurons, as in the | |
| connectome, so neurons leave rest, return to it and leave it again.""" | |
| rng = np.random.default_rng(seed) | |
| pre, post = rng.integers(0, n, n_edges), rng.integers(0, n, n_edges) | |
| w = rng.integers(1, 60, n_edges) * np.where(rng.random(n_edges) < 0.3, -1, 1) | |
| return SynapseMatrix.from_edges(pre, post, w, n) | |
| def test_skip_rest_is_bit_identical_to_the_plain_kernel(seed): | |
| m = _sparse_net(seed) | |
| rng = np.random.default_rng(seed) | |
| sched = poisson_schedule(rng, rng.choice(m.n, 40, replace=False), 120.0, 0, 3000, P.dt) | |
| plain = _run(m, sched, 6000) | |
| fast = CpuEngine(kernel="skip_rest") | |
| fast.dense_div = 1 # stay sparse: this test checks the list path | |
| fast.load(m, P) | |
| fast.schedule_inputs(sched) | |
| for stop in (1, 17, 18, 100, 2999, 3000, 3001, 4500, 6000): # odd chunk edges | |
| fast.advance_to(stop) | |
| ps, pn = plain.spikes_since(0) | |
| fs, fn = fast.spikes_since(0) | |
| assert len(ps) > 1000 | |
| np.testing.assert_array_equal(fs, ps) | |
| np.testing.assert_array_equal(fn, pn) | |
| # the whole state, bit for bit (v and g compared as raw bits, NaN-proof) | |
| a, b = plain.snapshot(), fast.snapshot() | |
| np.testing.assert_array_equal(a.v.view(np.int32), b.v.view(np.int32)) | |
| np.testing.assert_array_equal(a.g.view(np.int32), b.g.view(np.int32)) | |
| np.testing.assert_array_equal(a.last_spike, b.last_spike) | |
| # list invariant (sparse mode): every neuron off rest is listed, the list is sorted | |
| assert not fast._dense | |
| off = np.flatnonzero((fast.v != np.float32(P.v_0)) | (fast.g != 0)) | |
| listed = np.union1d(fast._act[fast._cur, : fast._n_act], fast._new[: fast._n_new]) | |
| assert np.isin(off, listed).all() | |
| cur = fast._act[fast._cur, : fast._n_act] | |
| assert np.all(np.diff(cur) > 0) | |
| assert 0 < fast._n_act < m.n # it actually skips neurons | |
| def test_skip_rest_survives_reset(): | |
| m = _sparse_net(6) | |
| rng = np.random.default_rng(6) | |
| sched = poisson_schedule(rng, np.arange(30), 150.0, 0, 1000, P.dt) | |
| eng = CpuEngine(kernel="skip_rest") | |
| eng.load(m, P) | |
| eng.schedule_inputs(sched) | |
| eng.advance_to(1500) | |
| first = eng.spikes_since(0) | |
| eng.reset() | |
| assert eng._n_act == 0 and eng._n_new == 0 and not eng._flag.any() | |
| eng.schedule_inputs(sched) | |
| eng.advance_to(1500) | |
| for x, y in zip(first, eng.spikes_since(0), strict=True): | |
| np.testing.assert_array_equal(x, y) | |
| def test_skip_rest_dense_switch_is_bit_identical(dense_div): | |
| m = _sparse_net(7) | |
| rng = np.random.default_rng(7) | |
| sched = poisson_schedule(rng, rng.choice(m.n, 60, replace=False), 150.0, 0, 3000, P.dt) | |
| plain = _run(m, sched, 6000) | |
| fast = CpuEngine(kernel="skip_rest") | |
| fast.dense_div = dense_div | |
| fast.load(m, P) | |
| fast.schedule_inputs(sched) | |
| for stop in (250, 2000, 6000): | |
| fast.advance_to(stop) | |
| for x, y in zip(plain.spikes_since(0), fast.spikes_since(0), strict=True): | |
| np.testing.assert_array_equal(x, y) | |
| np.testing.assert_array_equal(plain.v.view(np.int32), fast.v.view(np.int32)) | |
| np.testing.assert_array_equal(plain.g.view(np.int32), fast.g.view(np.int32)) | |
| if dense_div in (1, 10**6): # 1 never switches; 10**6 switches at the first input | |
| assert fast._dense == (dense_div == 10**6) | |
| def _bits_equal(a: CpuEngine, b: CpuEngine) -> None: | |
| """Spikes and the whole state, bit for bit (v and g as raw bits, NaN-proof).""" | |
| for x, y in zip(a.spikes_since(0), b.spikes_since(0), strict=True): | |
| np.testing.assert_array_equal(x, y) | |
| bits = np.int32 if a.dtype == np.float32 else np.int64 | |
| np.testing.assert_array_equal(a.v.view(bits), b.v.view(bits)) | |
| np.testing.assert_array_equal(a.g.view(bits), b.g.view(bits)) | |
| np.testing.assert_array_equal(a.last, b.last) | |
| def _until_matches(eng: CpuEngine) -> None: | |
| """vec's refractory state is last + max(rfc, 1) for every neuron that has spiked.""" | |
| spiked = eng.last > -(2**40) | |
| np.testing.assert_array_equal(eng._until[spiked], | |
| eng.last[spiked] + np.maximum(eng.rfc[spiked], 1)) | |
| assert np.all(eng._until[~spiked] < -(2**29)) | |
| def test_kernel_choice(): | |
| assert CpuEngine().kernel == "vec" and CpuEngine(skip_rest=True).kernel == "vec" | |
| assert CpuEngine(kernel="skip_rest").kernel == "skip_rest" | |
| assert CpuEngine(skip_rest=False).kernel == "plain" | |
| assert CpuEngine(kernel="vec").kernel == "vec" | |
| with pytest.raises(ValueError): | |
| CpuEngine(kernel="fast") | |
| def test_vec_is_bit_identical_to_the_plain_kernel(seed, dense_div, dtype): | |
| # dense_div 1 never leaves the list path; 10**6 sweeps densely from the first input | |
| m = _sparse_net(seed) | |
| rng = np.random.default_rng(seed) | |
| sched = poisson_schedule(rng, rng.choice(m.n, 60, replace=False), 150.0, 0, 3000, P.dt) | |
| plain = _run(m, sched, 6000, dtype=dtype) | |
| fast = CpuEngine(dtype, kernel="vec") | |
| fast.dense_div = dense_div | |
| fast.load(m, P) | |
| fast._log = np.empty(m.n + 1, np.int32) # force repeated log growth | |
| fast.schedule_inputs(sched) | |
| for stop in (1, 17, 18, 100, 511, 2999, 3000, 3001, 4500, 6000): # odd chunk edges | |
| fast.advance_to(stop) | |
| assert len(plain.spikes_since(0)[0]) > 1000 | |
| _bits_equal(plain, fast) | |
| _until_matches(fast) | |
| if dense_div in (1, 10**6): | |
| assert fast._dense == (dense_div == 10**6) | |
| def test_vec_dense_sweep_with_blocks_and_ragged_tail(): | |
| # more neurons than one block, not a multiple of it, dense from the start; a long | |
| # quiet tail lets g decay into the subnormal range, where it gets stuck: m * c | |
| # rounds back to m for subnormal mantissas m <= 25, so g never reaches 0 | |
| from flysim.engine.kernel import VEC_BLOCK | |
| n = 3 * VEC_BLOCK + 77 | |
| m = _sparse_net(8, n=n, n_edges=12 * n) | |
| rng = np.random.default_rng(8) | |
| sched = poisson_schedule(rng, rng.choice(n, 40, replace=False), 150.0, 0, 1500, P.dt) | |
| plain = CpuEngine(kernel="plain") | |
| fast = CpuEngine(kernel="vec") | |
| fast.dense_div = 10**6 | |
| subnormal = 0 | |
| for eng in (plain, fast): | |
| eng.load(m, P) | |
| eng.schedule_inputs(sched) | |
| for stop in range(500, 12001, 500): | |
| plain.advance_to(stop) | |
| fast.advance_to(stop) | |
| _bits_equal(plain, fast) | |
| gb = plain.g.view(np.int32) & 0x7FFFFFFF | |
| subnormal += int(np.sum((gb > 0) & (gb < 0x00800000))) | |
| assert fast._dense and subnormal > 0 | |
| gb = plain.g.view(np.int32) & 0x7FFFFFFF | |
| assert np.all(gb < 0x00800000) and np.any(gb > 0) # every g is 0 or subnormal | |
| def test_rfc_change_after_a_spike_is_honoured(kernel): | |
| # 1 spikes at 20 (kick from 0's spike at 1), so it is refractory for 22 steps. At | |
| # step 22 it becomes a stimulus target, so rfc drops to 0 and the inputs at 25 and | |
| # later count at once, as in the plain kernel (rfc is read when it is used). | |
| m = _matrix([(0, 1, 20000)], 2) | |
| for k in ("plain", kernel): | |
| eng = CpuEngine(np.float64, kernel=k) | |
| eng.load(m, P) | |
| eng.schedule_inputs(_inputs({0: [0]})) | |
| eng.advance_to(22) | |
| eng.schedule_inputs(_inputs({1: [25, 26, 30]})) | |
| eng.advance_to(60) | |
| if k == "plain": | |
| plain = eng | |
| assert _spike_steps(plain, 1) == [20, 26, 31] | |
| _bits_equal(plain, eng) | |
| if kernel == "vec": | |
| _until_matches(eng) | |
| def test_vec_survives_reset(): | |
| m = _sparse_net(6) | |
| rng = np.random.default_rng(6) | |
| sched = poisson_schedule(rng, np.arange(30), 150.0, 0, 1000, P.dt) | |
| eng = CpuEngine(kernel="vec") | |
| eng.dense_div = 10**6 | |
| eng.load(m, P) | |
| eng.schedule_inputs(sched) | |
| eng.advance_to(1500) | |
| first = eng.spikes_since(0) | |
| assert eng._dense | |
| eng.reset() | |
| assert not eng._dense and eng._n_act == 0 and not eng._flag.any() | |
| assert np.all(eng._until < -(2**29)) and eng.rfc.tolist() == [P.rfc_steps] * m.n | |
| eng.schedule_inputs(sched) | |
| eng.advance_to(1500) | |
| for x, y in zip(first, eng.spikes_since(0), strict=True): | |
| np.testing.assert_array_equal(x, y) | |