Skip to content

Support NPY_ARRAY_ALIGNED flag for dtype alignment tracking #581

@Nucs

Description

@Nucs

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']
True

When 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 alignment
  • int64/double: 8-byte alignment
  • float128/complex128: 16-byte alignment (platform-dependent)

Why It Matters

  1. SIMD operations — Aligned loads (Vector256.LoadAligned) are faster than unaligned on some platforms
  2. Interop — Native libraries may require aligned data
  3. 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;  // 0x0100

This is incorrect for sliced views that may not be aligned.

Proposal

  1. Check alignment at allocationNativeMemory.Alloc returns platform-aligned memory (typically 16 bytes), so freshly allocated arrays are aligned

  2. Check alignment for views/slices — When creating a view with offset:

    bool IsAligned(IntPtr address, int dtypeSize) =>
        (address.ToInt64() % dtypeSize) == 0;
  3. Update flag in Shape construction — When offset is applied, recalculate alignment

  4. Expose via NDArraynd.flags.aligned property

Non-Goals

References

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions