From 984ffacde423b7e076d8e6e370999522947584e7 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sat, 3 Oct 2026 17:06:59 +0200 Subject: [PATCH 1/8] Tune the workgroup size of a launch over an index range A kernel launched without a workgroup size partitions its ndrange with the ndrange itself as a preliminary workgroup size, which is not a valid workgroup size when the ndrange is a range or a CartesianIndices. Use its extents instead, as `Int`s also for a range of unsigned integers, whose length the tuning would otherwise not accept. --- src/backend_launch.jl | 7 ++++--- src/nditeration.jl | 4 ++-- test/offsets.jl | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/backend_launch.jl b/src/backend_launch.jl index fbd5cfd8d..28e49b997 100644 --- a/src/backend_launch.jl +++ b/src/backend_launch.jl @@ -26,7 +26,8 @@ mkcontext(kernel::Kernel, I, _ndrange, iterspace, ::Dynamic) where {Dynamic} = Normalize the launch arguments of `kernel`, and partition the `ndrange`. Returns the `ndrange` (`nothing` if it's static), the `workgroupsize` (`nothing` if it will be tuned), the iteration space and whether it needs bounds checks. If the workgroup size will be -tuned, the iteration space is preliminary: it uses the `ndrange` as the workgroup size. +tuned, the iteration space is preliminary: it uses the extents of the `ndrange` as the +workgroup size. """ function launch_config(kernel::Kernel, _ndrange, _workgroupsize) if _ndrange isa Integer @@ -37,8 +38,8 @@ function launch_config(kernel::Kernel, _ndrange, _workgroupsize) end iterspace, dynamic = if workgroupsize(kernel) <: DynamicSize && _workgroupsize === nothing - # use the ndrange as preliminary workgroupsize for autotuning - partition(kernel, _ndrange, something(_ndrange, static_ndrange(kernel))) + # use the extents of the ndrange as preliminary workgroupsize for autotuning + partition(kernel, _ndrange, extents(something(_ndrange, static_ndrange(kernel)))) else # this also checks that a given ndrange agrees with a static one partition(kernel, _ndrange, _workgroupsize) diff --git a/src/nditeration.jl b/src/nditeration.jl index 30a2238ab..d588f713d 100644 --- a/src/nditeration.jl +++ b/src/nditeration.jl @@ -18,7 +18,7 @@ axis(r::Base.OneTo) = Int(length(r)) axis(r::AbstractUnitRange) = UnitRange{Int}(r) extent(n::Integer) = Int(n) -extent(r::AbstractUnitRange) = length(r) +extent(r::AbstractUnitRange) = Int(length(r)) axis_offset(::Integer) = 0 axis_offset(r::AbstractUnitRange) = first(r) - 1 @@ -31,7 +31,7 @@ a `CartesianIndices`, a single range, or an integer. """ extents(t::Tuple) = map(extent, t) extents(ci::CartesianIndices) = size(ci) -extents(r::AbstractUnitRange) = (length(r),) +extents(r::AbstractUnitRange) = (extent(r),) extents(n::Integer) = (Int(n),) """ diff --git a/test/offsets.jl b/test/offsets.jl index 0367f6438..d8948ed4b 100644 --- a/test/offsets.jl +++ b/test/offsets.jl @@ -50,6 +50,23 @@ function offsets_testsuite(Backend, AT) @test Array(out) == ref end + @testset "dynamic workgroupsize" begin + # the workgroup size is tuned, starting from the extents of the ndrange + @testset for ndrange in (ranges, CartesianIndices(ranges)) + out = fresh() + offsets_fill_indices!(backend)(out, lo; ndrange) + synchronize(backend) + @test Array(out) == ref + end + + @testset for ndrange in (5:20, UInt(5):UInt(20)) + out = AT(zeros(Int, 16)) + offsets_fill_indices!(backend)(out, (5,); ndrange) + synchronize(backend) + @test Array(out) == 1:16 + end + end + @testset "mixed extents and ranges" begin out = fresh() offsets_fill_indices!(backend, (4, 4))(out, (1, 2); ndrange = (8, 2:11)) From b805173e6b452ab1e60b90feef4f09050d049654 Mon Sep 17 00:00:00 2001 From: Valentin Churavy Date: Sun, 13 Sep 2026 14:48:18 +0200 Subject: [PATCH 2/8] Add `foreach_index` A kernel whose body is a loop over the indices of an array needs none of the kernel language beyond the index itself, and writing it out is boilerplate that downstream packages repeat. Add `foreach_index(f, itr, backend = get_backend(itr); workgroupsize)`, which launches one work item per index of `eachindex(itr)` and calls `f` with the index a `for i in eachindex(itr)` loop would produce: a linear index for an `IndexLinear` array, a `CartesianIndex` otherwise. The index space is carried by the `ndrange`, so the kernel takes no argument besides the function, and an index space that does not start at 1 needs no special handling. The function is inlined into the kernel, as an out-of-line call to a closure can spill its captures to local memory. Ported from AcceleratedKernels.jl, without its CPU scheduling keywords (`max_tasks`, `min_elems`, `prefer_threads`): those pick a host-threaded loop, which 0.10 no longer has, and the workgroup size is left to the backend rather than defaulting to 256. Spelled with an underscore to keep the name distinct from the AcceleratedKernels function it does not behave identically to, so that importing both packages does not clash. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01DbbtGLjxXpt7kZj6h2yVdK --- docs/src/api.md | 6 ++ docs/src/index.md | 1 + docs/src/kernels.md | 24 +++++++ src/KernelAbstractions.jl | 2 + src/foreach_index.jl | 75 ++++++++++++++++++++ test/foreach_index.jl | 141 ++++++++++++++++++++++++++++++++++++++ test/testsuite.jl | 5 ++ 7 files changed, 254 insertions(+) create mode 100644 src/foreach_index.jl create mode 100644 test/foreach_index.jl diff --git a/docs/src/api.md b/docs/src/api.md index 826cd7455..09b5eb9b9 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -72,6 +72,12 @@ KernelAbstractions.ndrange KernelAbstractions.backend ``` +### Index loops + +```@docs +foreach_index +``` + ## Reflection To look at the code a backend actually generates, wrap a kernel launch in one of the diff --git a/docs/src/index.md b/docs/src/index.md index 9342c32fc..473aba615 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -153,6 +153,7 @@ end - The `CPU` backend runs kernels on as many threads as Julia was started with (`julia -t`), like the thread-based `CPU` backend of 0.9 did, and no longer on one thread per hardware thread. Set `JULIA_KA_CPU_THREADS` to use a different number of threads; see [`CPU`](@ref). +- `foreach_index(f, itr)` runs `f` once per index of `itr` without writing a kernel out. ## Semantic differences diff --git a/docs/src/kernels.md b/docs/src/kernels.md index e1bf57a8b..0f8b2802b 100644 --- a/docs/src/kernels.md +++ b/docs/src/kernels.md @@ -255,3 +255,27 @@ and `@ndrange()` returns the extents. Obtain the backend from an array with [`get_backend`](@ref) and always call [`synchronize`](@ref) before reading results on the host. See the [Quickstart](@ref) for a full walkthrough and the Examples section of the manual for larger patterns. + +## Loops without a kernel + +A kernel whose body is a loop over the indices of an array needs none of the kernel language +beyond the index itself. [`foreach_index`](@ref) launches such a loop directly, with one work item +per index of `eachindex(itr)`: + +```julia +function scale!(y, x) + foreach_index(x) do i + @inbounds y[i] = 2 * x[i] + 1 + end + return y +end +``` + +The body is an ordinary Julia function, and it receives the index a `for i in eachindex(itr)` loop +would: a linear index for an array with `IndexLinear` style, a `CartesianIndex` otherwise. The +launch is asynchronous like any other, and bounds checks are not elided. + +Because the body becomes a kernel, every value it captures must have a known type — which is why +the example wraps the loop in a function, and why the body must not assign to a captured variable. +Write the kernel out with [`@kernel`](@ref) when it needs more than an index: workgroup-level +indices, local memory, or synchronization. diff --git a/src/KernelAbstractions.jl b/src/KernelAbstractions.jl index c7c9c5504..dca8dda3e 100644 --- a/src/KernelAbstractions.jl +++ b/src/KernelAbstractions.jl @@ -6,6 +6,7 @@ export @index, @groupsize, @ndrange export @print export Backend, CPU export synchronize, get_backend, allocate +export foreach_index import PrecompileTools @@ -614,6 +615,7 @@ end include("macros.jl") include("spawn.jl") +include("foreach_index.jl") ### # Backends/Interface diff --git a/src/foreach_index.jl b/src/foreach_index.jl new file mode 100644 index 000000000..2e0621837 --- /dev/null +++ b/src/foreach_index.jl @@ -0,0 +1,75 @@ +# One work item per index of a collection. +# +# The index space is carried by the `ndrange`, so the kernels take no argument besides the +# function: `@index(Global, Cartesian)` already returns the index of the `ndrange`, including +# the offset of an index space that does not start at 1. +# +# `f` is inlined on purpose: an out-of-line call to a closure can spill its captures to local +# memory on some backends. + +@kernel function foreach_index_linear_kernel(f) + I = @index(Global, Cartesian) + @inline f(I.I[1]) +end + +@kernel function foreach_index_cartesian_kernel(f) + I = @index(Global, Cartesian) + @inline f(I) +end + +# `eachindex` of an `AbstractArray` is either a range of linear indices or a `CartesianIndices`; +# hand `f` the index type that `itr` is indexed with in either case. +foreach_index_kernel(::AbstractUnitRange, backend) = foreach_index_linear_kernel(backend) +foreach_index_kernel(::CartesianIndices, backend) = foreach_index_cartesian_kernel(backend) +foreach_index_kernel(indices, backend) = throw( + ArgumentError( + "`foreach_index` needs an index space that is a range of linear indices or a `CartesianIndices`, got `$(typeof(indices))`" + ) +) + +""" + foreach_index(f, itr, backend = get_backend(itr); workgroupsize = nothing) + +Call `f(i)` once for every `i` in `eachindex(itr)`, with one work item per index. + +This is the kernel-free spelling of a `for` loop over the indices of a collection: the body is +an ordinary Julia function, so the same code runs on every backend. + +```julia +function scale!(y, x) + foreach_index(x) do i + @inbounds y[i] = 2 * x[i] + 1 + end + return y +end +``` + +`f` receives the same index that a `for i in eachindex(itr)` loop would: a linear index for an +array with `IndexLinear` style, a `CartesianIndex` otherwise. + +Like any other kernel launch this is asynchronous; call [`synchronize`](@ref) before reading the +result on the host. Bounds checks are not elided, so write `@inbounds` in the body where it is +warranted, as in a hand-written kernel. `workgroupsize` is passed on to the launch, and by +default the backend chooses it. + +# Extended help + +`f` becomes the body of a kernel, so it is subject to the same restrictions: every value it +captures must be of a known type. Closing over a variable of the enclosing *global* scope leaves +its type unknown and fails to compile (typically with `unsupported dynamic function invocation`), +which is why the example above wraps the loop in a function. + +For the same reason `f` must not assign to a captured variable, as that makes Julia box the +capture; accumulate into a one-element array, with an atomic update if the indices race. + +See also [`@kernel`](@ref) to write the kernel out, which is what to reach for when the body +needs more of the kernel language than an index (workgroup-level indices, local memory, or +synchronization). +""" +function foreach_index(f::F, itr, backend::Backend = get_backend(itr); workgroupsize = nothing) where {F} + indices = eachindex(itr) + isempty(indices) && return nothing + kernel = foreach_index_kernel(indices, backend) + kernel(f; ndrange = indices, workgroupsize) + return nothing +end diff --git a/test/foreach_index.jl b/test/foreach_index.jl new file mode 100644 index 000000000..890feee40 --- /dev/null +++ b/test/foreach_index.jl @@ -0,0 +1,141 @@ +using KernelAbstractions +using KernelAbstractions: @atomic +using Adapt +using Test + +# An `IndexLinear` array whose `axes1` does not start at 1, so that `eachindex` returns a +# range of linear indices with an offset. +struct OffsetVec{T, A <: AbstractVector{T}} <: AbstractVector{T} + data::A + r::Base.IdentityUnitRange{UnitRange{Int}} +end +OffsetVec(data::AbstractVector, off::Int) = OffsetVec(data, Base.IdentityUnitRange((1 + off):(length(data) + off))) +Base.size(v::OffsetVec) = size(v.data) +Base.axes(v::OffsetVec) = (v.r,) +Base.IndexStyle(::Type{<:OffsetVec}) = IndexLinear() +Base.@propagate_inbounds Base.getindex(v::OffsetVec, i::Int) = v.data[i - first(v.r) + 1] +Base.@propagate_inbounds Base.setindex!(v::OffsetVec, x, i::Int) = (v.data[i - first(v.r) + 1] = x) +KernelAbstractions.get_backend(v::OffsetVec) = KernelAbstractions.get_backend(v.data) +Adapt.adapt_structure(to, v::OffsetVec) = OffsetVec(adapt(to, v.data), v.r) + +# The loop bodies live in functions so that their captures have known types, as the +# `foreach_index` docstring requires. + +function foreach_index_copy!(dst, src) + foreach_index(src) do i + @inbounds dst[i] = src[i] + end + return dst +end + +function foreach_index_copy_backend!(dst, src, backend) + foreach_index(src, backend) do i + @inbounds dst[i] = src[i] + end + return dst +end + +function foreach_index_copy_workgroupsize!(dst, src, workgroupsize) + foreach_index(src; workgroupsize) do i + @inbounds dst[i] = src[i] + end + return dst +end + +function foreach_index_fill_index!(v) + foreach_index(v) do i + @inbounds v[i] = i + end + return v +end + +function foreach_index_mark!(out, itr) + foreach_index(itr) do I + @inbounds out[I] += 1 + end + return out +end + +function foreach_index_sum_range!(out, range, backend) + foreach_index(range, backend) do i + @inbounds @atomic out[1] += i + end + return out +end + +function foreach_index_testsuite(Backend, AT) + backend = Backend() + + @testset "linear index space" begin + @testset "$(length(dims))-D" for dims in ((1024,), (32, 33), (4, 5, 6)) + src = AT(reshape(collect(1:prod(dims)), dims)) + dst = AT(zeros(Int, dims)) + @test foreach_index_copy!(dst, src) === dst + synchronize(backend) + @test Array(dst) == Array(src) + + # every index is visited exactly once + out = AT(zeros(Int, dims)) + foreach_index_mark!(out, src) + synchronize(backend) + @test all(isone, Array(out)) + end + end + + @testset "cartesian index space" begin + A = AT(zeros(Int, 8, 10)) + v = view(A, 1:2:8, 2:2:10) + @test eachindex(v) isa CartesianIndices + foreach_index_mark!(v, v) + synchronize(backend) + ref = zeros(Int, 8, 10) + ref[1:2:8, 2:2:10] .= 1 + @test Array(A) == ref + end + + @testset "offset linear index space" begin + v = OffsetVec(AT(zeros(Int, 10)), -3) + @test eachindex(v) == -2:7 + foreach_index_fill_index!(v) + synchronize(backend) + @test Array(v.data) == collect(-2:7) + end + + @testset "index space without device memory" begin + # a range carries no backend of its own, so it has to be given + out = AT(zeros(Int, 1)) + foreach_index_sum_range!(out, 1:100, backend) + synchronize(backend) + @test Array(out)[1] == sum(1:100) + end + + @testset "workgroupsize" begin + src = AT(collect(1:1000)) + dst = AT(zeros(Int, 1000)) + foreach_index_copy_workgroupsize!(dst, src, 8) + synchronize(backend) + @test Array(dst) == Array(src) + end + + @testset "explicit backend" begin + src = AT(collect(1:100)) + dst = AT(zeros(Int, 100)) + foreach_index_copy_backend!(dst, src, backend) + synchronize(backend) + @test Array(dst) == Array(src) + end + + @testset "empty index space" begin + src = AT(Int[]) + dst = AT(Int[]) + @test foreach_index_copy!(dst, src) === dst + synchronize(backend) + @test isempty(Array(dst)) + end + + @testset "errors" begin + # an index space that is neither linear nor cartesian + @test_throws ArgumentError foreach_index(identity, Dict(1 => 2), backend) + end + return +end diff --git a/test/testsuite.jl b/test/testsuite.jl index 2e3d2ae10..1ce7e703d 100644 --- a/test/testsuite.jl +++ b/test/testsuite.jl @@ -35,6 +35,7 @@ include("unroll.jl") include("nditeration.jl") include("offsets.jl") include("launch.jl") +include("foreach_index.jl") include("copyto.jl") include("devices.jl") include("print_test.jl") @@ -85,6 +86,10 @@ function testsuite(backend, backend_str, backend_mod, AT, DAT; skip_tests = Set{ launch_testsuite(backend, AT; skip_tests) end + @conditional_testset "foreach_index" skip_tests begin + foreach_index_testsuite(backend, AT) + end + @conditional_testset "copyto!" skip_tests begin copyto_testsuite(backend, AT) end From e3a8813d80b799fb24f083e136117766e31be8b7 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sat, 3 Oct 2026 17:18:49 +0200 Subject: [PATCH 3/8] Give foreach_index an explicit index-space form `foreach_index(f, itr, backend)` called `f` with `eachindex(itr)`, which is what one wants for an array, but for an index space rebases it: `foreach_index(f, 5:10, backend)` called `f(1:6)`, and the interior `CartesianIndices((2:n-1, 2:m-1))` of an array got rebased to start at 1. Split the two: `foreach_index(f, A)` loops over `eachindex(A)` on the backend of `A`, and `foreach_index(f, backend, indices)` over the given range or `CartesianIndices`, as an `ndrange` does. Other index spaces, including stepped ranges, are rejected also when they're empty. --- docs/src/index.md | 3 +- docs/src/kernels.md | 23 ++++++++++--- src/foreach_index.jl | 80 +++++++++++++++++++++++++++++-------------- test/foreach_index.jl | 60 +++++++++++++++++++++++++++++--- 4 files changed, 131 insertions(+), 35 deletions(-) diff --git a/docs/src/index.md b/docs/src/index.md index 473aba615..4105c5430 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -153,7 +153,8 @@ end - The `CPU` backend runs kernels on as many threads as Julia was started with (`julia -t`), like the thread-based `CPU` backend of 0.9 did, and no longer on one thread per hardware thread. Set `JULIA_KA_CPU_THREADS` to use a different number of threads; see [`CPU`](@ref). -- `foreach_index(f, itr)` runs `f` once per index of `itr` without writing a kernel out. +- `foreach_index(f, A)` runs `f` once per index of the array `A` without writing a kernel out, + and `foreach_index(f, backend, indices)` once per index in a range or `CartesianIndices`. ## Semantic differences diff --git a/docs/src/kernels.md b/docs/src/kernels.md index 0f8b2802b..1c961ab5a 100644 --- a/docs/src/kernels.md +++ b/docs/src/kernels.md @@ -260,22 +260,37 @@ See the [Quickstart](@ref) for a full walkthrough and the Examples section of th A kernel whose body is a loop over the indices of an array needs none of the kernel language beyond the index itself. [`foreach_index`](@ref) launches such a loop directly, with one work item -per index of `eachindex(itr)`: +per index of `eachindex(A)`: ```julia function scale!(y, x) - foreach_index(x) do i + foreach_index(y) do i @inbounds y[i] = 2 * x[i] + 1 end return y end ``` -The body is an ordinary Julia function, and it receives the index a `for i in eachindex(itr)` loop +The body is an ordinary Julia function, and it receives the index a `for i in eachindex(y)` loop would: a linear index for an array with `IndexLinear` style, a `CartesianIndex` otherwise. The launch is asynchronous like any other, and bounds checks are not elided. +To loop over other indices than those of an array, give the backend and the index space, a range +or a `CartesianIndices` like an `ndrange`. The body then receives these indices as they are, +e.g. those of the interior of a matrix: + +```julia +function smooth!(B, A) + interior = CartesianIndices((2:size(A, 1)-1, 2:size(A, 2)-1)) + foreach_index(get_backend(A), interior) do I + i, j = Tuple(I) + @inbounds B[I] = (A[i-1, j] + A[i+1, j] + A[i, j-1] + A[i, j+1]) / 4 + end + return B +end +``` + Because the body becomes a kernel, every value it captures must have a known type — which is why -the example wraps the loop in a function, and why the body must not assign to a captured variable. +the examples wrap the loop in a function, and why the body must not assign to a captured variable. Write the kernel out with [`@kernel`](@ref) when it needs more than an index: workgroup-level indices, local memory, or synchronization. diff --git a/src/foreach_index.jl b/src/foreach_index.jl index 2e0621837..d6f98f2f4 100644 --- a/src/foreach_index.jl +++ b/src/foreach_index.jl @@ -1,4 +1,4 @@ -# One work item per index of a collection. +# One work item per index of an index space. # # The index space is carried by the `ndrange`, so the kernels take no argument besides the # function: `@index(Global, Cartesian)` already returns the index of the `ndrange`, including @@ -9,7 +9,7 @@ @kernel function foreach_index_linear_kernel(f) I = @index(Global, Cartesian) - @inline f(I.I[1]) + @inline f(I[1]) end @kernel function foreach_index_cartesian_kernel(f) @@ -17,59 +17,87 @@ end @inline f(I) end -# `eachindex` of an `AbstractArray` is either a range of linear indices or a `CartesianIndices`; -# hand `f` the index type that `itr` is indexed with in either case. -foreach_index_kernel(::AbstractUnitRange, backend) = foreach_index_linear_kernel(backend) -foreach_index_kernel(::CartesianIndices, backend) = foreach_index_cartesian_kernel(backend) -foreach_index_kernel(indices, backend) = throw( +# The index spaces an `ndrange` can express: a range of integers, or a product of them. +const UnitCartesianIndices{N} = CartesianIndices{N, <:NTuple{N, AbstractUnitRange{Int}}} + +foreach_index_kernel(backend, ::AbstractUnitRange{<:Integer}) = foreach_index_linear_kernel(backend) +foreach_index_kernel(backend, ::UnitCartesianIndices) = foreach_index_cartesian_kernel(backend) +foreach_index_kernel(backend, indices) = throw( ArgumentError( - "`foreach_index` needs an index space that is a range of linear indices or a `CartesianIndices`, got `$(typeof(indices))`" + "`foreach_index` needs an index space that is a range of integers or a `CartesianIndices` of such ranges, got a `$(typeof(indices))`" ) ) """ - foreach_index(f, itr, backend = get_backend(itr); workgroupsize = nothing) + foreach_index(f, A::AbstractArray) + foreach_index(f, backend::Backend, indices) -Call `f(i)` once for every `i` in `eachindex(itr)`, with one work item per index. +Call `f(i)` once for every index `i` of the array `A`, or for every index `i` in `indices`, +with one work item per index. Returns `nothing`; the iterations run asynchronously. -This is the kernel-free spelling of a `for` loop over the indices of a collection: the body is -an ordinary Julia function, so the same code runs on every backend. +This is a `for` loop over indices without a kernel to write out: the body is an ordinary Julia +function, which becomes the body of a kernel. ```julia function scale!(y, x) - foreach_index(x) do i + foreach_index(y) do i @inbounds y[i] = 2 * x[i] + 1 end return y end + +scale!(y, x) +synchronize(get_backend(y)) ``` -`f` receives the same index that a `for i in eachindex(itr)` loop would: a linear index for an -array with `IndexLinear` style, a `CartesianIndex` otherwise. +The first form runs on the backend of `A`, over `eachindex(A)`: `f` receives the index that a +`for i in eachindex(A)` loop would, a linear index if `A` has `IndexLinear` style and a +`CartesianIndex` otherwise. + +The second form runs on `backend`, over the given `indices`: a range of integers such as +`1:n` or `axes(A, 2)`, for which `f` receives an `Int`, or a `CartesianIndices` of such ranges, +for which `f` receives a `CartesianIndex`. Indices that do not start at 1 are passed on as +they are, so this iterates, e.g., the interior of a 2-D array `A`: -Like any other kernel launch this is asynchronous; call [`synchronize`](@ref) before reading the -result on the host. Bounds checks are not elided, so write `@inbounds` in the body where it is -warranted, as in a hand-written kernel. `workgroupsize` is passed on to the launch, and by -default the backend chooses it. +```julia +foreach_index(get_backend(A), CartesianIndices((2:size(A, 1)-1, 2:size(A, 2)-1))) do I + ... +end +``` + +The iterations run concurrently and in no particular order, so they must not race on the +same memory. The value `f` returns is ignored. Like any other kernel launch, `foreach_index` +returns before the iterations have finished: call [`synchronize`](@ref) before reading their +results on the host. Bounds checks are not elided, so write `@inbounds` in the body where it is +warranted, as in a hand-written kernel. + +The keyword argument `workgroupsize` sets the workgroup size of the launch; by default the +backend chooses it. # Extended help -`f` becomes the body of a kernel, so it is subject to the same restrictions: every value it -captures must be of a known type. Closing over a variable of the enclosing *global* scope leaves -its type unknown and fails to compile (typically with `unsupported dynamic function invocation`), -which is why the example above wraps the loop in a function. +`f` is subject to the same restrictions as a kernel: every value it captures must be of a known +type. Closing over a variable of the enclosing *global* scope leaves its type unknown and fails +to compile (typically with `unsupported dynamic function invocation`), which is why the example +above wraps the loop in a function. For the same reason `f` must not assign to a captured variable, as that makes Julia box the capture; accumulate into a one-element array, with an atomic update if the indices race. +On the `CPU` backend `foreach_index` also launches a kernel, compiled for every new `f`. For a +loop that runs once, or over few indices, a threaded loop (`Threads.@threads`) is cheaper. + See also [`@kernel`](@ref) to write the kernel out, which is what to reach for when the body needs more of the kernel language than an index (workgroup-level indices, local memory, or synchronization). """ -function foreach_index(f::F, itr, backend::Backend = get_backend(itr); workgroupsize = nothing) where {F} - indices = eachindex(itr) +function foreach_index(f::F, backend::Backend, indices; workgroupsize = nothing) where {F} + kernel = foreach_index_kernel(backend, indices) isempty(indices) && return nothing - kernel = foreach_index_kernel(indices, backend) kernel(f; ndrange = indices, workgroupsize) return nothing end + +function foreach_index(f::F, A::AbstractArray; workgroupsize = nothing) where {F} + return foreach_index(f, get_backend(A), eachindex(A); workgroupsize) +end diff --git a/test/foreach_index.jl b/test/foreach_index.jl index 890feee40..344da9a0b 100644 --- a/test/foreach_index.jl +++ b/test/foreach_index.jl @@ -29,7 +29,7 @@ function foreach_index_copy!(dst, src) end function foreach_index_copy_backend!(dst, src, backend) - foreach_index(src, backend) do i + foreach_index(backend, eachindex(src)) do i @inbounds dst[i] = src[i] end return dst @@ -57,12 +57,21 @@ function foreach_index_mark!(out, itr) end function foreach_index_sum_range!(out, range, backend) - foreach_index(range, backend) do i + foreach_index(backend, range) do i @inbounds @atomic out[1] += i end return out end +# Record every index of the index space `indices` in `out`, an array indexed from 1. +function foreach_index_record!(out, backend, indices; workgroupsize = nothing) + offset = first(indices) - oneunit(first(indices)) + foreach_index(backend, indices; workgroupsize) do I + @inbounds out[I - offset] = I + end + return out +end + function foreach_index_testsuite(Backend, AT) backend = Backend() @@ -109,6 +118,35 @@ function foreach_index_testsuite(Backend, AT) @test Array(out)[1] == sum(1:100) end + @testset "index space as given" begin + # the values of the index space, not its own indices + @testset "$(indices)" for indices in ( + 5:20, -3:4, Base.IdentityUnitRange(-3:4), Int32(2):Int32(9), UInt(2):UInt(9), + ) + out = AT(zeros(Int, length(indices))) + foreach_index_record!(out, backend, indices) + synchronize(backend) + @test Array(out) == collect(indices) + end + + # e.g. the interior of an array, with default and explicit workgroup sizes + @testset "$(indices), workgroupsize=$(workgroupsize)" for indices in ( + CartesianIndices((2:9, 2:7)), CartesianIndices((-1:3, 0:0, 4:6)), + ), workgroupsize in (nothing, 4, (4, 4)) + out = AT(fill(CartesianIndex(ntuple(_ -> 0, ndims(indices))), size(indices))) + foreach_index_record!(out, backend, indices; workgroupsize) + synchronize(backend) + @test Array(out) == collect(indices) + end + + # indices beyond the range of `Int32` + indices = (typemax(Int32) + 1):(typemax(Int32) + 10) + out = AT(zeros(Int, 10)) + foreach_index_record!(out, backend, indices) + synchronize(backend) + @test Array(out) == collect(indices) + end + @testset "workgroupsize" begin src = AT(collect(1:1000)) dst = AT(zeros(Int, 1000)) @@ -131,11 +169,25 @@ function foreach_index_testsuite(Backend, AT) @test foreach_index_copy!(dst, src) === dst synchronize(backend) @test isempty(Array(dst)) + + out = AT(zeros(Int, 1)) + foreach_index_sum_range!(out, 5:4, backend) + foreach_index_record!(out, backend, CartesianIndices((1:2, 3:2))) + synchronize(backend) + @test Array(out) == [0] end @testset "errors" begin - # an index space that is neither linear nor cartesian - @test_throws ArgumentError foreach_index(identity, Dict(1 => 2), backend) + # index spaces that an `ndrange` cannot express, also when they are empty + @test_throws ArgumentError foreach_index(identity, backend, [1, 2, 3]) + @test_throws ArgumentError foreach_index(identity, backend, Int[]) + @test_throws ArgumentError foreach_index(identity, backend, 1:2:9) + @test_throws ArgumentError foreach_index(identity, backend, CartesianIndices((1:2:9, 1:3))) + @test_throws ArgumentError foreach_index(identity, backend, CartesianIndices((1:2:1, 1:3))) + @test_throws ArgumentError foreach_index(identity, backend, Dict(1 => 2)) + + # a collection that is not an array has no backend, and needs the second form + @test_throws MethodError foreach_index(identity, (1, 2, 3)) end return end From 5e190602f8f66b25c820d3a4c31e9667bf63bddd Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sat, 3 Oct 2026 17:19:25 +0200 Subject: [PATCH 4/8] Accept several arrays in foreach_index A loop body usually indexes more than one array with the same index. `foreach_index(f, A, Bs...)` loops over `eachindex(A, Bs...)`, as a `for` loop would, so that the index is valid for all of them, and Cartesian if any of them needs it. The arrays must share a backend. --- docs/src/kernels.md | 12 +++++++----- src/foreach_index.jl | 25 +++++++++++++++++-------- test/foreach_index.jl | 29 ++++++++++++++++++++++++++++- 3 files changed, 52 insertions(+), 14 deletions(-) diff --git a/docs/src/kernels.md b/docs/src/kernels.md index 1c961ab5a..5d6df509f 100644 --- a/docs/src/kernels.md +++ b/docs/src/kernels.md @@ -260,20 +260,22 @@ See the [Quickstart](@ref) for a full walkthrough and the Examples section of th A kernel whose body is a loop over the indices of an array needs none of the kernel language beyond the index itself. [`foreach_index`](@ref) launches such a loop directly, with one work item -per index of `eachindex(A)`: +per index of `eachindex(y, x)`: ```julia function scale!(y, x) - foreach_index(y) do i + foreach_index(y, x) do i @inbounds y[i] = 2 * x[i] + 1 end return y end ``` -The body is an ordinary Julia function, and it receives the index a `for i in eachindex(y)` loop -would: a linear index for an array with `IndexLinear` style, a `CartesianIndex` otherwise. The -launch is asynchronous like any other, and bounds checks are not elided. +The body is an ordinary Julia function, and it receives the index a `for i in eachindex(y, x)` +loop would: a linear index if the arrays have `IndexLinear` style, a `CartesianIndex` otherwise. +Passing every array the body indexes makes sure the index is valid for each, and that they all +live on the same backend. The launch is asynchronous like any other, and bounds checks are not +elided. To loop over other indices than those of an array, give the backend and the index space, a range or a `CartesianIndices` like an `ndrange`. The body then receives these indices as they are, diff --git a/src/foreach_index.jl b/src/foreach_index.jl index d6f98f2f4..db48af0c1 100644 --- a/src/foreach_index.jl +++ b/src/foreach_index.jl @@ -29,10 +29,10 @@ foreach_index_kernel(backend, indices) = throw( ) """ - foreach_index(f, A::AbstractArray) + foreach_index(f, A::AbstractArray, Bs::AbstractArray...) foreach_index(f, backend::Backend, indices) -Call `f(i)` once for every index `i` of the array `A`, or for every index `i` in `indices`, +Call `f(i)` once for every index `i` of the arrays `A, Bs...`, or for every index `i` in `indices`, with one work item per index. Returns `nothing`; the iterations run asynchronously. This is a `for` loop over indices without a kernel to write out: the body is an ordinary Julia @@ -40,7 +40,7 @@ function, which becomes the body of a kernel. ```julia function scale!(y, x) - foreach_index(y) do i + foreach_index(y, x) do i @inbounds y[i] = 2 * x[i] + 1 end return y @@ -50,9 +50,10 @@ scale!(y, x) synchronize(get_backend(y)) ``` -The first form runs on the backend of `A`, over `eachindex(A)`: `f` receives the index that a -`for i in eachindex(A)` loop would, a linear index if `A` has `IndexLinear` style and a -`CartesianIndex` otherwise. +The first form runs on the backend of the arrays, which must all have the same one, over +`eachindex(A, Bs...)`: `f` receives the index that a `for i in eachindex(A, Bs...)` loop would, +a linear index if the arrays have `IndexLinear` style and a `CartesianIndex` otherwise. Pass +every array that the body indexes with `i`, so that the index is valid for each of them. The second form runs on `backend`, over the given `indices`: a range of integers such as `1:n` or `axes(A, 2)`, for which `f` receives an `Int`, or a `CartesianIndices` of such ranges, @@ -98,6 +99,14 @@ function foreach_index(f::F, backend::Backend, indices; workgroupsize = nothing) return nothing end -function foreach_index(f::F, A::AbstractArray; workgroupsize = nothing) where {F} - return foreach_index(f, get_backend(A), eachindex(A); workgroupsize) +function foreach_index(f::F, A::AbstractArray, Bs::AbstractArray...; workgroupsize = nothing) where {F} + backend = get_backend(A) + for B in Bs + get_backend(B) == backend || throw( + ArgumentError( + "`foreach_index` needs arrays with the same backend, got a `$(typeof(A))` on $(backend) and a `$(typeof(B))` on $(get_backend(B))" + ) + ) + end + return foreach_index(f, backend, eachindex(A, Bs...); workgroupsize) end diff --git a/test/foreach_index.jl b/test/foreach_index.jl index 344da9a0b..fb087bba3 100644 --- a/test/foreach_index.jl +++ b/test/foreach_index.jl @@ -22,7 +22,7 @@ Adapt.adapt_structure(to, v::OffsetVec) = OffsetVec(adapt(to, v.data), v.r) # `foreach_index` docstring requires. function foreach_index_copy!(dst, src) - foreach_index(src) do i + foreach_index(dst, src) do i @inbounds dst[i] = src[i] end return dst @@ -147,6 +147,33 @@ function foreach_index_testsuite(Backend, AT) @test Array(out) == collect(indices) end + @testset "several arrays" begin + # linear indices if all arrays have them + A = AT(collect(reshape(1:12, 3, 4))) + B = AT(zeros(Int, 3, 4)) + foreach_index_copy!(B, A) + synchronize(backend) + @test Array(B) == Array(A) + + # Cartesian indices otherwise + C = AT(zeros(Int, 6, 4)) + v = view(C, 1:2:6, :) + @test eachindex(v, A) isa CartesianIndices + foreach_index_copy!(v, A) + synchronize(backend) + @test Array(C)[1:2:6, :] == Array(A) + @test all(iszero, Array(C)[2:2:6, :]) + + # arrays whose indices differ + @test_throws DimensionMismatch foreach_index_copy!(AT(zeros(Int, 4, 3)), view(C, 1:2:6, :)) + + # arrays on different backends, or without one + if get_backend(AT(Int[])) != get_backend(Int[]) + @test_throws ArgumentError foreach_index_copy!(AT(zeros(Int, 3)), zeros(Int, 3)) + end + @test_throws ArgumentError foreach_index_copy!(AT(zeros(Int, 3)), Base.OneTo(3)) + end + @testset "workgroupsize" begin src = AT(collect(1:1000)) dst = AT(zeros(Int, 1000)) From 70f4be64682bf256b090e148ea91a6d0278e8dc6 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sat, 3 Oct 2026 17:19:53 +0200 Subject: [PATCH 5/8] Run foreach_index over a zero-dimensional index space A zero-dimensional `CartesianIndices` has a single index, but as an `ndrange` it cannot be combined with a workgroup size, which has at least one dimension. Launch it as a single work item instead, so that a `workgroupsize` works for every index space. --- src/foreach_index.jl | 12 +++++++++++- test/foreach_index.jl | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/foreach_index.jl b/src/foreach_index.jl index db48af0c1..c337a642b 100644 --- a/src/foreach_index.jl +++ b/src/foreach_index.jl @@ -17,17 +17,27 @@ end @inline f(I) end +# A zero-dimensional index space has a single index. Launched as a one-dimensional `ndrange`, as +# a workgroup size has at least one dimension. +@kernel function foreach_index_zerodim_kernel(f) + @inline f(CartesianIndex()) +end + # The index spaces an `ndrange` can express: a range of integers, or a product of them. const UnitCartesianIndices{N} = CartesianIndices{N, <:NTuple{N, AbstractUnitRange{Int}}} foreach_index_kernel(backend, ::AbstractUnitRange{<:Integer}) = foreach_index_linear_kernel(backend) foreach_index_kernel(backend, ::UnitCartesianIndices) = foreach_index_cartesian_kernel(backend) +foreach_index_kernel(backend, ::CartesianIndices{0}) = foreach_index_zerodim_kernel(backend) foreach_index_kernel(backend, indices) = throw( ArgumentError( "`foreach_index` needs an index space that is a range of integers or a `CartesianIndices` of such ranges, got a `$(typeof(indices))`" ) ) +foreach_index_ndrange(indices) = indices +foreach_index_ndrange(::CartesianIndices{0}) = 1 + """ foreach_index(f, A::AbstractArray, Bs::AbstractArray...) foreach_index(f, backend::Backend, indices) @@ -95,7 +105,7 @@ synchronization). function foreach_index(f::F, backend::Backend, indices; workgroupsize = nothing) where {F} kernel = foreach_index_kernel(backend, indices) isempty(indices) && return nothing - kernel(f; ndrange = indices, workgroupsize) + kernel(f; ndrange = foreach_index_ndrange(indices), workgroupsize) return nothing end diff --git a/test/foreach_index.jl b/test/foreach_index.jl index fb087bba3..af27c0a18 100644 --- a/test/foreach_index.jl +++ b/test/foreach_index.jl @@ -190,6 +190,23 @@ function foreach_index_testsuite(Backend, AT) @test Array(dst) == Array(src) end + @testset "zero-dimensional index space" begin + # a single index + @testset "workgroupsize=$(workgroupsize)" for workgroupsize in (nothing, 4) + out = AT(fill(CartesianIndex(1), 1)) + foreach_index(backend, CartesianIndices(()); workgroupsize) do I + @inbounds out[1] = CartesianIndex(length(I) + 2) + end + synchronize(backend) + @test Array(out) == [CartesianIndex(2)] + end + + A = AT(fill(1)) + foreach_index_fill_index!(A) + synchronize(backend) + @test Array(A)[] == 1 + end + @testset "empty index space" begin src = AT(Int[]) dst = AT(Int[]) From f0eedb64fe66df4fcf94bd648556da3413c08aac Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sat, 3 Oct 2026 17:21:27 +0200 Subject: [PATCH 6/8] Explain boxed captures in foreach_index A variable that is reassigned after a closure captures it is stored in a `Core.Box`, which a kernel cannot access, and compiling the kernel fails with an error about non-isbits kernel arguments that does not mention the variable. Check for boxed captures before launching, which is free for other closures, and name the variable in the error. --- src/foreach_index.jl | 32 ++++++++++++++++++++++++++++++-- test/foreach_index.jl | 6 ++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/foreach_index.jl b/src/foreach_index.jl index c337a642b..724b2dcc6 100644 --- a/src/foreach_index.jl +++ b/src/foreach_index.jl @@ -35,6 +35,31 @@ foreach_index_kernel(backend, indices) = throw( ) ) +# A captured variable that is assigned to after the closure was created, or in it, is stored in +# a `Core.Box`, which a kernel cannot access. That fails to compile with an error about the +# kernel's arguments, so catch it here with one about the variable. +@inline function check_captures(f::F) where {F} + has_box(fieldtypes(F)) && boxed_capture_error(f) + return +end + +# (`any` would not be folded by Julia 1.10) +has_box(::Tuple{}) = false +has_box(Ts::Tuple) = first(Ts) === Core.Box || has_box(Base.tail(Ts)) + +@noinline function boxed_capture_error(::F) where {F} + names = [fieldname(F, i) for i in 1:fieldcount(F) if fieldtype(F, i) === Core.Box] + vars = join(("`$name`" for name in names), ", ", " and ") + throw( + ArgumentError( + "`foreach_index` cannot run a function that captures a variable that is reassigned " * + "($vars): Julia stores such a variable in a box, which a kernel cannot access. " * + "Capture a variable that is not reassigned instead, e.g. by wrapping the loop in " * + "`let $(first(names)) = $(first(names))`, and write results to an array." + ) + ) +end + foreach_index_ndrange(indices) = indices foreach_index_ndrange(::CartesianIndices{0}) = 1 @@ -92,8 +117,10 @@ type. Closing over a variable of the enclosing *global* scope leaves its type un to compile (typically with `unsupported dynamic function invocation`), which is why the example above wraps the loop in a function. -For the same reason `f` must not assign to a captured variable, as that makes Julia box the -capture; accumulate into a one-element array, with an atomic update if the indices race. +For the same reason `f` cannot capture a variable that is assigned to after `f` is created, or +in `f`, as Julia then boxes the variable. Bind the value to a new variable (e.g. with `let`) +for `f` to capture, and accumulate results into an array, with an atomic update if the indices +race. On the `CPU` backend `foreach_index` also launches a kernel, compiled for every new `f`. For a loop that runs once, or over few indices, a threaded loop (`Threads.@threads`) is cheaper. @@ -104,6 +131,7 @@ synchronization). """ function foreach_index(f::F, backend::Backend, indices; workgroupsize = nothing) where {F} kernel = foreach_index_kernel(backend, indices) + check_captures(f) isempty(indices) && return nothing kernel(f; ndrange = foreach_index_ndrange(indices), workgroupsize) return nothing diff --git a/test/foreach_index.jl b/test/foreach_index.jl index af27c0a18..0d4554433 100644 --- a/test/foreach_index.jl +++ b/test/foreach_index.jl @@ -230,6 +230,12 @@ function foreach_index_testsuite(Backend, AT) @test_throws ArgumentError foreach_index(identity, backend, CartesianIndices((1:2:1, 1:3))) @test_throws ArgumentError foreach_index(identity, backend, Dict(1 => 2)) + # a function capturing a boxed variable + s = 1 + boxed = i -> s + s = 2 + @test_throws "reassigned (`s`)" foreach_index(boxed, backend, 1:3) + # a collection that is not an array has no backend, and needs the second form @test_throws MethodError foreach_index(identity, (1, 2, 3)) end From 18e2cc2b2659272170ae11505690394a2a50661d Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Sat, 3 Oct 2026 17:30:07 +0200 Subject: [PATCH 7/8] Use 32-bit atomics in the foreach_index tests Metal has no 64-bit atomic addition. --- test/foreach_index.jl | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/foreach_index.jl b/test/foreach_index.jl index 0d4554433..67707ef64 100644 --- a/test/foreach_index.jl +++ b/test/foreach_index.jl @@ -58,7 +58,7 @@ end function foreach_index_sum_range!(out, range, backend) foreach_index(backend, range) do i - @inbounds @atomic out[1] += i + @inbounds @atomic out[1] += i % eltype(out) end return out end @@ -112,7 +112,8 @@ function foreach_index_testsuite(Backend, AT) @testset "index space without device memory" begin # a range carries no backend of its own, so it has to be given - out = AT(zeros(Int, 1)) + # (32-bit atomics, as not every backend has 64-bit ones) + out = AT(zeros(Int32, 1)) foreach_index_sum_range!(out, 1:100, backend) synchronize(backend) @test Array(out)[1] == sum(1:100) @@ -214,7 +215,7 @@ function foreach_index_testsuite(Backend, AT) synchronize(backend) @test isempty(Array(dst)) - out = AT(zeros(Int, 1)) + out = AT(zeros(Int32, 1)) foreach_index_sum_range!(out, 5:4, backend) foreach_index_record!(out, backend, CartesianIndices((1:2, 3:2))) synchronize(backend) From 7f08f18cd945ff2da131ae9a8f2e9dbb540860c9 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Mon, 5 Oct 2026 17:44:00 +0200 Subject: [PATCH 8/8] Let ranges in foreach_index run on the backend of the other arrays `foreach_index(f, y, 1:n)` asked every array for its backend, and a range has none, so it failed with an error asking to implement `get_backend` for it, although a range can be indexed on any backend. Like AcceleratedKernels, let ranges, `CartesianIndices` and `LinearIndices`, and Base's views, reshapes and permutations of them, run on the backend of the other arrays. Unlike it, do not fall back to the host if there are no other arrays: ask for the backend instead. --- src/foreach_index.jl | 35 +++++++++++++++++++++++++++-------- test/foreach_index.jl | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/src/foreach_index.jl b/src/foreach_index.jl index 724b2dcc6..e029fdfd8 100644 --- a/src/foreach_index.jl +++ b/src/foreach_index.jl @@ -88,7 +88,9 @@ synchronize(get_backend(y)) The first form runs on the backend of the arrays, which must all have the same one, over `eachindex(A, Bs...)`: `f` receives the index that a `for i in eachindex(A, Bs...)` loop would, a linear index if the arrays have `IndexLinear` style and a `CartesianIndex` otherwise. Pass -every array that the body indexes with `i`, so that the index is valid for each of them. +every array that the body indexes with `i`, so that the index is valid for each of them. Ranges, +`CartesianIndices` and `LinearIndices`, and views or reshapes of them, have no backend and run +on that of the other arrays; if none of the arrays has a backend, use the second form. The second form runs on `backend`, over the given `indices`: a range of integers such as `1:n` or `axes(A, 2)`, for which `f` receives an `Int`, or a `CartesianIndices` of such ranges, @@ -137,14 +139,31 @@ function foreach_index(f::F, backend::Backend, indices; workgroupsize = nothing) return nothing end +# The backend of the arrays passed to `foreach_index`. Ranges, `CartesianIndices` and +# `LinearIndices` are computed rather than stored, as are Base's views, reshapes and permutations +# of them: they have no backend and do not decide the one the loop runs on. This is what +# AcceleratedKernels.jl does. +array_backend(A::AbstractArray) = get_backend(A) +array_backend(::Union{AbstractRange, CartesianIndices, LinearIndices}) = nothing +array_backend(A::Union{SubArray, Base.ReshapedArray, PermutedDimsArray}) = array_backend(parent(A)) + +common_backend() = nothing +common_backend(A, Bs...) = merge_backend(array_backend(A), common_backend(Bs...)) + +merge_backend(::Nothing, ::Nothing) = nothing +merge_backend(a, ::Nothing) = a +merge_backend(::Nothing, b) = b +function merge_backend(a, b) + a == b || throw(ArgumentError("`foreach_index` needs arrays with the same backend, got arrays on $a and on $b")) + return a +end + function foreach_index(f::F, A::AbstractArray, Bs::AbstractArray...; workgroupsize = nothing) where {F} - backend = get_backend(A) - for B in Bs - get_backend(B) == backend || throw( - ArgumentError( - "`foreach_index` needs arrays with the same backend, got a `$(typeof(A))` on $(backend) and a `$(typeof(B))` on $(get_backend(B))" - ) + backend = common_backend(A, Bs...) + backend === nothing && throw( + ArgumentError( + "`foreach_index` cannot determine a backend from arrays that are not stored, such as ranges; pass it explicitly, as in `foreach_index(f, backend, eachindex(A, Bs...))`" ) - end + ) return foreach_index(f, backend, eachindex(A, Bs...); workgroupsize) end diff --git a/test/foreach_index.jl b/test/foreach_index.jl index 67707ef64..725e96c06 100644 --- a/test/foreach_index.jl +++ b/test/foreach_index.jl @@ -28,6 +28,13 @@ function foreach_index_copy!(dst, src) return dst end +function foreach_index_copy_from_first!(src, dst) + foreach_index(src, dst) do i + @inbounds dst[i] = src[i] + end + return dst +end + function foreach_index_copy_backend!(dst, src, backend) foreach_index(backend, eachindex(src)) do i @inbounds dst[i] = src[i] @@ -168,11 +175,33 @@ function foreach_index_testsuite(Backend, AT) # arrays whose indices differ @test_throws DimensionMismatch foreach_index_copy!(AT(zeros(Int, 4, 3)), view(C, 1:2:6, :)) - # arrays on different backends, or without one + # arrays on different backends if get_backend(AT(Int[])) != get_backend(Int[]) @test_throws ArgumentError foreach_index_copy!(AT(zeros(Int, 3)), zeros(Int, 3)) end - @test_throws ArgumentError foreach_index_copy!(AT(zeros(Int, 3)), Base.OneTo(3)) + + # ranges, and views of them, run on the backend of the other arrays + for r in (Base.OneTo(3), 4:6, view(reshape(1:12, 3, 4), :, 2)) + dst = AT(zeros(Int, 3)) + foreach_index_copy!(dst, r) + synchronize(backend) + @test Array(dst) == collect(r) + end + dst = AT(zeros(Int, 2, 3)) + foreach_index_copy!(dst, reshape(1:6, 2, 3)) + synchronize(backend) + @test Array(dst) == reshape(1:6, 2, 3) + dst = AT(zeros(Int, 2, 3)) + foreach_index_copy!(dst, LinearIndices((2, 3))) + synchronize(backend) + @test Array(dst) == collect(LinearIndices((2, 3))) + # ... also as the first argument + dst = AT(zeros(Int, 3)) + foreach_index_copy_from_first!(2:4, dst) + synchronize(backend) + @test Array(dst) == 2:4 + # ... and need one if there are no other arrays + @test_throws "pass it explicitly" foreach_index_copy!(1:3, 4:6) end @testset "workgroupsize" begin