Skip to content

Faster exact median for common_reference - #4854

Open
galenlynch wants to merge 10 commits into
SpikeInterface:mainfrom
galenlynch:perf/cmr-row-median
Open

galenlynch wants to merge 10 commits into
SpikeInterface:mainfrom
galenlynch:perf/cmr-row-median

Conversation

@galenlynch

@galenlynch galenlynch commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

common_reference(operator="median") calls np.median(traces, axis=1) on every chunk. np.median partitions each row with branches that depend on the data, and on 384 channels it mispredicts about one branch per value.

This PR adds row_median, a numba kernel that returns exactly np.median's values and dtype:

  • int16 with at least 4 channels, which is what common_reference gets in the default chain: each row is counted into a histogram around the previous row's median. Neighbouring samples have nearly the same median, so most rows take one pass; a row whose median falls outside the histogram is sorted instead.
  • float32 with at least 64 channels: counting passes narrow in on the middle values, and the few left are sorted. Rows holding NaN or inf take an exact path.

Other inputs, and installs without numba, keep np.median.

Speed. 1 s of 384 highpassed channels, column-major as filter steps return them, one thread, i9-12900K:

main this PR
median, int16 72 ms 11 ms
median, float32 101 ms 38 ms
common_reference, int16 94 ms 33 ms
common_reference, float32 106 ms 43 ms
common_reference(reference="local"), int16 640 ms 379 ms
row_median

The median of 1 s of highpassed traces against the number of channels in each median, as reference="local" and groups produce.

Mispredicts per row drop from 354 to 4 for int16, and from 392 to 47 for float32, measured with hardware counters.

One case is slower: float32 holding only whole numbers, such as unfiltered int16 cast to float32, takes 108 ms against 97.

Tests. row_median equals np.median on int8 to uint16 and float32, including ties, saturated channels, a median jumping outside the histogram, column-major and non-contiguous input, and NaN and inf. common_reference output is unchanged for int16 and float32.

Update: float rows now use np.sort, as #4836 does, and the float32 kernel described below has been removed (see this comment). The int16 kernel is unchanged.

np.median partitions each row with data-dependent branches and mispredicts
about once per value. row_median gives the same values and dtype: int16 rows
of 4 or more channels are counted into a histogram around the previous row's
median, and float32 rows of 64 or more channels are narrowed with branchless
counting passes. Other inputs, and installs without numba, keep np.median.
On 1 s of 384 column-major channels, as filter steps return them, the median
drops from 72 to 11 ms for int16 and from 101 to 38 ms for float32.
@alejoe91 alejoe91 added preprocessing Related to preprocessing module performance Performance issues/improvements labels Oct 13, 2026
@JoeZiminski

Copy link
Copy Markdown
Contributor

Thanks @galenlynch this is very cool, however my 2 cents is as a library I do not think we should be in the business of rewriting core mathematical functions. This also applies to #4836. In general it makes the library harder to maintain and the risk of bugs greatly increases. Unless the speed up is absolutely mindboggling it is safer to rely on these standard library implementations wherever we can.

The histogram and interval-narrowing kernels now state their invariants,
early exits and fallbacks, so a reader can check them without
reconstructing the algorithm. No code changes.
np.sort vectorises 32- and 64-bit sorts, and on the default chain's
float32 output it beats the counting kernel (29 vs 39 ms per 1 s of
384 channels) and np.median (100 ms). This is the approach of SpikeInterface#4836.
It also covers float64 and needs no numba. The int16 histogram
kernel stays, since np.sort is 2.6x slower than np.median there.
@galenlynch

galenlynch commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews, @JoeZiminski and @chrishalcrow, both are fair points. I've cut this PR down to one integer kernel, a 55-line numba function with comments, about the size of the correlogram kernels in postprocessing/correlograms.py. For floats this PR now uses #4836's approach, which is faster than what I had. The kernel that remains makes the median 5.9 times faster on int16, the default dtype. Once the other steps of common preprocessing chains are fast, that matters. With #4563 and #4856, a chain of phase_shift → bandpass_filter → common_reference, each with its default parameters, takes 7.9 minutes of one core per hour of neuropixels 2.0 recording, and 11.0 minutes with np.median.

preprocessing_stream_hours

One core, 384 channels at 30 kHz, int16 data in RAM. "main" is upstream main; #4859 is the fused prototype.

Here is the timing of the median alone, on what common_reference receives from phase_shift → bandpass_filter: 1 s of 384 channels, on one thread of an i9-12900K.

median of each row float32 int16
np.median (main) 100 ms 70 ms
np.sort, as in #4836 29 ms 182 ms
counting kernels, as first posted here 39 ms 12 ms

The common_reference step as a whole, which also subtracts the median and casts back to int16, goes from 91 to 33 ms, 2.8 times faster, as in the figure.

For float32, np.sort beats my counting kernel, so this PR now sorts float rows, and my float kernel, which was most of the code, is gone.

For int16, np.sort is 2.6 times slower than np.median, because numpy vectorises 16-bit sorts only on CPUs with AVX-512 (not mine). The kernel I've kept is much faster on ephys data, but not general enough to contribute to numpy. It counts each value into a histogram centred on the previous time point's median, which avoids the hard-to-predict comparisons in np.median's partition. That suits filtered traces, whose median moves little between samples. Where the median jumps, rows fall back to sorting and are slower than np.median.

The tests compare it with np.median value for value on every integer dtype it accepts, from 1 to 384 channels, including the full value range, ties, saturated channels, a median jumping outside the histogram, and reversed, strided and column-major input. Like the correlograms, it falls back to numpy, here np.median, when numba isn't installed.

I think this one kernel earns its place, since it is small, exact, on the default path, and 5.9 times faster than np.median, but you know the maintenance costs better than I do. If you'd rather not carry its maintenance then I'll close this and leave float32 to #4836.

alejoe91 and others added 3 commits October 14, 2026 14:46
Sorting float rows for the median, in beec896, follows @JESUSROYETH's
approach in SpikeInterface#4836.

Co-authored-by: JESUSROYETH <[email protected]>
numba does not accept non-native byte order, so the integer kernel raised on big-endian int16 or uint16 traces. Those now use np.median, as other unsupported dtypes already did.
@alejoe91

Copy link
Copy Markdown
Member

Confirmed: common_reference with the median is 55% faster on int16 (384 ch: 86.4 ms to 39.3 ms per 1 s chunk; author: 94 to 33 ms) and 62% faster on float32 (116.8 to 44.9 ms; author: 106 to 43 ms), the local median is 65% faster (1.37 s to 0.48 s per chunk; author: 640 to 379 ms), and outputs are identical to main (8 of 8 arrays). The int16 histogram kernel is what makes int16 faster on this Zen 3 CPU, where a plain np.sort on int16 is slower than np.median (seen when testing #4836), so the kernel for int16 and np.sort for float looks right; the 32-channel int16 case also uses the kernel (_MIN_INT_CHANNELS = 4) and is 71% faster. Not covered: NaN/inf rows, saturated channels and 3-channel inputs (in the PR's unit tests, not in this case); the numba kernel lines are invisible to coverage.

A/B vs main: PR #4854 head 9783cea764 vs its base on main 27606fe0c0, 3 alternating run(s) per side, values are medians (the base is 4 commits behind current main).

main this PR change
run() wall time, whole timed call (s) 53.32 20.2 -62.1%
peak memory, PSS of process tree (GB) 2.96 2.92 -1.3%
float32_384ch_F, time (s) 0.1168 0.04485 -61.6%
int16_32ch_F, time (s) 0.007917 0.002282 -71.2%
int16_384ch_F, time (s) 0.08635 0.03932 -54.5%
int16_384ch_local, time (s) 1.37 0.4839 -64.7%

Timed run() and setup: common_reference (global median, plus local median) get_traces over 1 s chunks of an in-memory recording of highpass-filtered (300 Hz, int16 output) NP1 traces; 20 s (4 s for the local median), 384 ch, 30 kHz. Filtering and the raw read happen in untimed setup, so the timed work is the CMR only. Variants (all column-major, as filters return it): int16 and float32 on 384 ch, int16 on 32 channels (below the PR's kernel threshold, regression check) and int16 local median. The *, time (s) rows are per 1 s chunk. Each variant: 1 warm-up (numba JIT), median of 5 inner repeats over all chunks (*, time (s) rows); the run() wall-time row sums everything, peak PSS includes setup.

Outputs identical to main for all 8 compared arrays (floats within rtol=1e-05, atol=1e-06).

System
  • CPU: AMD Ryzen 9 5950X 16-Core Processor, 32 logical cores, 63 GiB RAM
  • OS: Linux-6.8.0-149-generic-x86_64-with-glibc2.39, Python 3.13.2
  • numpy 2.5.5, scipy 1.18.1, numba 0.67.0, zarr 3.4.2, numcodecs 0.17.1, probeinterface 0.5.1, neo 0.15.0.dev0, torch 2.14.0

@JoeZiminski JoeZiminski 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.

Thanks @galenlynch for this, the cut down version is more accessible. I am less averse to this in general now, I guess we live in a new age!

Similar to #4855 I think we should start centralising all of these implementations into a algorithms module with submodules numpy and numba (this is the request changes for this PR). Each implementation is then easy accessible and its simple to see where and how is directly tested against the reference implementation across a range of inputs. Ideally each testing module would include in its description the dtype, numerical ranges and distributions of the data the algorithm is tested over. It will also makes it easier to reuse this functions and swap them out for even faster versions in future.

I threw GTP6 Astra (medium) at this over a range of numerical inputs and it found one edge-case error (below), which is so edge case I'll leave it up to you if you want to fix it, I'm not sure if it will slow things down.

image

…edian

Averaging the middle value with itself overflowed to inf near the float
maximum, where np.median returns the value.
@galenlynch

Copy link
Copy Markdown
Contributor Author

Thanks @JoeZiminski, and good catch on the overflow. With an odd channel count, row_median now returns the middle value instead of averaging it with itself, and the test covers both odd and even counts. With an even count np.median overflows too, so the two now agree either way.

I'm happy to start an algorithms module, with each implementation tested against a reference. I'd rather group it by algorithm rather than by backend, though: algorithms/median.py would hold the np.median reference, the numba kernel and the rules choosing between them (dtype, channel count). If the module were instead split by backend, then the kernel and its reference would sit in different directories, and the selection rules would belong to neither.

The reference depends on the kernel. The median and the convolution compute the same function as numpy and scipy, so they're tested against them to rounding precision. The FIR phase shift approximates a fractional delay differently from the FFT shift on purpose, so its test would be an accuracy spec, such as 34 ppm mean error over the NP 2.0 passband. Your drift concern applies to kernels like that one, so the end-to-end tests matter most for them.

I'd move the median there in this PR, and the phase shift and NNLS in a follow-up. Kernels tied to SI structures, like the amplitude-scaling Gram kernel, would stay with their callers. @alejoe91, does that layout work for you?

@JoeZiminski

Copy link
Copy Markdown
Contributor

Thanks @galenlynch! All sounds good to me agree on the layout (will wait for @alejoe91on the final call on this suggestion). Good point about the tolerance on agreement with reference implementations, Agree 's okay to test to within some tolerance even if they do not match exactly, its nice that it's explicit and permits easy benchmarking future implementations. Thanks!

@galenlynch

Copy link
Copy Markdown
Contributor Author

Thanks! I've written this up in #4963 so @alejoe91 can decide it in one place, since it also covers the overlap-save from #4855 and the NNLS. One change from above: I suggested core.numerics instead of algorithms, since most entries, like the median, are operations rather than algorithms.

@samuelgarcia

Copy link
Copy Markdown
Member

I was out for a while.
My feed back of this, I have controversial feeling:

  • I am in favor in improving the speed for spikeinterface any time we can
  • I am affraid that with AI we could be tempted to rewrite any upstream library for efficiency (scipy, numpy, sklearn)

Here we are trying to compete with numpy itself.
For the the float side, it is hard to understand why a simple np.sort could be faster than a np.partition. The partition way should be faster, clearly here the axis handling in numyp must slow down the speed. Why not contributing directly in numpy repo.
For the int side, if I understand correctly the trick is that we do an histogram because our data is already centered, this lloks smart but why not having the same trick for float ?

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

Labels

performance Performance issues/improvements preprocessing Related to preprocessing module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants