Add `foreach_index`, a parallel loop over indices without a kernel #827
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 70%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
maleadt
Supersedes #779. That PR is based on #772, which may not land, while it only needs the range
ndranges that are already onmain(#771). This branch keeps its commit, rebases it ontomain,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_indexlets you writethose as an ordinary function, without the kernel language:
fgets the index afor i in eachindex(y, x)loop would give: a linear index if all arrayssupport it, a
CartesianIndexotherwise. It runs on the backend of the arrays, which must all bethe 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
ndrangeworks:Like every other launch it's asynchronous and returns
nothing. Iterations run in no particularorder. Bounds checks stay on unless the body uses
@inbounds.Why
The function comes from AcceleratedKernels.jl, where
foreachindexis the primitive undermap,reduce,sort,accumulateand the others. Moving it into KA gives users the convenient formwithout 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 onCUDA: everything passes. Two bodies had to add
@inbounds, since they relied on AK's kernel beinginbounds=true. AK keeps its own publicforeachindex, with its host-threads path and schedulingkeywords. 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)withget_backend(itr)as default. For arrays that's right, but for index spaces it isn't:foreach_index(f, 5:10, backend)calledf(1)throughf(6), and a stencil interiorCartesianIndices((2:n-1, 2:m-1))got rebased to start at 1. AK needs the given indices for itsown call sites (e.g. a
CartesianIndicesover offset axes inaccumulate, andaxes(x, d)). Thetwo 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
CartesianIndiceshas no backend, soforeach_index(f, 5:10)is an error, not asilent loop over
1:6. Only unit ranges of integers andCartesianIndicesof 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'sndrange, JACC. SYCL, CUB and Warp onlysupport
[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 ifany of them needs it.
Zero-dimensional index spaces run as a single work item. An explicit
workgroupsizefailed anassertion 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 argumentand 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 ofI.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'sthe 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
mainthat #779 ran into. A kernel launched with a range orCartesianIndicesas itsndrange(#771) and no workgroup size threwMethodError: normalize_workgroupsize(::OneTo): the launch uses the ndrange as a preliminaryworkgroup size before tuning. The #771 tests always passed a workgroup size, so they missed this.
The launch now uses the extents, as
Intalso for unsigned ranges.Testing
The
foreach_indexand 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.10branches merged with theirLLVM.jl 10 ports.
Performance matches a hand-written
@kerneleverywhere, since it is one. Median time per launchplus 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
CartesianIndicesdirectly beats AK's linear launch with anindex 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
@kernelsees the same difference, and AKpasses its own workgroup size anyway.
On the CPU backend it also matches a
@kernel. Each new closure costs about 150 ms to compile, andbelow roughly a million elements
Threads.@threadsis 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
foreach_indexavoids clashing with AK's exportedforeachindex, which hasdifferent semantics (synchronous host threads, scheduling keywords).
foreachindexwould readmore like
eachindex.