Skip to content

Move errors out of line, unroll stride normalization, extend unsafe_stridedview - #68

Merged
Jutho merged 3 commits into
mainfrom
jh/inline-errors-and-normalization
Nov 25, 2026
Merged

Jutho merged 3 commits into
mainfrom
jh/inline-errors-and-normalization

Conversation

@Jutho

@Jutho Jutho commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

This moves some of the improvements from QuantumKitHub/Strided.jl#104 to StridedViews, so that Strided can build on them, and fixes a few things found along the way.

Changes

  • Errors out of line. All errors are thrown from @noinline helpers (_throw_invalidperm, _throw_reshape_dimensionmismatch, _throw_reshapeexception, and two for ReinterpretArray). Messages that interpolate are LazyStrings, so building the exception and its message does not end up in the code of the callers.
  • Clearer sreshape length errors. sreshape checks the lengths up front, e.g. DimensionMismatch: Cannot reshape a StridedView of size (2, 3, 4) (length 24) to size (5, 5) (length 25), instead of throwing an empty DimensionMismatch() from inside _computereshapestrides. The checks there were redundant after this and are removed; the recursion preserves prod(newsize) == prod(oldsize).
  • Bounds checks when slicing. Slicing a StridedView with ranges and colons (getindex, view, sview) did not check bounds, so e.g. B[1:5, :] on a 3×4 view returned a 5×4 view reaching outside the parent; Strided's kernels then read or write that memory with @inbounds. Slicing now throws a BoundsError. The check can be skipped with @inbounds, which view and sview propagate.
  • Faster permutation check. For N ≤ 64, _isperm records the entries as bits in a 64-bit mask: N entries in 1:N form a permutation if and only if they set all N bits. This is O(N), without branches or allocations, whereas Base.isperm compares all pairs for tuples (O(N²)) and allocates for vectors. For tuples with N ≤ 4, Base.isperm is just as fast and is still used. Tests compare it with Base.isperm exhaustively for N ≤ 5 (with out-of-range entries) and on random cases up to N = 65.
  • @inbounds where the indices are already checked. permutedims reads a.size[p[n]] and a.strides[p[n]] with @inbounds, after _isperm has checked p. _strides(::PermutedDimsArray) does the same with its type parameter perm.
  • unsafe_stridedview(a::StridedView, size = size(a), strides = strides(a), offset = offset(a)). This new method replaces the layout of a view while keeping its element type, parent and operation. The number of dimensions can change, and the strides are used as given, so zero strides (broadcasting, reductions) survive. This is what Strided's _relayout does in Pass arrays to the kernels and reduce the fixed cost for small inputs Strided.jl#104, which can then simply be this method. Internally it replaces the longer form in getindex, permutedims and sreshape.
  • Unrolled _normalizestrides. It is now a scan that carries the extent of the preceding dimension, like _normalizesingletons in Pass arrays to the kernels and reduce the fixed cost for small inputs Strided.jl#104. The results are unchanged: a leading size 1 dimension still gets stride 1, any other size 1 dimension gets stride × size of the preceding dimension, and an array with a zero-size dimension gets contiguous strides. A test compares it with the previous implementation on random inputs.

Relation to _normalizesingletons in QuantumKitHub/Strided.jl#104

Both functions give size 1 dimensions the extent of the preceding dimension as their stride. They differ only for leading size 1 dimensions: here these keep stride 1, while _normalizesingletons gives them the stride of the first dimension with size > 1, so that they fuse. Changing the convention here would change the public strides of e.g. a 1×n row view from (1, m) to (m, m), and break checks such as stride(A, 1) == 1 downstream. The leading-singleton handling therefore stays in Strided, where _fusedims can skip size 1 dimensions altogether.

Timings

Apple M-series, Julia 1.13, minimum times:

main this PR
permutedims N = 6, tuple 8.1 ns 6.0 ns
permutedims N = 6, vector 18.8 ns 6.8 ns
permutedims N = 12, tuple 21.3 ns 10.3 ns
slice B[2:3, :, 1:3, 2] 1.7 ns 2.2 ns (bounds check; 1.7 ns with @inbounds)
_normalizestrides N = 6 2.2 ns 2.0 ns

The version is not bumped; Strided will need the release that includes the new unsafe_stridedview method.

🤖 Generated with Claude Code

Jutho and others added 2 commits November 24, 2026 23:37
…tridedview

- Throw errors from `@noinline` helpers, with `LazyString` messages where
  they interpolate, so that building them does not end up in the callers.
- `permutedims` indexes the size and strides with `@inbounds`, since the
  permutation has been checked; same for `_strides(::PermutedDimsArray)`.
- `unsafe_stridedview(a::StridedView, size, strides, offset)` replaces the
  layout of a view while keeping its element type, parent and operation.
  The strides are used as given, so this also supports zero strides.
- `_normalizestrides` is a fully unrolled scan, with the same results as
  before (checked against the previous implementation in the tests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…utation check

- Slicing a `StridedView` (`getindex` with ranges and colons, `view` and
  `sview`) now checks bounds; previously an out-of-range slice silently
  produced a view outside the parent. The check can be skipped with
  `@inbounds`.
- `sreshape` checks the lengths up front, with a message that gives both
  sizes and lengths, instead of an empty `DimensionMismatch` from inside
  `_computereshapestrides`, whose checks were therefore redundant.
- `_isperm` records the entries in a 64-bit mask for N <= 64, which is
  O(N) without branches or allocations, instead of `Base.isperm`, which
  is O(N^2) for tuples and allocates for vectors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 59.09091% with 27 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/auxiliary.jl 56.41% 17 Missing ⚠️
src/stridedview.jl 62.96% 10 Missing ⚠️
Files with missing lines Coverage Δ
src/stridedview.jl 30.85% <62.96%> (+0.31%) ⬆️
src/auxiliary.jl 68.18% <56.41%> (-1.39%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lkdvos lkdvos left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left some minor style comments, otherwise definitely in favor of having these changes here, rather than in Strided. Definitely some cool implementation improvements as well!

Comment thread src/auxiliary.jl Resolved
Comment thread src/auxiliary.jl
_computereshapestrides(newsize::Dims, oldsize::Tuple{}, strides::Tuple{}) = newsize
function _computereshapestrides(newsize::Dims, oldsize::Dims{N}, strides::Dims{N}) where {N}
d, r = divrem(oldsize[1], newsize[1])
return if r == 0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again just a style comment: the branches all have return statements, so this one is probably not required?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot this one, will change in a next PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Jutho
Jutho merged commit a254e35 into main Nov 25, 2026
14 checks passed
@Jutho
Jutho deleted the jh/inline-errors-and-normalization branch November 25, 2026 08:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants