Skip to content

Make indices zero-based first in the Horner linear index - #236

Draft
vchuravy wants to merge 2 commits into
mainfrom
vc/zero-based-horner-index
Draft

vchuravy wants to merge 2 commits into
mainfrom
vc/zero-based-horner-index

Conversation

@vchuravy

@vchuravy vchuravy commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Cartesian getindex/setindex! compute the linear index in Horner form as

i + n1 * ((j + n2 * (k - 1)) - 1)       # current: subtract one from the partial sums

This PR changes the association to

1 + (i - 1) + n1 * ((j - 1) + n2 * (k - 1))   # this PR: make each index zero-based first

The number of integer operations is the same, but starting with Julia v1.12 (LLVM 18) the loop vectorizer does not vectorize short loops over an index of a FixedSizeArray with the current form.

Measurements

Gather-form derivative kernel over a FixedSizeArrayDims with dimensions (Val(1), Val(4), Val(4), Val(4), n), minimum time in µs, x86-64 (Ryzen 9 5950X), one pinned core:

Julia v1.5.2 this PR
1.10 30 30
1.11 29 30
1.12 59 25
1.14 58 20

The same kernel with a hand-written wrapper type using either index form reproduces both columns, so the difference is the index expression and not something else in FixedSizeArray. A sum of strided terms (1 + (i - 1) + n1 * (j - 1) + ...) does not vectorize on 1.12/1.14 either.

In Trixi.jl (trixi-framework/Trixi.jl#3357, 3D p4est advection, Julia 1.14): rhs! 307–320 µs → 290–302 µs, interface flux 84–86 µs → 62–65 µs, volume integral 180–184 µs → 167–175 µs. One kernel (prolong2interfaces!) gets slower, 23 µs → 32 µs, because LLVM unrolls its node loop differently; that is fixable in the Trixi.jl kernel and independent of the index form otherwise.

Open points (hence draft)

  • The current form was chosen in Compute the linear index of Cartesian indexing in Horner form #217 for a 2.5–3.5% gain in Trixi.jl's flux differencing kernels over the strided sum. Flux differencing with this PR is unchanged within run-to-run noise (volume integral, min µs, v1.5.2 → this PR, Julia 1.14): tree_3d_dgsem/elixir_euler_ec.jl 1784 → 1760, p4est_3d_dgsem/elixir_euler_ec.jl 1110 → 1110, tree_2d_dgsem/elixir_euler_ec.jl 542–588 → 552–562, p4est_2d_dgsem/elixir_euler_shockcapturing_ec.jl 369 → 365. So for compressible Euler this PR is neutral; the gains above are for scalar advection.
  • Only measured on x86-64.
  • I have not identified which LLVM analysis distinguishes the two forms; the claim is from benchmarks and from counting packed vs. scalar FMAs in the native code.
  • The changelog entry will conflict with Adapt the memory backend of a FixedSizeArray for adaptors that are not array types #235 (both add an "Unreleased" section).

The existing test suite passes locally on Julia 1.14.

🤖 Generated with Claude Code

https://claude.ai/code/session_01HgDfyeGjfcC7cikr7MfRB3

The Cartesian linear index was computed as `i + n1 * ((j + n2 * (k - 1)) - 1)`,
subtracting one from the partial sums. With Julia v1.12 and newer (LLVM 18+),
the loop vectorizer does not vectorize short loops over an index of a
`FixedSizeArray` with this form. Computing the zero-based offset
`(i - 1) + n1 * ((j - 1) + n2 * (k - 1))` and adding one at the end has the
same number of integer operations and vectorizes.

Assisted-by: Claude Code (Fable 5.2)
@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.48%. Comparing base (ab67d3f) to head (be712be).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #236      +/-   ##
==========================================
+ Coverage   94.73%   95.48%   +0.74%     
==========================================
  Files           8        8              
  Lines         323      332       +9     
==========================================
+ Hits          306      317      +11     
+ Misses         17       15       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@giordano giordano left a comment

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.

Sounds like a FileCheck test would help?

…n element

Since Julia v1.13, with the zero-based Horner form of the Cartesian linear index
the loop vectorizer needs no runtime check that the index does not wrap
(`vector.scevcheck`) and no scalar fallback loop for short loops over the nodes
of an element.  These tests fail with the previous form of the index.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016cX3ig3MD9aPL8rgQRif5v
@giordano

Copy link
Copy Markdown
Member

Sounds like a FileCheck test would help?

I pushed a test, but the bot couldn't find a loop which solves the missed optimisation in Julia v1.12, apparently this is only solved in v1.13+

@giordano

giordano commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Also, this branch makes this test from #217

fc_run_bounds_check_elision_checks &&
@testset "elements along the first dimension share one offset: $(A)" for A in (FixedSizeArrayDefault{Float64, 4}, fc_node_val_dims_array)
# The offset of the node is computed once, before the first load, and the other
# variables are at constant offsets from it: no multiplication after the first load.
# (On Julia 1.11 the first two loads are one vector load.)
@test @filecheck begin
@check "define"
@check "load {{(<2 x )?}}double"
@check_not "{{mul|shl}}"
@check "ret double"
fc_llvm(fc_node_sum, (A, Int, Int, Int))
end
end
fail in Julia v1.12 with --check-bounds=auto (which is a combination we don't run here on CI). Compilers are fun 🫠

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants