Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 70 additions & 32 deletions src/auxiliary.jl
Original file line number Diff line number Diff line change
@@ -1,10 +1,53 @@
# Auxiliary routines
#---------------------
# Errors are thrown from `@noinline` functions, so that building the exception and its
# message does not end up in the code of the (often inlined) callers. Messages with
# interpolation are `LazyString`s, so that they are only built when they are shown.
@noinline function _throw_reshape_dimensionmismatch(oldsize::Dims, newsize::Dims)
throw(DimensionMismatch(lazy"Cannot reshape a StridedView of size $oldsize (length $(prod(oldsize))) to size $newsize (length $(prod(newsize)))"))
end
@noinline function _throw_invalidperm(N::Int, p)
throw(ArgumentError(lazy"Invalid permutation of length $N: $p"))
end
@noinline function _throw_reinterpret_eltype(S::Type, T::Type)
throw(ArgumentError(lazy"Cannot create StridedView with reinterpretation from $S to $T"))
end
@noinline function _throw_reinterpret_op()
throw(ArgumentError("Cannot create StridedView with reinterpretation from view with non-identity operation"))
end

# Check whether p is a valid permutation of length N
_isperm(N::Integer, p::AbstractVector) = (length(p) == N && isperm(p))
_isperm(N::Integer, p::NTuple{M, Integer}) where {M} = (M == N && isperm(p))
# For N <= 64, the entries are recorded as bits in a mask: N entries that are all in `1:N` form
# a permutation if and only if together they set all N bits. This takes O(N) operations
# without branches or allocations, whereas `Base.isperm` compares all pairs for tuples
# (O(N^2)) and allocates for vectors. For N <= 4, `Base.isperm` is just as fast for tuples.
@inline function _isperm(N::Integer, p::NTuple{M, Integer}) where {M}
M == N || return false
# `M` is known at compile time, so only one of the branches remains
(M <= 4 || M > 64) && return isperm(p)
return _isperm_mask(p, M)
end
function _isperm(N::Integer, p::AbstractVector{<:Integer})
length(p) == N || return false
N > 64 && return isperm(p)
return _isperm_mask(p, Int(N))
end
_isperm(N::Integer, p::AbstractVector) = length(p) == N && isperm(p)
_isperm(N::Integer, p) = false

@inline function _isperm_mask(p, N::Int)
used = zero(UInt64)
valid = true
for x in p
valid &= (1 <= x <= N)
# `% Int` and `& 63` keep the shift well defined (and branch free) for invalid entries,
# which are rejected through `valid`
used |= one(UInt64) << (((x % Int) - 1) & 63)
end
full = N == 64 ? typemax(UInt64) : (one(UInt64) << N) - one(UInt64)
return valid & (used == full)
end

# Compute the memory index given a list of cartesian indices and corresponding strides
@inline function _computeind(indices::NTuple{N, Int}, strides::NTuple{N, Int}) where {N}
return (indices[1] - 1) * strides[1] + _computeind(tail(indices), tail(strides))
Expand All @@ -30,20 +73,25 @@ function _simplifydims(size::Dims{N}, strides::Dims{N}) where {N}
end

# 'Normalize' the strides of a `StridedView`, i.e. strides associated with dimensions of
# size 1 have no intrinsic meaning and can be changed arbitrarily. If one of the dimensions
# has size zero, then the whole array has length zero, and all strides are ambiguous. All
# ambiguous strides are set to 1.
function _normalizestrides(size::Dims{N}, strides::Dims{N}) where {N}
for i in 1:N
if size[i] == 1
newstride = i == 1 ? 1 : strides[i - 1] * size[i - 1]
strides = Base.setindex(strides, newstride, i)
elseif size[i] == 0
return (1, Base.front(cumprod(size))...)
end
end
return strides
# size 1 have no intrinsic meaning and can be changed arbitrarily. They are set to the extent
# of the preceding dimension (stride times size), or 1 for leading dimensions of size 1, such
# that a size 1 dimension never prevents fusing its neighbours. If one of the dimensions has
# size zero, then the whole array has length zero, and all strides are ambiguous; they are
# set to those of a contiguous array.
# The strides are computed with a fully unrolled scan that carries the extent of the
# preceding dimension.
@inline function _normalizestrides(size::Dims{N}, strides::Dims{N}) where {N}
any(iszero, size) && return _contiguousstrides(size)
return first(_normalizestrides_scan(size, strides, 1))
end
_normalizestrides_scan(::Tuple{}, ::Tuple{}, carry::Int) = ((), carry)
@inline function _normalizestrides_scan(size::Dims, strides::Dims, carry::Int)
s = ifelse(size[1] == 1, carry, strides[1])
rest, _ = _normalizestrides_scan(tail(size), tail(strides), size[1] * s)
return (s, rest...), carry
end
_contiguousstrides(::Tuple{}) = ()
@inline _contiguousstrides(size::Dims) = (1, Base.front(cumprod(size))...)

# 'Normalize' the layout of a DenseArray, in order to reduce the number of required
# specializations in functions. The offset is adjusted to the start of `A` in the
Expand Down Expand Up @@ -107,19 +155,13 @@ _computeviewoffset(::Tuple{}, ::Tuple{}) = 0
# Auxiliary methods for `sreshape`
#----------------------------------
# Compute the new strides of a (strided) reshape given the original strides and new and
# original sizes
# original sizes, or `nothing` if the reshape is not possible without copying.
# Callers guarantee that `prod(newsize) == prod(oldsize)`, which is preserved in the
# recursion: once one of the sizes is exhausted, the remaining dimensions of the other one
# all have size 1.
_computereshapestrides(newsize::Tuple{}, oldsize::Tuple{}, strides::Tuple{}) = strides
function _computereshapestrides(
newsize::Tuple{}, oldsize::Dims{N},
strides::Dims{N}
) where {N}
all(isequal(1), oldsize) || throw(DimensionMismatch())
return ()
end
function _computereshapestrides(newsize::Dims, oldsize::Tuple{}, strides::Tuple{})
all(isequal(1), newsize) || throw(DimensionMismatch())
return newsize
end
_computereshapestrides(newsize::Tuple{}, oldsize::Dims, strides::Dims) = ()
_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.

Expand All @@ -137,10 +179,6 @@ function _computereshapestrides(newsize::Dims, oldsize::Dims{N}, strides::Dims{N
return isnothing(stail) ? nothing : (s1, stail...)
end
else
if prod(newsize) != prod(oldsize)
throw(DimensionMismatch())
else
return nothing
end
return nothing
end
end
75 changes: 49 additions & 26 deletions src/stridedview.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,32 @@ end

"""
unsafe_stridedview(T, parent, size, strides, offset, op)
unsafe_stridedview(a::StridedView, size = size(a), strides = strides(a), offset = offset(a))

Construct a `StridedView{T}` without normalizing `parent` and `strides`, which are assumed to
be normalized already, e.g. because they are taken from an existing `StridedView`.
Construct a `StridedView{T}` without normalizing `parent` and `strides`.

The first form assumes these are normalized already, e.g. because they are taken from an
existing `StridedView`. The second form keeps the element type, parent and operation of `a`
and replaces its layout, which can have any number of dimensions. The strides are used as
given, so they need not be normalized: e.g. a stride of zero repeats the same element along
that dimension.

!!! warning
No checks are performed: the caller is responsible for all indices in the new layout
being valid indices of the parent.
"""
function unsafe_stridedview(
@inline function unsafe_stridedview(
::Type{T}, parent::DenseArray, size::NTuple{N, Int}, strides::NTuple{N, Int},
offset::Int, op::F
) where {T, N, F}
return StridedView{T, N, typeof(parent), F}(parent, size, strides, offset, op)
end
@inline function unsafe_stridedview(
a::StridedView{T}, size::NTuple{N, Int} = a.size, strides::NTuple{N, Int} = a.strides,
offset::Int = a.offset
) where {T, N}
return unsafe_stridedview(T, a.parent, size, strides, offset, a.op)
end

StridedView(a::StridedView) = a
StridedView(a::Adjoint) = StridedView(a')'
Expand All @@ -81,9 +97,8 @@ function StridedView(a::Base.ReinterpretArray{T, N}) where {T, N}
b = StridedView(a.parent)
S = eltype(b)
isbitstype(T) && isbitstype(S) && sizeof(T) == sizeof(S) ||
throw(ArgumentError("Cannot create StridedView with reinterpretation from $S to $T"))
b.op isa FN ||
throw(ArgumentError("Cannot create StridedView with reinterpretation from view with non-identity operation"))
_throw_reinterpret_eltype(S, T)
b.op isa FN || _throw_reinterpret_op()
return unsafe_stridedview(T, b.parent, size(b), strides(b), offset(b), identity)
end

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

Expand Down Expand Up @@ -152,13 +167,11 @@ end
end

# Indexing with slice indices to create a new view.
function Base.getindex(a::StridedView{T, N}, I::Vararg{SliceIndex, N}) where {T, N}
@inline function Base.getindex(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N}
@boundscheck checkbounds(a, I...)
newsize = _computeviewsize(a.size, I)
newstrides = _normalizestrides(newsize, _computeviewstrides(a.strides, I))
return unsafe_stridedview(
T, a.parent, newsize, newstrides,
a.offset + _computeviewoffset(a.strides, I), a.op
)
return unsafe_stridedview(a, newsize, newstrides, a.offset + _computeviewoffset(a.strides, I))
end

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

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

LinearAlgebra.transpose(a::StridedView{<:Number, 2}) = permutedims(a, (2, 1))
Expand Down Expand Up @@ -240,18 +254,24 @@ end
# Creating or transforming StridedView by slicing
#-------------------------------------------------
# we cannot use Base.view, as this also accepts indices that might not preserve stridedness
sview(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N} = getindex(a, I...)
sview(a::StridedView, I::SliceIndex) = getindex(sreshape(a, (length(a),)), I)
@propagate_inbounds function sview(a::StridedView{<:Any, N}, I::Vararg{SliceIndex, N}) where {N}
return getindex(a, I...)
end
@propagate_inbounds function sview(a::StridedView, I::SliceIndex)
return getindex(sreshape(a, (length(a),)), I)
end

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

# `sview` can be used as a constructor when acting on `AbstractArray` objects
function sview(a::AbstractArray{<:Any, N}, I::Vararg{SliceIndex, N}) where {N}
@propagate_inbounds function sview(a::AbstractArray{<:Any, N}, I::Vararg{SliceIndex, N}) where {N}
return getindex(StridedView(a), I...)
end
function sview(a::AbstractArray, I::SliceIndex)
@propagate_inbounds function sview(a::AbstractArray, I::SliceIndex)
return getindex(sreshape(StridedView(a), (length(a),)), I)
end

Expand All @@ -267,19 +287,22 @@ function Base.show(io::IO, e::ReshapeException)
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)`."
return print(io, msg)
end
@noinline function _throw_reshapeexception(newsize::Dims, oldsize::Dims, strides::Dims)
throw(ReshapeException(newsize, oldsize, strides))
end

# we cannot use Base.reshape, as this also accepts indices that might not preserve stridedness
sreshape(a, args::Vararg{Int}) = sreshape(a, args)
function sreshape(a::StridedView{T}, newsize::Dims) where {T}
function sreshape(a::StridedView, newsize::Dims)
size(a) == newsize && return a
prod(newsize) == length(a) || _throw_reshape_dimensionmismatch(size(a), newsize)
if any(isequal(0), newsize)
any(isequal(0), size(a)) || throw(DimensionMismatch())
newstrides = one.(newsize)
else
newstrides = _computereshapestrides(newsize, _simplifydims(size(a), strides(a))...)
end
isnothing(newstrides) && throw(ReshapeException(newsize, size(a), strides(a)))
return unsafe_stridedview(T, a.parent, newsize, _normalizestrides(newsize, newstrides), a.offset, a.op)
isnothing(newstrides) && _throw_reshapeexception(newsize, size(a), strides(a))
return unsafe_stridedview(a, newsize, _normalizestrides(newsize, newstrides))
end

sreshape(a::AbstractArray, newsize::Dims) = sreshape(StridedView(a), newsize)
Expand Down
103 changes: 103 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,109 @@ if !is_buildkite
end
end

@testset "stride normalization" begin
# reference implementation (previous version of `_normalizestrides`)
function normalizestrides_ref(size::Dims{N}, strides::Dims{N}) where {N}
for i in 1:N
if size[i] == 1
newstride = i == 1 ? 1 : strides[i - 1] * size[i - 1]
strides = Base.setindex(strides, newstride, i)
elseif size[i] == 0
return (1, Base.front(cumprod(size))...)
end
end
return strides
end
@test @inferred(StridedViews._normalizestrides((), ())) == ()
for N in 1:6, _ in 1:200
sz = ntuple(_ -> rand((0, 1, 1, 2, 3)), N)
st = ntuple(_ -> rand(-5:20), N)
@test @inferred(StridedViews._normalizestrides(sz, st)) ==
normalizestrides_ref(sz, st)
end
@test StridedViews._normalizestrides((1, 1, 3, 1, 2), (7, 7, 5, 7, 2)) ==
(1, 1, 5, 15, 2)
end

@testset "unsafe_stridedview with a StridedView" begin
A = randn(ComplexF64, 4, 3, 2)
B = conj(StridedView(A))
@test StridedViews.unsafe_stridedview(B) === B
C = @inferred StridedViews.unsafe_stridedview(B, (4, 6), (1, 4))
@test C isa StridedView{ComplexF64, 2, typeof(B.parent), typeof(conj)}
@test C == conj(reshape(A, (4, 6)))
# strides are used as given, e.g. zero strides for broadcasting
D = StridedViews.unsafe_stridedview(B, (4, 5), (1, 0), StridedViews.offset(B) + 4)
@test D == repeat(conj(A[:, 2, 1]), 1, 5)
@test strides(D) == (1, 0)
end

@testset "permutation check" begin
mask(p) = StridedViews._isperm_mask(p, length(p))
# exhaustive for small lengths, including out of range entries
for N in 0:5, t in Iterators.product(ntuple(_ -> -1:(N + 1), N)...)
@test mask(t) == isperm(t)
@test StridedViews._isperm(N, t) == isperm(t)
@test StridedViews._isperm(N, collect(Int, t)) == isperm(t)
end
for N in (6, 10, 17, 63, 64, 65), _ in 1:50
p = randperm(N)
@test StridedViews._isperm(N, Tuple(p))
@test StridedViews._isperm(N, p)
@test StridedViews._isperm(N, UInt8.(p))
q = copy(p)
q[rand(1:N)] = rand((0, -1, N + 1, typemin(Int), p[mod1(rand(1:N), N)]))
isperm(q) && continue # the replacement can be the original entry
@test !StridedViews._isperm(N, Tuple(q))
@test !StridedViews._isperm(N, q)
end
@test !StridedViews._isperm(3, (1, 2))
@test !StridedViews._isperm(2, [1, 2, 3])
@test !StridedViews._isperm(2, (UInt(2)^63 + 1, 1))
@test !StridedViews._isperm(2, "ab")
end

@testset "bounds checks when slicing" begin
A = randn(3, 4, 5)
B = StridedView(A)
@test_throws BoundsError B[1:4, :, :]
@test_throws BoundsError B[0:2, :, 1]
@test_throws BoundsError B[:, 5, :]
@test_throws BoundsError view(B, :, :, 2:6)
@test_throws BoundsError sview(B, :, 1:2:5, 1)
@test_throws BoundsError sview(B, 1:61)
@test_throws BoundsError sview(A, 3:4, :, :)
@test B[3:-1:1, 4:-2:1, 1:0] == A[3:-1:1, 4:-2:1, 1:0]
@test sview(B, 60:-7:1) == vec(A)[60:-7:1]
end

@testset "errors" begin
B = StridedView(randn(2, 3, 4))
err = try
permutedims(B, (1, 1, 2))
catch e
e
end
@test err isa ArgumentError
@test err.msg == "Invalid permutation of length 3: (1, 1, 2)"
@test_throws ArgumentError permutedims(B, (1, 2))
@test_throws ArgumentError permutedims(B, [3, 1])
@test_throws DimensionMismatch sreshape(B, (5, 5))
err = try
sreshape(B, (5, 5))
catch e
e
end
@test sprint(showerror, err) ==
"DimensionMismatch: Cannot reshape a StridedView of size (2, 3, 4) (length 24) to size (5, 5) (length 25)"
@test_throws DimensionMismatch sreshape(StridedView(zeros(2, 0)), (3, 1))
@test_throws DimensionMismatch sreshape(B, (2, 3, 4, 0))
@test_throws StridedViews.ReshapeException sreshape(B[:, 1:2, :], (2, 8))
@test_throws ArgumentError StridedView(reinterpret(Float32, randn(4)))
A = randn(ComplexF64, 4)
@test_throws ArgumentError StridedView(reinterpret(NTuple{2, Float64}, conj(StridedView(A))))
end

@testset "views with StridedView" begin
@testset for T in (Float32, Float64, ComplexF32, ComplexF64)
A = randn(T, (10, 10, 10, 10))
Expand Down
Loading