Skip to content

perf(kernels): shift alignment, canonicalize on words, half norm2 - #71

Open
ondrik wants to merge 5 commits into
review/fix-guaranteesfrom
review/perf-kernels
Open

ondrik wants to merge 5 commits into
review/fix-guaranteesfrom
review/perf-kernels

Conversation

@ondrik

@ondrik ondrik commented Dec 2, 2026 •

Copy link
Copy Markdown

This is part 1 of 9 of the performance work from the code review tracked in #5 (issues #43–#55). It speeds up three core kernels: the scale alignment in add, sub and fma_into (#43), canonicalize (#45) and norm2 (#52). It is stacked on split-check/guarantees, the last of the fix PRs, so the fix PRs come first and this diff shows only these 5 commits. Please review and merge the PRs in stack order. The changes keep the fix PRs' contracts. The sticky overflow flag of a Checked result is set if and only if the result does not fit, and the words are the same as before even after an overflow. ACN_REQUIRE errors are unchanged. A throw from canonicalize leaves (c, k) unchanged (#18).

Fix PRs #58–#70 come first (this stack is based on #70).

# PR Base Fixes
1 #71 (this PR) #70 #43, #45, #52
2 #72 #71 #44, #55
3 #73 #72 #48
4 #74 #73 #53
5 #75 #74 #47
6 #76 #75 #46
7 #77 #76 #49, #50
8 #78 #77 #51
9 #79 #78 #54

How to merge this stack: see the merge guide (one at a time, in order, with "Create a merge commit", then delete the merged branch so the next PR retargets to main).

Issues

Measurements

The base is bdc6fb9, the head of the original fix branch; split-check/guarantees differs from it only in the tests of #68's fa2ec11. The tip is 88da72e (the combined branch this stack was split from; not pushed), the head of the whole performance stack. Both were built with GCC 15.2 -O3 -DNDEBUG and measured with perf stat -e instructions:u,cycles:u. Each workload is a separate binary, and the setup cost (a run with 0 iterations) is subtracted. The figures are medians of 5 interleaved base/tip runs. The machine is shared and loaded, so instruction counts are the primary metric and cycles the secondary one.

These are figures for the whole stack against bdc6fb9. Later PRs also touch add, from_coeffs and the BigInt path. The table shows only the rows of this PR's issues. Ratios are base/tip, so a value above 1× means the tip is faster.

Issue Workload (i64 = CheckedI64) Instructions per op, base → tip Instructions Cycles
#43 add Acn<4,i64>, k gap 2 / 6 / 20 237 / 337 / 701 → 128 1.85× / 2.63× / 5.48× 2.12× / 2.85× / 5.98×
#43 add AcnDyn<i64> n=16, k gap 20 2812 → 772 3.64× 3.92×
#43 1/sqrt2^1600000 + 1, Acn<4,BigInt> (whole program) 35.5e9 → 1.97e6 1.8·10⁴× 2.46 s → 1.9 ms (task-clock)
#45 canonicalize Acn<4,i64>, canonical / 2·√2·u input 103 / 232 → 47 / 196 2.19× / 1.18× 1.90× / 0.98×
#45 canonicalize Acn<16,i64>, canonical / 2·√2·u input 247 / 747 → 47 / 489 5.26× / 1.53× 4.85× / 1.22×
#45 from_coeffs Acn<4,i64> / Acn<16,i64> 176 / 611 → 62 / 183 2.82× / 3.33× 5.21× / 1.82×
#52 norm2 Acn<4,i64> / Acn<16,i64> / AcnDyn<i64> n=16 219 / 4193 / 4126 → 97 / 1364 / 2173 2.26× / 3.07× / 1.90× 2.25× / 3.30× / 1.79×

The whole-program row was measured before the rebase onto the fixes, at the pre-rebase commit 1daf50a. The commits after it do not touch the BigInt path of this program. The odd-gap add rows (Acn<8>/Acn<16>, k gap 1) belong to the fixed-N sqrt(2) step and are in the BigInt PR.

Each commit message gives before/after figures for that commit alone. These were measured with the same kind of fixed-work harness before the rebase. Examples: canonicalize Acn<16,i64> 2.88×, norm2 Acn<16,i64> 2.60×, and add Acn<4,i64> with a k gap of 20 3.01× fewer instructions. dbdc5b7 brings the bare kernel back to the pre-rebase instruction counts, for example 167.9M → 161.3M per 2M calls on random input with GCC 15. Its cycles are equal within noise.

GCC 13 (13.4, the CI compiler), base → tip, instructions / cycles:

  • canonicalize Acn<4>, canonical / 2·√2·u: 1.79× / 1.18× fewer instructions, 1.42× / 1.12× fewer cycles.
  • canonicalize Acn<16>, the same two inputs: 4.36× / 1.55× fewer instructions, 3.36× / 1.18× fewer cycles.
  • from_coeffs Acn<4> / Acn<16>: 2.76× / 3.83× fewer instructions, 2.15× / 2.05× fewer cycles.

Clang 20, base → tip, instructions / cycles:

  • canonicalize Acn<4>: 2.22× / 1.47× fewer instructions, 1.36× / 1.08× fewer cycles.
  • canonicalize Acn<16>: 5.25× / 1.96× fewer instructions, 3.14× / 1.25× fewer cycles.
  • from_coeffs: 1.96× / 2.70× fewer instructions, 1.77× / 2.39× fewer cycles.

A side effect in the next PR: with GCC, the dense matrix-vector row of #44 ((H ⊗ I_256) × dense vector) runs more instructions than the base (0.85× with GCC 15, 0.86× with GCC 13). At the pre-rebase commit 1daf50a, before the change that dbdc5b7 makes, the same row was 1.08× faster with GCC 15. The investigation for the matrix PR found the cause in the code GCC generates for the matrix product's all-terms loop. GCC recomputes the index r*cols_ + k and reloads the data pointer from the stack for every term. canonicalize itself is not the cause. Changing canonical.hpp to avoid it made things worse: canonicalize on canonical Acn<4> input went from 47 to 68 instructions, and the 16×16 Acn<4,i64> product went from 1.65× to 1.50× against the base. So this PR keeps dbdc5b7 as it is. The matrix PR fixes the regression in the matrix product's loop (e120f59).

Behaviour changes

  • Values, k, the overflow flag and exceptions are unchanged for every input. The ACN_STATS counters are bumped as before.
  • A BigInt add, sub or fma_into across a large k gap is no longer quadratic in the gap.
  • New public functions: ring::shift_left, the overload canonicalize(c, k) without scratch, and the overload ring::norm2(out, a) without scratch. The old overloads with a scratch span are kept and forward to the new ones.
  • The internal scratch slot detail::ScratchTag::Norm2 was removed.

Decisions for @MichalHe

#45, accepted cost. With GCC 15, two canonicalize inputs run fewer instructions but take 2%–7% more cycles than the base:

  • the 2·√2·u Acn<4> input: 232 → 196 instructions, 0.96×–0.98× of the base's cycles;
  • an all-even Acn<4> input in the bare kernel, where the OR scan never exits early. 0849351 measured 588M against 696M instructions, but 132.9M against 124.5M cycles (1.07×).

A branch-free OR for n <= 4 was tried. It made that input 1.22× faster, but canonical input took 1.48× more cycles (38.2M → 56.5M), and the Acn<4,i64> product took 1.43× more (99.7M → 142.2M), so it was not taken. Through Acn and AcnDyn (from_coeffs, add, mul), canonicalize is faster than on the base. Please confirm that this cost is acceptable.

Testing

On the final commits, each run with -G Ninja -DACN_WERROR=ON and the full ctest -V, with no warnings and no "No test cases matched":

Compiler Configuration Passed
GCC 13.4 Release, at this PR's head 523b213 312/312

Earlier runs were on the stack before the matrix PR's dense-loop commit e120f59 and before the latest CodeRabbit follow-ups (in #68, #73, #78 and #79): every commit of the stack passed GCC 15 Debug, and every PR head passed GCC 13 Release and GCC 15 Debug with ACN_WITH_GMP=OFF. The full matrix (GCC 13 and 15, Clang 20; Debug, Release, RelWithDebInfo; ASan+UBSan; GMP on and off; _GLIBCXX_ASSERTIONS; ACN_SCALE_EXP_64; ACN_STATS with benchmarks; Ninja Multi-Config; the CMake consumer jobs) passed on 88da72e, the combined branch this stack was split from. Of those follow-ups, only fa2ec11 (two test files, #68) is below this PR's head. After the follow-ups, the top of the stack (d445ac6, #79) passed GCC 15 Debug, GCC 13 ASan+UBSan, ACN_WITH_GMP=OFF, Clang 20, ACN_STATS with benchmarks, and ACN_SCALE_EXP_64 with _GLIBCXX_ASSERTIONS. CI (GCC 13.3, Clang 18) runs the full matrix on this PR.

Differential tests in the new tests/test_kernels.cpp:

  • ring::shift_left against the single-bit loop, comparing value and flag. The inputs are boundary values for CheckedI64 and CheckedI128, including amounts above INT_MAX.
  • An add across a k gap of 4·10⁶ for BigInt, AcnDyn and CheckedI64. It checks that the result is exact and that the add is fast.
  • canonicalize on the words against the generic path and against BigInt, for n = 1..32 with CheckedI64 and CheckedI128. It compares values and k, checks the overflow_error at the ScaleExp limits, and checks that the flag is never set.
  • The sqrt(2) step placed exactly at the minimum k: a throw must leave (c, k) unchanged ([M5] Scale-exponent arithmetic is unchecked #18).
  • Checked::ctz against a bit loop.
  • ring::norm2 against mul(a, conj(a)) for n = 1..32. With CheckedI64 and CheckedI128 on boundary values, the words and the flag must be equal, and the flag must be set exactly when sum a[t]^2 does not fit. With BigInt, the values must be equal.

The tests that parse a Checked word's to_string into a BigInt REQUIRE that the parse succeeded before they dereference the optional, as the #11 sweep does. Outside the suite, a 400k-case differential of the dbdc5b7 word path against canonicalize_generic found no difference. It used CheckedI64 and CheckedI128, k near the minimum, throws included, and checked that (c, k) is unchanged on a throw. It ran under ASan+UBSan with GCC 15, with Clang 20, and with GCC 13 and ACN_SCALE_EXP_64. test_dynamic and scratch_exit drop the removed Norm2 slot.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92

Summary by CodeRabbit

  • Improvements

    • Canonicalization and norm calculations now require less temporary storage.
    • Scaling operations apply even powers of two more efficiently.
    • Canonicalization handles scale limits while preserving coefficient values when an operation cannot be completed.
  • Tests

    • Expanded coverage for scaling, canonicalization, norm calculations, and integer edge cases.

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Explain Change →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 59 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0018e166-cd10-4a8c-9cae-4af187902f91
Commits

Reviewing files that changed from the base of the PR and between 0258505 and 523b213.

Files selected for processing: 11

  • docs/DESIGN.md
  • include/acn/acn_dynamic.hpp
  • include/acn/acn_static.hpp
  • include/acn/canonical.hpp
  • include/acn/int_backend.hpp
  • include/acn/ring.hpp
  • include/acn/scratch.hpp
  • tests/CMakeLists.txt
  • tests/scratch_exit.cpp
  • tests/test_dynamic.cpp
  • tests/test_kernels.cpp

No actionable comments were generated in the recent review.

Walkthrough

This PR adds a shared coefficient-shift helper and updates scale alignment. It adds separate Checked and generic canonicalization paths. It also computes norm2 without a scratch buffer and adds differential tests for these kernels.

Changes: Ring kernel and canonicalization updates

Layer / File(s) Summary
Coefficient shifting and scale alignment
include/acn/ring.hpp, include/acn/acn_dynamic.hpp, include/acn/acn_static.hpp, tests/test_kernels.cpp, tests/CMakeLists.txt
ring::shift_left shifts coefficients in steps for large amounts. Static and dynamic scale adjustment use this helper. Kernel tests cover shift and scale-alignment behavior.
Canonicalization paths and backend support
include/acn/canonical.hpp, include/acn/int_backend.hpp, include/acn/acn_dynamic.hpp, include/acn/acn_static.hpp, docs/DESIGN.md, tests/test_kernels.cpp
Canonicalization dispatches Checked backends to a word-based path and other backends to a generic path. Checked trailing-zero counting and two-argument calls are added. Tests compare results and check exception safety.
Scratch-free norm2
include/acn/ring.hpp, include/acn/scratch.hpp, include/acn/acn_dynamic.hpp, include/acn/acn_static.hpp, tests/scratch_exit.cpp, tests/test_dynamic.cpp, tests/test_kernels.cpp
A two-span norm2 overload computes the conjugate-symmetric result. Existing scratch-span calls forward to it, and the Norm2 scratch tag and related capacity checks are removed. Tests compare results and overflow behavior.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Possibly related issues

  • Issue 5 tracks performance findings that include the canonicalization, alignment, and norm2 changes in this PR.
  • Issue 27 concerns spurious overflow in canonicalization’s sqrt(2) parity probe. This PR adds a parity pre-check to the Checked path.

Possibly related PRs

Suggested reviewers: samo538

Merge Risk: Minimal · previous review 02585

The PR speeds up scale alignment, canonicalization and norm2 while keeping values, scale, overflow flags and exceptions unchanged. The new differential tests cover these kernels. No merge-blocking issue was found. The author's note that some direct canonicalize inputs showed 2%–7% more cycles on GCC 15 is a performance tradeoff for reviewers to accept.

Pre-merge checks: Passed 3 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Linked Issues check Inconclusive Stack objectives, using the current PR and the stack evidence.

[#43] Scale alignment, one shift per coefficient. Addressed by this PR for the even-gap path. add, sub and fma_into call the new ring::s…
Provide current review evidence for PR #79 (commit perf(static): fixed-N sqrt(2) step for odd k gaps at N >= 8 (#43)). Confirm that the odd-gap add path for N >= 8 uses a single fixed-N step with the same value and overflow flag as the bitw…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title names three changes: shift alignment (ring::shift_left in add, sub, and fma_into), canonicalization on machine words with a no-scratch overload, and a half-output norm2. The raw summary conf…
Out of Scope Changes check Passed The changes introduced by PR #71 relate to the linked objectives. Changed areas: ring::shift_left and its use in acn_static.hpp and acn_dynamic.hpp for #43; canonical.hpp, int_backend.hpp (Checked::ct…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names three changes: shift alignment (ring::shift_left in add, sub, and fma_into), canonicalization on machine words with a no-scratch overload, and a half-output norm2. The raw summary confirms each of these in the changed files (acn_dynamic.hpp, acn_static.hpp, canonical.hpp, ring.hpp, int_backend.hpp). The title is specific and matches the main performance work in the changeset. It does not mention the Norm2 scratch-slot removal, but that is a supporting detail.

Full details: Out of Scope Changes check

Explanation

The changes introduced by PR #71 relate to the linked objectives. Changed areas: ring::shift_left and its use in acn_static.hpp and acn_dynamic.hpp for #43; canonical.hpp, int_backend.hpp (Checked::ctz, trailing_zeros) and the canonicalize overload for #45; ring::norm2 and the removal of ScratchTag::Norm2 in scratch.hpp for #52. Supporting changes are the new tests/test_kernels.cpp and its CMake registration, the matching test updates in test_dynamic.cpp and scratch_exit.cpp for the removed scratch slot, and the DESIGN.md update for the canonicalization description. These support the objectives. No change in the reviewed summary is unrelated to #43, #45 or #52.

Full details: Linked Issues check

Explanation

Stack objectives, using the current PR and the stack evidence.

[#43] Scale alignment, one shift per coefficient. Addressed by this PR for the even-gap path. add, sub and fma_into call the new ring::shift_left once per coefficient. The shift uses the total Checked::shift_left and mpz_mul_2exp for BigInt. Shift amounts above INT_MAX are applied in steps and stop at zero. The author reports the BigInt quadratic-gap case dropping from 2.5 s to under 1 ms. Status: Partially addressed in this PR. The odd-gap fixed-N sqrt(2) step for N >= 8 is stated to be in PR #79 (commit perf(static): fixed-N sqrt(2) step for odd k gaps at N >= 8 (#43)). PR #79 is uncertain in the stack evidence, so the odd-gap part is Uncertain.

[#45] canonicalize. Addressed by this PR. Checked values use one OR reduction with one countr_zero, and the scan stops at the first odd coefficient. The parity pre-check stops at its first mismatch. Checked::ctz is O(1). Acn and AcnDyn use a new canonicalize(c, k) overload with no 2N scratch. The sqrt(2) minimum-k test runs before shifting in canonicalize_words_to_min, which keeps the #18 contract. The parity pre-check and halved butterfly were already in the fix PRs. Contributing PR: #71. Status: Addressed by this PR's changes.

[#52] norm2. Addressed by this PR. ring::norm2 computes out[l] for l < n/2 and derives the rest by self-conjugacy. The overflow flag follows the Cauchy-Schwarz argument stated in the PR. Contributing PR: #71. Status: Addressed by this PR's changes.

Uncertain part. Stack PRs #72 to #79 have no current review evidence. The odd-gap part of #43 depends on PR #79. Under the stack rules, the #43 objective cannot reach a PASS. The current evidence also rests on the author's summary and the file summaries. Those are not confirmed by direct code reading in this assessment.

Resolution

Provide current review evidence for PR #79 (commit perf(static): fixed-N sqrt(2) step for odd k gaps at N >= 8 (#43)). Confirm that the odd-gap add path for N >= 8 uses a single fixed-N step with the same value and overflow flag as the bitwise loop. Also confirm that no stack member regresses the even-gap shift path in ring::shift_left from this PR.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 99d4e8ab-ea5d-4f01-b162-389a0fdcae51
Commits

Reviewing files that changed from the base of the PR and between 43fb1fe and 0258505.

Files selected for processing: 11

  • docs/DESIGN.md
  • include/acn/acn_dynamic.hpp
  • include/acn/acn_static.hpp
  • include/acn/canonical.hpp
  • include/acn/int_backend.hpp
  • include/acn/ring.hpp
  • include/acn/scratch.hpp
  • tests/CMakeLists.txt
  • tests/scratch_exit.cpp
  • tests/test_dynamic.cpp
  • tests/test_kernels.cpp
Files with no reviewable changes: 2

  • include/acn/scratch.hpp
  • tests/test_dynamic.cpp

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

This was referenced Dec 2, 2026
@codacy-production

Copy link
Copy Markdown

Not up to standards ⛔

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@ondrik
ondrik marked this pull request as ready for review December 2, 2026 13:58
@ondrik

ondrik commented Dec 2, 2026

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

ondrik and others added 3 commits December 2, 2026 15:17
The scale alignment of add, sub and fma_into multiplied the lifted
operand by 2^(delta/2) with delta/2 single-bit shift_left calls per
coefficient. It now makes one shift per coefficient (ring::shift_left),
using the exact, total Checked::shift_left from #6 and mpz_mul_2exp for
BigInt. The result and the overflow flag are those of the bitwise loop:
a Checked value overflows the first time its magnitude leaves the word,
which a single shift detects exactly, and a shift by bit_width or more
leaves 0 either way. Amounts beyond INT_MAX (only reachable with a
64-bit ScaleExp) are applied in INT_MAX steps, which end as soon as a
fixed-width value is 0. The range-checked distance from #18 is kept.

This also removes the denial of service of a BigInt add across a large
k gap, which was quadratic in the gap: 1/sqrt(2)^1600000 + 1 took 2.5 s
and now takes < 1 ms; a 30-byte parsed value with k = 10^7 took minutes.

Measured (perf stat -e instructions, fixed-work harness, -O3 -DNDEBUG,
2M adds, before -> after):
  add Acn<4,i64>, k gap 2:     542M ->  508M (1.07x)
  add Acn<4,i64>, k gap 6:     726M ->  484M (1.50x)
  add Acn<4,i64>, k gap 20:   1455M ->  484M (3.01x)
  add Acn<16,i64>, k gap 6:   2595M -> 1505M (1.72x)
  add AcnDyn n=16, k gap 20:  5828M -> 1981M (2.94x)
  16x16 Acn<4,i64> matmul:     281M ->  270M (1.04x)
Results are identical. New test_kernels.cpp checks ring::shift_left
against the single-bit loop (value and flag) on boundary values for
CheckedI64 and CheckedI128, including amounts above INT_MAX, and an
add across a k gap of 4*10^6 for BigInt, AcnDyn and CheckedI64.

Fixes #43.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92
The parity pre-check and the overflow-free halved butterfly exist since
#27. What remained of #45:

- Checked::ctz is O(1) (std::countr_zero, over two halves for i128)
  instead of a loop over the bits.
- For a Checked backend canonicalize works on the machine words: the
  OR of the coefficients is the zero test and, with one countr_zero,
  the shared power of two (one pass instead of an all_zero pass plus a
  ctz per coefficient); the scan stops at the first odd coefficient,
  the shift needs no zero test, and the parity test compares low bits
  and stops at the first mismatch. Both loops are kept scalar with an
  early exit on purpose: a vectorized OR reduction over coefficients
  that were just stored one word at a time stalls on store forwarding
  (measured: half the instructions, but ~40% more cycles than before).
- Other backends (BigInt) find the shared ctz in the same single pass
  and stop at the first odd coefficient.
- Acn and AcnDyn call a canonicalize overload without the unused 2n
  scratch: Acn no longer zero-initializes (for BigInt: constructs and
  destroys) 2N coefficients per operation, and AcnDyn no longer borrows
  a thread-local scratch slot; its ScratchTag::Canonicalize is gone.
  The public canonicalize(c, k, scratch) is kept and forwards.

Never flags, k is still range-checked before (c, k) changes (#18), and
the ACN_STATS counters are bumped as before.

Measured (perf stat -e instructions, fixed-work harness, -O3 -DNDEBUG,
5M operations, before -> after):
  canonicalize Acn<4,i64> (hidden 2/sqrt2 factors):   858M ->  409M (2.10x)
  canonicalize Acn<16,i64>:                          2760M ->  959M (2.88x)
  canonicalize AcnDyn<i64> n=16:                     4239M -> 2639M (1.61x)
  canonicalize Acn<4,i128>:                          1513M ->  673M (2.25x)
  canonicalize Acn<4,BigInt>:                       11938M -> 10777M (1.11x)
  mul Acn<4,i64>:   984M ->  714M (1.38x)   fma Acn<4,i64>: 1139M -> 874M (1.30x)
  add Acn<4,i64>:   679M ->  399M (1.70x)   mul Acn<4,BigInt>: 1.06x
Cycles go down too (canonicalize Acn<4,i64> 1.19x wall, Acn<16,i64>
2.5x, mul<4,i64> 1.5x); results are identical. Same direction with
g++-13 and clang 20. test_kernels checks the word path against the
generic one and against BigInt (values, k, the overflow_error at the
ScaleExp limits, no flag) for n = 1..32, CheckedI64 and CheckedI128,
and Checked::ctz against a bit loop.

Rebased onto the #18 and #30 fixes, where canonicalize already took an
empty scratch span and Acn and AcnDyn already passed one: the word and
generic paths now also undo the even reduction on the cold path where
the sqrt(2) step's k would leave ScaleExp, so a throw leaves (c, k)
unchanged (test_kernels checks it), and canonicalize(c, k, scratch)
still accepts an empty span.

The differential test REQUIREs that BigInt::parse accepted each
Checked word's to_string before dereferencing the optional, as the #11
sweep does, so a rejected parse is a reported failure, not undefined
behaviour.

Fixes #45.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92
The rebase onto the #18 fix gave canonicalize_words a cold-path undo:
when the sqrt(2) step's k - 1 does not fit, it shifted the even
reduction back and restored k. That kept `shared` live across the
parity loop and cost 3-4 instructions per call over the pre-rebase
word path, contrary to the comment's "no cost to the common case".

The step can only fail when the even reduction lands exactly on the
minimum k (with no shift, k - 1 is checked before c changes). So the
even-reduction branch now compares its new k with the minimum and, on
a match, calls a cold helper, canonicalize_words_to_min, that runs the
parity test on the shifted words before writing c. A throw still
leaves (c, k) unchanged (#18); the generic (BigInt) path keeps the
undo. DESIGN §4 and the comments state the two paths.

Bare kernel, noinline canonicalize<CheckedI64> at n = 4, 2M calls,
-O3 -DNDEBUG, instructions:u, median of 5 interleaved runs
(the pre-rebase #45 commit / before / after):
  random     GCC 15 161.2M / 167.9M / 161.3M, GCC 13 147.9M / 152.8M / 148.2M
  all even   GCC 15 291.6M / 300.2M / 293.7M, GCC 13 272.7M / 277.6M / 276.8M
  sqrt2 step GCC 15 256.6M / 264.8M / 256.6M, GCC 13 240.1M / 248.3M / 240.1M
Cycles are equal within noise. A composite Acn<4>/Acn<8> loop goes
from 1759.4M to 1750.0M instructions (GCC 15), 1779.9M to 1765.9M
(GCC 13), and 2524.3M to 2524.8M (Clang 20); cycles within noise.

A 400k-case differential against canonicalize_generic (CheckedI64 and
CheckedI128, k near the minimum, throws included, (c, k) unchanged on
a throw) passes under ASan+UBSan with GCC 15, with Clang 20, and with
GCC 13 and ACN_SCALE_EXP_64.

Refs #45, #18

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92
ondrik and others added 2 commits December 2, 2026 15:17
The review measured canonicalize<CheckedI64> called directly on a
reducing Acn<4> numerator (2*sqrt(2)*u: every coefficient even, so
the OR scan never exits early) at 232 -> 196 instructions but 40.8 ->
43.2 cycles per call with g++ 15 since 45493e2, where the #45 commit
message says cycles fall with every compiler. Reproduced here
(g++ 15 -O3 -DNDEBUG, 15 interleaved runs, 3M calls): 124.5M -> 132.9M
cycles (1.07x) for 696M -> 588M instructions.

Tried: a branch-free OR for n <= 4 (no early exit). It gave that input
108.6M cycles (1.22x faster than the pre-review tip), but canonicalize on
canonical input went 38.2M -> 56.5M cycles and the Acn<4,i64> product
99.7M -> 142.2M (instructions 47 -> 90 and 161 -> 167 per call), so it
is not taken. The regression is limited to the bare kernel on this
input at n = 4 with GCC 15; canonicalize through Acn and AcnDyn
(from_coeffs, add, mul) is faster than on 824ac8f. The comment on
canonicalize_words now says so.

Refs #45.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92
a * conj(a) is self-conjugate: out[n/2] == 0 and out[n-l] == -out[l].
ring::norm2 computed it as mul(a, conj(a)), n^2 multiplies plus a
negated copy of a. It now computes out[l] for l < n/2 only (n^2/2
multiplies, zero coefficients of a skipped as in mul) and fills in the
rest, with no conj copy. DESIGN.md's operation table already promised
"about half of a multiply".

The overflow flag is unchanged: every partial sum of out[l] is at most
sum_t a[t]^2 = out[0] in magnitude (Cauchy-Schwarz), and the partial
sums of out[0] only grow, so both the old and the new kernel flag
exactly when out[0] does not fit; the words are equal even after an
overflow (both are exact modulo 2^bits). The scratch overload of
ring::norm2 is kept and forwards; AcnDyn::norm2 no longer borrows a
scratch slot (ScratchTag::Norm2 is gone), Acn::norm2 no longer zeroes
one.

Measured (perf stat -e instructions, fixed-work harness, -O3 -DNDEBUG,
5M norm2 calls, before -> after):
  Acn<4,i64>::norm2:     1037M ->  598M (1.73x), wall 1.9x
  Acn<16,i64>::norm2:   19178M -> 7365M (2.60x), wall 3.1x
  AcnDyn<i64> n=16:     20725M -> 11591M (1.79x), wall 2.2x
Results are identical. (A gather form, one accumulator per l, was
faster for n = 4 but slower for Acn<16> and skips no zeros, so it was
not taken.) test_kernels checks ring::norm2 against mul(a, conj(a))
for n = 1..32: equal words and equal flag for CheckedI64 and
CheckedI128 on boundary values, the flag set iff sum a[t]^2 does not
fit, and equal values for BigInt.

The flag test REQUIREs that BigInt::parse accepted each coefficient's
to_string before dereferencing the optional, as the #11 sweep does.

Fixes #52.

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

ondrik commented Dec 2, 2026

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@ondrik
ondrik force-pushed the review/perf-kernels branch from 0258505 to 523b213 Compare December 3, 2026 01:12
@ondrik
ondrik force-pushed the review/fix-guarantees branch from 43fb1fe to 129caea Compare December 3, 2026 01:12
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.

1 participant