← Back to Pull requests

Add `foreach_index`, a parallel loop over indices without a kernel #827

Closed
unknown closed this pull request without merging on Oct 05, 2026 16:59 UTC
View on GitHub
unknown unknown commented on Oct 03, 2026 16:02 UTC
Author

Supersedes #779. That PR is based on #772, which may not land, while it only needs the range
ndranges that are already on main (#771). This branch keeps its commit, rebases it onto main,
and builds on it, mainly to change the semantics for index spaces; see
[Changes compared to #779](#changes-compared-to-779) below.

Many kernels are just a loop body over the indices of some arrays. foreach_index lets you write
those as an ordinary function, without the kernel language:

function scale!(y, x)
    foreach_index(y, x) do i
        @inbounds y[i] = 2 * x[i] + 1
    end
    return y
end

f gets the index a for i in eachindex(y, x) loop would give: a linear index if all arrays
support it, a CartesianIndex otherwise. It runs on the backend of the arrays, which must all be
the same.

To loop over something other than the indices of an array, pass a backend and an index space. The
indices are used as they are, offsets included, the same way an ndrange works:

foreach_index(get_backend(A), CartesianIndices((2:n-1, 2:m-1))) do I
    # the interior of A
end

Like every other launch it's asynchronous and returns nothing. Iterations run in no particular
order. Bounds checks stay on unless the body uses @inbounds.

Why

The function comes from AcceleratedKernels.jl, where foreachindex is the primitive under map,
reduce, sort, accumulate and the others. Moving it into KA gives users the convenient form
without pulling in AK, and lets AK use KA's version for its GPU path instead of maintaining its
own kernel.

I checked that last point by swapping AK's GPU kernel for
KA.foreach_index(f, backend, indices; workgroupsize=block_size) and running AK's test suite on
CUDA: everything passes. Two bodies had to add @inbounds, since they relied on AK's kernel being
inbounds=true. AK keeps its own public foreachindex, with its host-threads path and scheduling
keywords. It can only depend on this once it requires KA 0.10.

Changes compared to #779

An index-space form with an explicit backend. #779 ran over eachindex(itr) with
get_backend(itr) as default. For arrays that's right, but for index spaces it isn't:
foreach_index(f, 5:10, backend) called f(1) through f(6), and a stencil interior
CartesianIndices((2:n-1, 2:m-1)) got rebased to start at 1. AK needs the given indices for its
own call sites (e.g. a CartesianIndices over offset axes in accumulate, and axes(x, d)). The
two meanings are now two methods:

  • foreach_index(f, A, Bs...): the indices of these arrays, on their backend.

  • foreach_index(f, backend, indices): these indices, on this backend.
  • A range or CartesianIndices has no backend, so foreach_index(f, 5:10) is an error, not a
    silent loop over 1:6. Only unit ranges of integers and CartesianIndices of those are accepted.
    Anything else, including stepped ranges, throws an ArgumentError, also when it's empty.

    Most frameworks I looked at that accept a begin and end pass the actual indices: Kokkos'
    RangePolicy/MDRangePolicy, RAJA segments, Taichi's ndrange, JACC. SYCL, CUB and Warp only
    support [0, N).

    Several arrays. A loop body almost always indexes more than one array, so the array form takes
    several, like eachindex(A, B...). That makes the index valid for all of them, and Cartesian if
    any of them needs it.

    Zero-dimensional index spaces run as a single work item. An explicit workgroupsize failed an
    assertion otherwise, and AK always passes one.

    Boxed captures get a useful error. Capturing a variable that is reassigned (a common mistake
    for people new to GPU programming) used to fail with KernelError: passing non-bitstype argument
    and a page of kernel types. Now it says which variable it is and how to fix it. The check
    constant-folds away for other closures, also on Julia 1.10.

    Smaller things. I[1] instead of I.I[1]. A docstring that leads with the asynchronous,
    unordered semantics, and notes that on the CPU backend each new closure means a kernel compile.
    The tests use 32-bit atomics, because Metal has no 64-bit atomic add.

    I didn't take the review suggestion to use @index(Global, Linear) in the linear kernel: that's
    the position in the ndrange, which loses the offset of a range that doesn't start at 1.

    A launch fix

    The first commit fixes a bug on main that #779 ran into. A kernel launched with a range or
    CartesianIndices as its ndrange (#771) and no workgroup size threw
    MethodError: normalize_workgroupsize(::OneTo): the launch uses the ndrange as a preliminary
    workgroup size before tuning. The #771 tests always passed a workgroup size, so they missed this.
    The launch now uses the extents, as Int also for unsigned ranges.

    Testing

    The foreach_index and offset tests pass on CPU (PoCL), CUDA, AMDGPU (a gfx1036 iGPU), OpenCL
    (PoCL and NVIDIA), Metal (M1) and oneAPI (Iris Xe). The full suite passes on CPU, and KA's full
    testsuite on CUDA. The GPU back-ends were tested with their ka-0.10 branches merged with their
    LLVM.jl 10 ports.

    Performance matches a hand-written @kernel everywhere, since it is one. Median time per launch
    plus synchronization, for y[i] = 2x[i] + 1:

    | | 2^24 elements | strided 2-D view |
    |---|---|---|
    | CUDA (RTX 5080) | 165 µs, same as broadcast and @kernel | 530 µs (4096²), same as broadcast |
    | AMDGPU (iGPU) | 6.4 ms, same as @kernel; broadcast 6.7 ms | 2.4 ms (2048²); broadcast 3.3 ms |
    | Metal (M1) | 2.38 ms, same as broadcast and @kernel | 1.74 ms (2048²); AK's kernel 2.67 ms |
    | oneAPI (Iris Xe) | 7.2 ms, all variants within noise | 4.9 ms (2048²), all within noise |

    On strided views, launching over the CartesianIndices directly beats AK's linear launch with an
    index decode on Metal and AMDGPU, and matches it elsewhere. The one place AK's kernel came out
    ahead is large 1-D arrays on the AMD iGPU (6.15 vs 6.42 ms), which comes from its fixed workgroup
    size of 256 versus KA's tuned one. A hand-written @kernel sees the same difference, and AK
    passes its own workgroup size anyway.

    On the CPU backend it also matches a @kernel. Each new closure costs about 150 ms to compile, and
    below roughly a million elements Threads.@threads is faster (6.5 vs 20 µs for 64k elements),
    which is why the docstring points to threaded loops for one-off or small work.

    Open questions

  • The name. foreach_index avoids clashing with AK's exported foreachindex, which has

  • different semantics (synchronous host threads, scheduling keywords). foreachindex would read
    more like eachindex.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: maleadt Review duration: 2936m
    All Vouch review confidence checks passed
    Residual risk 0.19 = Change Risk (0.52) × (1 − Review Confidence (0.64)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 70%
    64%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #827"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 64% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 64% · Lower = rushed or shallow review
    64%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 18.7% · Safe to merge
    18.7%