Skip to content

modexp: one-digit Montgomery products and 32-bit quotient digits - #12

Merged
maximmenshikov merged 3 commits into
mainfrom
perf/modexp-one-digit-montgomery
Nov 21, 2026
Merged

maximmenshikov merged 3 commits into
mainfrom
perf/modexp-one-digit-montgomery

Conversation

@LukaszRozmej

Copy link
Copy Markdown
Member

Changes

  • reduce() (Knuth D3) estimates each quotient digit with two 32-bit divisions (Hacker's Delight divlu) in place of a 64-bit division. On RV32IM the 64-bit division is a call to __udivdi3, about 680 instructions. The digit is now a uint32_t, so the products in D3 and D4 are 32 x 32 bit.
  • A modulus of one 256-bit digit has its own Montgomery product, hi(a b) - hi(q N) with q = lo(a b) N^-1 mod R: eight delegations in place of about 21 in the general CIOS loop. modexp_mont keeps N^-1 for it.

MODEXP with a 256-bit odd modulus, for example a field inversion x^(r-2) mod r in a SNARK verifier, goes from about 88,000 to about 24,000 cycles for each call.

Measured on the Nethermind trusted-input Airbender guest (master 6b332240f76), Airbender CLI cycles, 27 mainnet blocks (26279462 to 26279540, every third block):

Block Before After Change
26279522 186.09M 160.62M -13.69%
26279477 190.25M 164.63M -13.47%
26279465 222.83M 197.25M -11.48%
26279528 255.99M 230.12M -10.11%
Geomean, 27 blocks -2.00%

No block is slower. The other 23 blocks change by 0 to -0.57%.

Testing

  • build/ci.sh: all 1554 vectors pass. They include odd moduli of 1 to 32 bytes (the one-digit path) and random even moduli (the reduce() path).
  • The guest's block hash and status are unchanged on all 27 blocks.

@LukaszRozmej

Copy link
Copy Markdown
Member Author

Verified the MODEXP changes in 1cb9108 against all 1,556 RV32 QEMU vectors. The inversion benchmark fell from 23,260 to 16,083 guest cycles versus the preceding PR head. The build, ISA gates and CodeQL checks passed.

🤖 AI agent (Codex / GPT-6) on behalf of @LukaszRozmej

main got a one-digit Montgomery product of its own, mont_mul_1 (12
delegations). This branch has the shared mont_mul for that case (8), so
the merge keeps modexp.c of this branch.
@maximmenshikov

Copy link
Copy Markdown
Collaborator

#11 is in main now and it had a one-digit product of its own (mont_mul_1, 12 delegations), so the branches conflicted in modexp.c. I merged main into this branch and kept modexp.c of this branch: mont_mul of mont.h does the same in 8. CI passes.

@maximmenshikov
maximmenshikov merged commit a8c24a8 into main Nov 21, 2026
5 checks passed
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