Skip to content

Commit a254e35

Browse files
Juthoclaude
andauthored
Move errors out of line, unroll stride normalization, extend unsafe_stridedview (#68)
* Move errors out of line, unroll stride normalization, extend unsafe_stridedview - 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> * Check slicing bounds, explain sreshape length mismatches, faster permutation 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> * Fold the tuple and vector permutation checks into `_isperm` Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 123036e commit a254e35

3 files changed

Lines changed: 222 additions & 58 deletions

File tree

‎src/auxiliary.jl‎

Lines changed: 70 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,53 @@
11
# Auxiliary routines
22
#---------------------
3+
# Errors are thrown from `@noinline` functions, so that building the exception and its
4+
# message does not end up in the code of the (often inlined) callers. Messages with
5+
# interpolation are `LazyString`s, so that they are only built when they are shown.
6+
@noinline function _throw_reshape_dimensionmismatch(oldsize::Dims, newsize::Dims)
7+
throw(DimensionMismatch(lazy"Cannot reshape a StridedView of size $oldsize (length $(prod(oldsize))) to size $newsize (length $(prod(newsize)))"))
8+
end
9+
@noinline function _throw_invalidperm(N::Int, p)
10+
throw(ArgumentError(lazy"Invalid permutation of length $N: $p"))
11+
end
12+
@noinline function _throw_reinterpret_eltype(S::Type, T::Type)
13+
throw(ArgumentError(lazy"Cannot create StridedView with reinterpretation from $S to $T"))
14+
end
15+
@noinline function _throw_reinterpret_op()
16+
throw(ArgumentError("Cannot create StridedView with reinterpretation from view with non-identity operation"))
17+
end
18+
319
# Check whether p is a valid permutation of length N
4-
_isperm(N::Integer, p::AbstractVector) = (length(p) == N && isperm(p))
5-
_isperm(N::Integer, p::NTuple{M, Integer}) where {M} = (M == N && isperm(p))
20+
# For N <= 64, the entries are recorded as bits in a mask: N entries that are all in `1:N` form
21+
# a permutation if and only if together they set all N bits. This takes O(N) operations
22+
# without branches or allocations, whereas `Base.isperm` compares all pairs for tuples
23+
# (O(N^2)) and allocates for vectors. For N <= 4, `Base.isperm` is just as fast for tuples.
24+
@inline function _isperm(N::Integer, p::NTuple{M, Integer}) where {M}
25+
M == N || return false
26+
# `M` is known at compile time, so only one of the branches remains
27+
(M <= 4 || M > 64) && return isperm(p)
28+
return _isperm_mask(p, M)
29+
end
30+
function _isperm(N::Integer, p::AbstractVector{<:Integer})
31+
length(p) == N || return false
32+
N > 64 && return isperm(p)
33+
return _isperm_mask(p, Int(N))
34+
end
35+
_isperm(N::Integer, p::AbstractVector) = length(p) == N && isperm(p)
636
_isperm(N::Integer, p) = false
737

38+
@inline function _isperm_mask(p, N::Int)
39+
used = zero(UInt64)
40+
valid = true
41+
for x in p
42+
valid &= (1 <= x <= N)
43+
# `% Int` and `& 63` keep the shift well defined (and branch free) for invalid entries,
44+
# which are rejected through `valid`
45+
used |= one(UInt64) << (((x % Int) - 1) & 63)
46+
end
47+
full = N == 64 ? typemax(UInt64) : (one(UInt64) << N) - one(UInt64)
48+
return valid & (used == full)
49+
end
50+
851
# Compute the memory index given a list of cartesian indices and corresponding strides
952
@inline function _computeind(indices::NTuple{N, Int}, strides::NTuple{N, Int}) where {N}
1053
return (indices[1] - 1) * strides[1] + _computeind(tail(indices), tail(strides))
@@ -30,20 +73,25 @@ function _simplifydims(size::Dims{N}, strides::Dims{N}) where {N}
3073
end
3174

3275
# 'Normalize' the strides of a `StridedView`, i.e. strides associated with dimensions of
33-
# size 1 have no intrinsic meaning and can be changed arbitrarily. If one of the dimensions
34-
# has size zero, then the whole array has length zero, and all strides are ambiguous. All
35-
# ambiguous strides are set to 1.
36-
function _normalizestrides(size::Dims{N}, strides::Dims{N}) where {N}
37-
for i in 1:N
38-
if size[i] == 1
39-
newstride = i == 1 ? 1 : strides[i - 1] * size[i - 1]
40-
strides = Base.setindex(strides, newstride, i)
41-
elseif size[i] == 0
42-
return (1, Base.front(cumprod(size))...)
43-
end
44-
end
45-
return strides
76+
# size 1 have no intrinsic meaning and can be changed arbitrarily. They are set to the extent
77+
# of the preceding dimension (stride times size), or 1 for leading dimensions of size 1, such
78+
# that a size 1 dimension never prevents fusing its neighbours. If one of the dimensions has
79+
# size zero, then the whole array has length zero, and all strides are ambiguous; they are
80+
# set to those of a contiguous array.
81+
# The strides are computed with a fully unrolled scan that carries the extent of the
82+
# preceding dimension.
83+
@inline function _normalizestrides(size::Dims{N}, strides::Dims{N}) where {N}
84+
any(iszero, size) && return _contiguousstrides(size)
85+
return first(_normalizestrides_scan(size, strides, 1))
4686
end
87+
_normalizestrides_scan(::Tuple{}, ::Tuple{}, carry::Int) = ((), carry)
88+
@inline function _normalizestrides_scan(size::Dims, strides::Dims, carry::Int)
89+
s = ifelse(size[1] == 1, carry, strides[1])
90+
rest, _ = _normalizestrides_scan(tail(size), tail(strides), size[1] * s)
91+
return (s, rest...), carry
92+
end
93+
_contiguousstrides(::Tuple{}) = ()
94+
@inline _contiguousstrides(size::Dims) = (1, Base.front(cumprod(size))...)
4795

4896
# 'Normalize' the layout of a DenseArray, in order to reduce the number of required
4997
# specializations in functions. The offset is adjusted to the start of `A` in the
@@ -107,19 +155,13 @@ _computeviewoffset(::Tuple{}, ::Tuple{}) = 0
107155
# Auxiliary methods for `sreshape`
108156
#----------------------------------
109157
# Compute the new strides of a (strided) reshape given the original strides and new and
110-
# original sizes
158+
# original sizes, or `nothing` if the reshape is not possible without copying.
159+
# Callers guarantee that `prod(newsize) == prod(oldsize)`, which is preserved in the
160+
# recursion: once one of the sizes is exhausted, the remaining dimensions of the other one
161+
# all have size 1.
111162
_computereshapestrides(newsize::Tuple{}, oldsize::Tuple{}, strides::Tuple{}) = strides
112-
function _computereshapestrides(
113-
newsize::Tuple{}, oldsize::Dims{N},
114-
strides::Dims{N}
115-
) where {N}
116-
all(isequal(1), oldsize) || throw(DimensionMismatch())
117-
return ()
118-
end
119-
function _computereshapestrides(newsize::Dims, oldsize::Tuple{}, strides::Tuple{})
120-
all(isequal(1), newsize) || throw(DimensionMismatch())
121-
return newsize
122-
end
163+
_computereshapestrides(newsize::Tuple{}, oldsize::Dims, strides::Dims) = ()
164+
_computereshapestrides(newsize::Dims, oldsize::Tuple{}, strides::Tuple{}) = newsize
123165
function _computereshapestrides(newsize::Dims, oldsize::Dims{N}, strides::Dims{N}) where {N}
124166
d, r = divrem(oldsize[1], newsize[1])
125167
return if r == 0
@@ -137,10 +179,6 @@ function _computereshapestrides(newsize::Dims, oldsize::Dims{N}, strides::Dims{N
137179
return isnothing(stail) ? nothing : (s1, stail...)
138180
end
139181
else
140-
if prod(newsize) != prod(oldsize)
141-
throw(DimensionMismatch())
142-
else
143-
return nothing
144-
end
182+
return nothing
145183
end
146184
end

‎src/stridedview.jl‎

Lines changed: 49 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,32 @@ end
5858

5959
"""
6060
unsafe_stridedview(T, parent, size, strides, offset, op)
61+
unsafe_stridedview(a::StridedView, size = size(a), strides = strides(a), offset = offset(a))
6162
62-
Construct a `StridedView{T}` without normalizing `parent` and `strides`, which are assumed to
63-
be normalized already, e.g. because they are taken from an existing `StridedView`.
63+
Construct a `StridedView{T}` without normalizing `parent` and `strides`.
64+
65+
The first form assumes these are normalized already, e.g. because they are taken from an
66+
existing `StridedView`. The second form keeps the element type, parent and operation of `a`
67+
and replaces its layout, which can have any number of dimensions. The strides are used as
68+
given, so they need not be normalized: e.g. a stride of zero repeats the same element along
69+
that dimension.
70+
71+
!!! warning
72+
No checks are performed: the caller is responsible for all indices in the new layout
73+
being valid indices of the parent.
6474
"""
65-
function unsafe_stridedview(
75+
@inline function unsafe_stridedview(
6676
::Type{T}, parent::DenseArray, size::NTuple{N, Int}, strides::NTuple{N, Int},
6777
offset::Int, op::F
6878
) where {T, N, F}
6979
return StridedView{T, N, typeof(parent), F}(parent, size, strides, offset, op)
7080
end
81+
@inline function unsafe_stridedview(
82+
a::StridedView{T}, size::NTuple{N, Int} = a.size, strides::NTuple{N, Int} = a.strides,
83+
offset::Int = a.offset
84+
) where {T, N}
85+
return unsafe_stridedview(T, a.parent, size, strides, offset, a.op)
86+
end
7187

7288
StridedView(a::StridedView) = a
7389
StridedView(a::Adjoint) = StridedView(a')'
@@ -81,9 +97,8 @@ function StridedView(a::Base.ReinterpretArray{T, N}) where {T, N}
8197
b = StridedView(a.parent)
8298
S = eltype(b)
8399
isbitstype(T) && isbitstype(S) && sizeof(T) == sizeof(S) ||
84-
throw(ArgumentError("Cannot create StridedView with reinterpretation from $S to $T"))
85-
b.op isa FN ||
86-
throw(ArgumentError("Cannot create StridedView with reinterpretation from view with non-identity operation"))
100+
_throw_reinterpret_eltype(S, T)
101+
b.op isa FN || _throw_reinterpret_op()
87102
return unsafe_stridedview(T, b.parent, size(b), strides(b), offset(b), identity)
88103
end
89104

@@ -118,7 +133,7 @@ _strides(a::Transpose{<:Any, <:AbstractVector}) = (stride(a.parent, 2), stride(a
118133
_strides(a::Transpose{<:Any, <:AbstractMatrix}) = reverse(strides(a.parent))
119134
function _strides(a::PermutedDimsArray{T, N, perm}) where {T, N, perm}
120135
s = _strides(parent(a))
121-
return ntuple(d -> s[perm[d]], Val(N))
136+
return ntuple(d -> @inbounds(s[perm[d]]), Val(N)) # `perm` is a valid permutation
122137
end
123138
_strides(a::SubArray) = Base.substrides(_strides(a.parent), a.indices)
124139

@@ -152,13 +167,11 @@ end
152167
end
153168

154169
# Indexing with slice indices to create a new view.
155-
function Base.getindex(a::StridedView{T, N}, I::Vararg{SliceIndex, N}) where {T, N}
170+
@inline function Base.getindex(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N}
171+
@boundscheck checkbounds(a, I...)
156172
newsize = _computeviewsize(a.size, I)
157173
newstrides = _normalizestrides(newsize, _computeviewstrides(a.strides, I))
158-
return unsafe_stridedview(
159-
T, a.parent, newsize, newstrides,
160-
a.offset + _computeviewoffset(a.strides, I), a.op
161-
)
174+
return unsafe_stridedview(a, newsize, newstrides, a.offset + _computeviewoffset(a.strides, I))
162175
end
163176

164177
# Indexing directly into parent array
@@ -192,11 +205,12 @@ function Base.conj(a::StridedView)
192205
return unsafe_stridedview(T, a.parent, a.size, a.strides, a.offset, newop)
193206
end
194207

195-
function Base.permutedims(a::StridedView{T, N}, p) where {T, N}
196-
_isperm(N, p) || throw(ArgumentError("Invalid permutation of length $N: $p"))
197-
newsize = ntuple(n -> size(a, p[n]), Val(N))
198-
newstrides = ntuple(n -> stride(a, p[n]), Val(N))
199-
return unsafe_stridedview(T, a.parent, newsize, _normalizestrides(newsize, newstrides), a.offset, a.op)
208+
function Base.permutedims(a::StridedView{<:Any, N}, p) where {N}
209+
_isperm(N, p) || _throw_invalidperm(N, p)
210+
# `p` has been checked to be a permutation of `1:N`
211+
newsize = ntuple(n -> @inbounds(a.size[p[n]]), Val(N))
212+
newstrides = ntuple(n -> @inbounds(a.strides[p[n]]), Val(N))
213+
return unsafe_stridedview(a, newsize, _normalizestrides(newsize, newstrides))
200214
end
201215

202216
LinearAlgebra.transpose(a::StridedView{<:Number, 2}) = permutedims(a, (2, 1))
@@ -240,18 +254,24 @@ end
240254
# Creating or transforming StridedView by slicing
241255
#-------------------------------------------------
242256
# we cannot use Base.view, as this also accepts indices that might not preserve stridedness
243-
sview(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} = getindex(a, I...)
244-
sview(a::StridedView, I::SliceIndex) = getindex(sreshape(a, (length(a),)), I)
257+
@propagate_inbounds function sview(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N}
258+
return getindex(a, I...)
259+
end
260+
@propagate_inbounds function sview(a::StridedView, I::SliceIndex)
261+
return getindex(sreshape(a, (length(a),)), I)
262+
end
245263

246264
# for StridedView and index arguments which preserve stridedness, we do replace Base.view
247265
# with sview
248-
Base.view(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} = getindex(a, I...)
266+
@propagate_inbounds function Base.view(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N}
267+
return getindex(a, I...)
268+
end
249269

250270
# `sview` can be used as a constructor when acting on `AbstractArray` objects
251-
function sview(a::AbstractArray{<:Any, N}, I::Vararg{SliceIndex, N}) where {N}
271+
@propagate_inbounds function sview(a::AbstractArray{<:Any, N}, I::Vararg{SliceIndex, N}) where {N}
252272
return getindex(StridedView(a), I...)
253273
end
254-
function sview(a::AbstractArray, I::SliceIndex)
274+
@propagate_inbounds function sview(a::AbstractArray, I::SliceIndex)
255275
return getindex(sreshape(StridedView(a), (length(a),)), I)
256276
end
257277

@@ -267,19 +287,22 @@ function Base.show(io::IO, e::ReshapeException)
267287
msg = "Cannot reshape a StridedView with size $(e.oldsize) and strides $(e.strides) to newsize=$(e.newsize) without allocating, try `sreshape(copy(array), newsize)` or fall back to `reshape(array, newsize)`."
268288
return print(io, msg)
269289
end
290+
@noinline function _throw_reshapeexception(newsize::Dims, oldsize::Dims, strides::Dims)
291+
throw(ReshapeException(newsize, oldsize, strides))
292+
end
270293

271294
# we cannot use Base.reshape, as this also accepts indices that might not preserve stridedness
272295
sreshape(a, args::Vararg{Int}) = sreshape(a, args)
273-
function sreshape(a::StridedView{T}, newsize::Dims) where {T}
296+
function sreshape(a::StridedView, newsize::Dims)
274297
size(a) == newsize && return a
298+
prod(newsize) == length(a) || _throw_reshape_dimensionmismatch(size(a), newsize)
275299
if any(isequal(0), newsize)
276-
any(isequal(0), size(a)) || throw(DimensionMismatch())
277300
newstrides = one.(newsize)
278301
else
279302
newstrides = _computereshapestrides(newsize, _simplifydims(size(a), strides(a))...)
280303
end
281-
isnothing(newstrides) && throw(ReshapeException(newsize, size(a), strides(a)))
282-
return unsafe_stridedview(T, a.parent, newsize, _normalizestrides(newsize, newstrides), a.offset, a.op)
304+
isnothing(newstrides) && _throw_reshapeexception(newsize, size(a), strides(a))
305+
return unsafe_stridedview(a, newsize, _normalizestrides(newsize, newstrides))
283306
end
284307

285308
sreshape(a::AbstractArray, newsize::Dims) = sreshape(StridedView(a), newsize)

‎test/runtests.jl‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,109 @@ if !is_buildkite
259259
end
260260
end
261261

262+
@testset "stride normalization" begin
263+
# reference implementation (previous version of `_normalizestrides`)
264+
function normalizestrides_ref(size::Dims{N}, strides::Dims{N}) where {N}
265+
for i in 1:N
266+
if size[i] == 1
267+
newstride = i == 1 ? 1 : strides[i - 1] * size[i - 1]
268+
strides = Base.setindex(strides, newstride, i)
269+
elseif size[i] == 0
270+
return (1, Base.front(cumprod(size))...)
271+
end
272+
end
273+
return strides
274+
end
275+
@test @inferred(StridedViews._normalizestrides((), ())) == ()
276+
for N in 1:6, _ in 1:200
277+
sz = ntuple(_ -> rand((0, 1, 1, 2, 3)), N)
278+
st = ntuple(_ -> rand(-5:20), N)
279+
@test @inferred(StridedViews._normalizestrides(sz, st)) ==
280+
normalizestrides_ref(sz, st)
281+
end
282+
@test StridedViews._normalizestrides((1, 1, 3, 1, 2), (7, 7, 5, 7, 2)) ==
283+
(1, 1, 5, 15, 2)
284+
end
285+
286+
@testset "unsafe_stridedview with a StridedView" begin
287+
A = randn(ComplexF64, 4, 3, 2)
288+
B = conj(StridedView(A))
289+
@test StridedViews.unsafe_stridedview(B) === B
290+
C = @inferred StridedViews.unsafe_stridedview(B, (4, 6), (1, 4))
291+
@test C isa StridedView{ComplexF64, 2, typeof(B.parent), typeof(conj)}
292+
@test C == conj(reshape(A, (4, 6)))
293+
# strides are used as given, e.g. zero strides for broadcasting
294+
D = StridedViews.unsafe_stridedview(B, (4, 5), (1, 0), StridedViews.offset(B) + 4)
295+
@test D == repeat(conj(A[:, 2, 1]), 1, 5)
296+
@test strides(D) == (1, 0)
297+
end
298+
299+
@testset "permutation check" begin
300+
mask(p) = StridedViews._isperm_mask(p, length(p))
301+
# exhaustive for small lengths, including out of range entries
302+
for N in 0:5, t in Iterators.product(ntuple(_ -> -1:(N + 1), N)...)
303+
@test mask(t) == isperm(t)
304+
@test StridedViews._isperm(N, t) == isperm(t)
305+
@test StridedViews._isperm(N, collect(Int, t)) == isperm(t)
306+
end
307+
for N in (6, 10, 17, 63, 64, 65), _ in 1:50
308+
p = randperm(N)
309+
@test StridedViews._isperm(N, Tuple(p))
310+
@test StridedViews._isperm(N, p)
311+
@test StridedViews._isperm(N, UInt8.(p))
312+
q = copy(p)
313+
q[rand(1:N)] = rand((0, -1, N + 1, typemin(Int), p[mod1(rand(1:N), N)]))
314+
isperm(q) && continue # the replacement can be the original entry
315+
@test !StridedViews._isperm(N, Tuple(q))
316+
@test !StridedViews._isperm(N, q)
317+
end
318+
@test !StridedViews._isperm(3, (1, 2))
319+
@test !StridedViews._isperm(2, [1, 2, 3])
320+
@test !StridedViews._isperm(2, (UInt(2)^63 + 1, 1))
321+
@test !StridedViews._isperm(2, "ab")
322+
end
323+
324+
@testset "bounds checks when slicing" begin
325+
A = randn(3, 4, 5)
326+
B = StridedView(A)
327+
@test_throws BoundsError B[1:4, :, :]
328+
@test_throws BoundsError B[0:2, :, 1]
329+
@test_throws BoundsError B[:, 5, :]
330+
@test_throws BoundsError view(B, :, :, 2:6)
331+
@test_throws BoundsError sview(B, :, 1:2:5, 1)
332+
@test_throws BoundsError sview(B, 1:61)
333+
@test_throws BoundsError sview(A, 3:4, :, :)
334+
@test B[3:-1:1, 4:-2:1, 1:0] == A[3:-1:1, 4:-2:1, 1:0]
335+
@test sview(B, 60:-7:1) == vec(A)[60:-7:1]
336+
end
337+
338+
@testset "errors" begin
339+
B = StridedView(randn(2, 3, 4))
340+
err = try
341+
permutedims(B, (1, 1, 2))
342+
catch e
343+
e
344+
end
345+
@test err isa ArgumentError
346+
@test err.msg == "Invalid permutation of length 3: (1, 1, 2)"
347+
@test_throws ArgumentError permutedims(B, (1, 2))
348+
@test_throws ArgumentError permutedims(B, [3, 1])
349+
@test_throws DimensionMismatch sreshape(B, (5, 5))
350+
err = try
351+
sreshape(B, (5, 5))
352+
catch e
353+
e
354+
end
355+
@test sprint(showerror, err) ==
356+
"DimensionMismatch: Cannot reshape a StridedView of size (2, 3, 4) (length 24) to size (5, 5) (length 25)"
357+
@test_throws DimensionMismatch sreshape(StridedView(zeros(2, 0)), (3, 1))
358+
@test_throws DimensionMismatch sreshape(B, (2, 3, 4, 0))
359+
@test_throws StridedViews.ReshapeException sreshape(B[:, 1:2, :], (2, 8))
360+
@test_throws ArgumentError StridedView(reinterpret(Float32, randn(4)))
361+
A = randn(ComplexF64, 4)
362+
@test_throws ArgumentError StridedView(reinterpret(NTuple{2, Float64}, conj(StridedView(A))))
363+
end
364+
262365
@testset "views with StridedView" begin
263366
@testset for T in (Float32, Float64, ComplexF32, ComplexF64)
264367
A = randn(T, (10, 10, 10, 10))

0 commit comments

Comments
 (0)