Repository navigation
Conversation
|
Warning Review limit reachedYou'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. View limit details
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
Not up to standards ⛔
|
|
@coderabbitai review |
Action not completed
|
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
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
|
@coderabbitai review |
Action performed
|
0258505 to
523b213
Compare
43fb1fe to
129caea
Compare
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) andnorm2(#52). It is stacked onsplit-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_REQUIREerrors are unchanged. A throw from canonicalize leaves (c, k) unchanged (#18).Fix PRs #58–#70 come first (this stack is based on #70).
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
Fixes [P1] Scale alignment: shift each coefficient once (
delta/2bits,countl_zero) instead ofdelta/2single-bit shifts #43 (5bb3eb9): the scale alignment of add, sub andfma_intoused to makedelta/2single-bitshift_leftcalls per coefficient. It now makes one shift per coefficient through the newring::shift_left, which uses the exact, totalChecked::shift_leftfrom [C1]Checked<i64>::shift_leftUB at INT64_MIN: the overflow flag disappears in optimized builds #6 andmpz_mul_2expfor BigInt. The value and the flag match the bitwise loop. Shift amounts aboveINT_MAXcan only occur with a 64-bitScaleExp. They are applied inINT_MAXsteps, which stop as soon as a fixed-width value is 0. This also removes the BigInt add's run time that was quadratic in the k gap:1/sqrt(2)^1600000 + 1took 2.5 s and now takes under 1 ms. For odd gaps at N >= 8, a fixed-N sqrt(2) step comes later in the stack, in the BigInt PR (perf(static): fixed-N sqrt(2) step for odd k gaps at N >= 8 (#43)).Fixes [P3]
canonicalize: parity pre-check, in-place radix-4 butterfly, O(1) trailing-zero count #45 (08db153): Checked values are canonicalized on the machine words:countr_zeroof it gives the shared power of two. The scan stops at the first odd coefficient.Checked::ctzis O(1) (std::countr_zero, over two halves for i128).AcnandAcnDyncall a new overloadcanonicalize(c, k)without the unused 2n scratch, soAcnno longer zero-initializes 2N coefficients per operation.canonicalize(c, k, scratch)is kept and forwards to it.The parity pre-check and the halved butterfly were already done in the fix PRs ([L1] canonicalize's √2 probe raises spurious overflow flags for |c| ≥ 2^62 #27).
Refs [P3]
canonicalize: parity pre-check, in-place radix-4 butterfly, O(1) trailing-zero count #45, [M5] Scale-exponent arithmetic is unchecked #18 (dbdc5b7): the word path tests the minimum-k case of the sqrt(2) step before it shifts. It does this in a cold helper,canonicalize_words_to_min. Before, the [M5] Scale-exponent arithmetic is unchecked #18 undo on the cold path kept a value live across the parity loop and cost 3–4 instructions per call. The generic (BigInt) path keeps the undo. DESIGN §4 describes both paths.Refs [P3]
canonicalize: parity pre-check, in-place radix-4 butterfly, O(1) trailing-zero count #45 (0849351): a comment oncanonicalize_wordsrecords the early exit's cost on an all-even input with GCC 15 (see Decisions).Fixes [P10]
norm2: compute only half of the coefficients (the result is self-conjugate) #52 (523b213):ring::norm2computes onlyout[l]forl < n/2.a * conj(a)is self-conjugate, so the other half follows (out[n/2] == 0,out[n-l] == -out[l]). There is noconjcopy, and zero coefficients are skipped as inmul. The overflow flag is unchanged. By Cauchy-Schwarz, every partial sum ofout[l]is at mostout[0]in magnitude, so both kernels flag exactly whenout[0]does not fit.AcnDyn::norm2no longer borrows a scratch slot, andAcn::norm2no longer zeroes one.Measurements
The base is
bdc6fb9, the head of the original fix branch;split-check/guaranteesdiffers from it only in the tests of #68'sfa2ec11. The tip is88da72e(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 -DNDEBUGand measured withperf 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_coeffsand 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.i64=CheckedI64)Acn<4,i64>, k gap 2 / 6 / 20AcnDyn<i64>n=16, k gap 201/sqrt2^1600000 + 1,Acn<4,BigInt>(whole program)Acn<4,i64>, canonical / 2·√2·u inputAcn<16,i64>, canonical / 2·√2·u inputfrom_coeffsAcn<4,i64>/Acn<16,i64>norm2Acn<4,i64>/Acn<16,i64>/AcnDyn<i64>n=16The 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×,norm2Acn<16,i64>2.60×, and addAcn<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:
Acn<4>, canonical / 2·√2·u: 1.79× / 1.18× fewer instructions, 1.42× / 1.12× fewer cycles.Acn<16>, the same two inputs: 4.36× / 1.55× fewer instructions, 3.36× / 1.18× fewer cycles.from_coeffsAcn<4>/Acn<16>: 2.76× / 3.83× fewer instructions, 2.15× / 2.05× fewer cycles.Clang 20, base → tip, instructions / cycles:
Acn<4>: 2.22× / 1.47× fewer instructions, 1.36× / 1.08× fewer cycles.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 commit1daf50a, 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 indexr*cols_ + kand reloads the data pointer from the stack for every term. canonicalize itself is not the cause. Changingcanonical.hppto avoid it made things worse: canonicalize on canonicalAcn<4>input went from 47 to 68 instructions, and the 16×16Acn<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
ACN_STATScounters are bumped as before.fma_intoacross a large k gap is no longer quadratic in the gap.ring::shift_left, the overloadcanonicalize(c, k)without scratch, and the overloadring::norm2(out, a)without scratch. The old overloads with a scratch span are kept and forward to the new ones.detail::ScratchTag::Norm2was 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:
Acn<4>input: 232 → 196 instructions, 0.96×–0.98× of the base's cycles;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. ThroughAcnandAcnDyn(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=ONand the fullctest -V, with no warnings and no "No test cases matched":523b213Earlier runs were on the stack before the matrix PR's dense-loop commit
e120f59and 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 withACN_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_STATSwith benchmarks; Ninja Multi-Config; the CMake consumer jobs) passed on88da72e, the combined branch this stack was split from. Of those follow-ups, onlyfa2ec11(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_STATSwith benchmarks, andACN_SCALE_EXP_64with_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_leftagainst the single-bit loop, comparing value and flag. The inputs are boundary values for CheckedI64 and CheckedI128, including amounts aboveINT_MAX.AcnDynand CheckedI64. It checks that the result is exact and that the add is fast.overflow_errorat theScaleExplimits, and checks that the flag is never set.Checked::ctzagainst a bit loop.ring::norm2againstmul(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 whensum a[t]^2does not fit. With BigInt, the values must be equal.The tests that parse a Checked word's
to_stringinto a BigIntREQUIREthat 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 againstcanonicalize_genericfound 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 andACN_SCALE_EXP_64.test_dynamicandscratch_exitdrop the removedNorm2slot.🤖 Generated with Claude Code
https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92
Summary by CodeRabbit
Improvements
Tests