Repository navigation
feat: implement zero-copy numpy structured array for MSSpectrum (AoS) - #8802
Conversation
|
pretty cool. have you been able to benchmark this? |
|
Yep really cool. I wonder if the detour via byte is necessary but that is extra. |
|
Thanks, @jpfeuffer! I used the byte detour because nanobind::ndarray currently requires a scalar template argument. Since Peak1D is a custom struct, exposing it as a raw byte buffer and applying the structured dtype in Python was the most straightforward way to achieve zero-copy without writing a custom nanobind type-caster for the array elements. It also allows us to explicitly handle the 16-byte alignment of the Peak1D struct. |
|
@timosachsenberg I've benchmarked the new implementation with 1,000,000 peaks on my Mac Mini. Legacy get_peaks(): 0.002736s New get_peaks_struct(): 0.000090s Result: 30.6x speedup. More importantly, the memory overhead is 0 bytes, as it provides a direct view into the existing C++ buffer. |
Summary
This PR introduces get_peaks_struct(), a zero-copy NumPy structured array view for MSSpectrum peaks. This addresses the performance bottleneck of existing peak extraction methods by allowing direct, high-speed access to the underlying C++ memory without data duplication.
Technical Implementation
The implementation maps the C++ memory layout of OpenMS::Peak1D directly to a Python structured array (Array of Structures - AoS):
C++ Binding (bind_spectrum.cpp):
Exposes the std::vector data as a raw 1D uint8_t (byte) nanobind::ndarray.
Employs nb::rv_policy::reference_internal to ensure the MSSpectrum object's lifetime is tied to the NumPy view, preventing memory corruption if the C++ object is deleted while Python still holds the view.
Python Addon (msspectrum.py):
Defines a structured np.dtype that mirrors the Peak1D memory layout.
Memory Alignment: Specifically handles the 16-byte alignment of Peak1D on modern architectures (8 bytes for double mz, 4 bytes for float intensity, and 4 bytes of padding).
Key Advantages
Performance: Drastically reduces latency for data-intensive tasks like plotting and signal processing.
Memory Efficiency: Zero data copying; uses the same memory buffer as the C++ kernel.
In-Place Modification: Modifications made to the NumPy array are instantly reflected in the C++ object, enabling efficient data cleaning and normalization.
Verification Results
Verified on macOS (AppleClang 17) with the following success:
Plaintext
Original C++ Peak 0: mz=123.45, intensity=67.89
Modifying NumPy array...
New C++ Peak 0: mz=123.45, intensity=999.9
RESULT: ZERO-COPY SUCCESS!
Testing
A new unit test test_spectrum_zerocopy.py has been added to cover:
Data Integrity: Validating that m/z and intensity values map correctly.
Zero-Copy Verification: Proving that NumPy updates affect the C++ state.