-
Notifications
You must be signed in to change notification settings - Fork 205
Description
Overview
NumPy tracks whether array data is properly aligned for its dtype via the NPY_ARRAY_ALIGNED flag. NumSharp should implement equivalent functionality.
NumPy Behavior
NumPy's NPY_ARRAY_ALIGNED flag (value 0x0100) indicates that data is aligned appropriately for the dtype:
>>> a = np.array([1.0, 2.0, 3.0])
>>> a.flags.aligned
True
>>> a.flags['ALIGNED']
TrueWhen It's Checked
NumPy updates this flag after allocation and when creating views (from ctors.c:940):
PyArray_UpdateFlags((PyArrayObject *)fa, NPY_ARRAY_ALIGNED);Alignment Requirements
int32: 4-byte alignmentint64/double: 8-byte alignmentfloat128/complex128: 16-byte alignment (platform-dependent)
Why It Matters
- SIMD operations — Aligned loads (
Vector256.LoadAligned) are faster than unaligned on some platforms - Interop — Native libraries may require aligned data
- Safety — Some platforms fault on unaligned access (rare in x86 but exists in ARM)
Current NumSharp State
NumSharp has ArrayFlags.ALIGNED defined but it's always set to true:
// Shape.cs - ALIGNED is always set
_flags = (int)ArrayFlags.ALIGNED; // 0x0100This is incorrect for sliced views that may not be aligned.
Proposal
-
Check alignment at allocation —
NativeMemory.Allocreturns platform-aligned memory (typically 16 bytes), so freshly allocated arrays are aligned -
Check alignment for views/slices — When creating a view with offset:
bool IsAligned(IntPtr address, int dtypeSize) => (address.ToInt64() % dtypeSize) == 0;
-
Update flag in Shape construction — When offset is applied, recalculate alignment
-
Expose via NDArray —
nd.flags.alignedproperty
Non-Goals
- Forced alignment — We won't over-allocate to ensure alignment (NumPy doesn't either)
- Aligned allocation API — Separate from this issue (see Modernize unmanaged allocation: Marshal.AllocHGlobal → NativeMemory #528 discussion)
References
- NumPy flag definition:
numpy/_core/include/numpy/ndarraytypes.h - NumPy alignment check:
numpy/_core/src/multiarray/flagsobject.c - Related: Modernize unmanaged allocation: Marshal.AllocHGlobal → NativeMemory #528 (NativeMemory modernization)
- NEP 49: Data Allocation Strategies (custom allocators could provide alignment)