Skip to content

WIP: ⚡️ expWad and lnWad via Remez continued fraction - #1567

Draft
duncancmt wants to merge 3 commits into
Vectorized:mainfrom
duncancmt:dcmt/exp-ln-continued-fraction
Draft

duncancmt wants to merge 3 commits into
Vectorized:mainfrom
duncancmt:dcmt/exp-ln-continued-fraction

Conversation

@duncancmt

Copy link
Copy Markdown
Contributor

WIP: stacked on top of #1546

Description

Describe the changes made in your pull request here.

Checklist

Ensure you completed all of the steps below before submitting your pull request:

  • Ran forge fmt?
  • Ran forge test?

Pull requests with an incomplete checklist will be thrown out.

ddallaire and others added 3 commits August 18, 2026 10:04
…ions

Replace the Horner-form rational evaluations in FixedPointMathLib.expWadFast
and FixedPointMathLib.lnWadFast (both src/utils/FixedPointMathLib.sol and
src/utils/clz/FixedPointMathLib.sol) with lattice-refined Remez continued
fractions, tightening expWadFast error bounds by 16+ orders of magnitude while
reducing gas on all four compiler/EVM profiles.

- expWadFast:
  - Replace the two-step WAD-to-Q96 division and k*ln(2) subtraction with a
    single Q202 base-2 multiply and shift extraction to a Q129 fractional
    octave f.
  - Evaluate 2**f = 1 + 2*f / (C(f**2) - f) via a 10-term Q129 continued
    fraction fitted to 2**t * exp(-a*t) (odd tilt balancing the -3 * 2**-130
    one-sided margin) with LLL/Babai lattice refinement on the low bits.
  - Tighten the certified one-sided relative shortfall from 2.58e-22 to
    < 1.7237 * 2**-128 (< 5.07e-39), expanding the exact floor(E) or
    floor(E) - 1 domain from x <= 8265113944572514620 (~3885 * 1e18) to
    x <= 46731834294601968657 (~1.97e38, covering all int128 values), while
    keeping r <= E, expWadFast(0) == 1e18, monotonicity across all 2**k seams,
    and identical domain/revert boundaries.
  - Single-call gas (solc 0.8.35, 1000 runs): 387 -> 358 (Paris legacy),
    353 -> 300 (Paris via-ir), 383 -> 354 (Osaka legacy), 350 -> 297
    (Osaka via-ir).

- lnWadFast:
  - Normalize to Q71 and center on round(sqrt(2) * 2**71) using sub(c, x) to
    avoid pushing a second negated literal.
  - Evaluate 2 * 1e18 * atanh(s) via a 7-term Q70 continued fraction with
    alternating gauge scaling alpha = 2**61 / 1e18 (all 7 constants fit 9
    bytes and sdiv(s << 81, d) lands directly in Q20 WAD without a WAD
    multiply) and LLL/Babai lattice refinement on the low bits.
  - Preserve r in {floor(L), floor(L) - 1}, lnWadFast(1e18) == 0, global
    monotonicity, and LnWadUndefined() reverts.
  - Single-call gas and runtime size (solc 0.8.35, 1000 runs):
    536g/535B -> 456g/405B (Paris legacy), 446g/507B -> 378g/384B (Paris
    via-ir), 397g/400B -> 311g/265B (Osaka legacy), 309g/372B -> 241g/248B
    (Osaka via-ir).

- Credit David Dallaire (ddallaire) in NatSpec for both functions, update
  generated docs and golden/seam tests (including worst-case vectors and
  fixing the double-wrapping bug in testExpWadFastMonotonicallyIncreasingAround).

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
Co-Authored-By: Cursor <cursoragent@cursor.com>
Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
Apply optimizations and polish from GPT-6.2 Astra adversarial review:

- expWadFast:
  - Retain all 202 fractional bits in the linear numerator `n = shl(54, p)`
    instead of shifting `f = sar(127, n)` back left by 127, decrement `D0` by
    1 to center the `f`-floor bias in `den`, pin `x == 0` via `iszero(x)`,
    and place the WAD multiplier literal first in `mul(...)`.
  - Tightens the pre-floor relative shortfall bound from `1.7237 * 2**-128`
    to `1.4307 * 2**-128` (`< 4.21e-39`), expanding the `floor(E)` or
    `floor(E) - 1` domain to `x <= 46918143602790025991` (`~2.38e38`, 1.40x
    `type(int128).max`), while shrinking runtime bytecode across all 8
    compiler/EVM/runs configurations and cutting single-call gas by 1 gas in
    legacy and 6-9 gas in `--via-ir` (`294` Paris / `291` Osaka at 1000 runs).

- lnWadFast:
  - Compute the centered Mobius argument via unsigned division as
    `s = shl(70, 1) - div(shl(71, c), add(x, c))` and add the final signed
    quotient to `BIAS - r * LN2`.
  - Saves 6-12 gas across all 8 compiler/EVM/runs configurations (`444` Paris
    legacy, `372` Paris via-ir, `305` Osaka legacy, `232` Osaka via-ir) and
    tightens pre-floor shortfall to `< 0.0860` wei while preserving
    `r in {floor(L), floor(L) - 1}` and `lnWadFast(1e18) == 0`.

- Docs, comments, credit, and tests:
  - Credit both David Dallaire (ddallaire) and Duncan Townsend (duncancmt).
  - Remove unqualified relative-error phrasing from `expWadFast` NatSpec and
    differential test comments, state the overflow cutoff explicitly, use
    "nondecreasing", and align all inline rounding/bias figures with the
    pure exact-rational Bernstein proofs.
  - Update `testExpWadFast` golden vectors (including the current octave 0->1
    boundary `346573590279972654/346573590279972655` and new threshold
    `46918143602790025991`) and replace binary search in `_expWadFastSeamOf`
    with direct ceiling division (10x faster seam test).

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
Co-Authored-By: Cursor <cursoragent@cursor.com>
Co-Authored-By: GPT-6.2 Astra <noreply@openai.com>
@github-actions

Copy link
Copy Markdown

Gas Snapshot Comparison Report

Generated at commit : e9d2296, Compared to commit : 258f67c

Contract Name Test Name Main Gas PR Gas Diff
BlockHashLibTest testVerifyBlock() 5386 5297 -89
test__codesize() 8760 8321 -439
EnumerableSetLibTest testEnumerableAddressSetBasic2() 175344 175309 -35
testEnumerableAddressSetUpdate() 459603 459990 387
testEnumerableBytes32SetBasic() 271151 271128 -23
testEnumerableBytes32SetBasic2() 178444 178427 -17
testIndexOfDirtyUpperBits() 227857 - -
testIndexOfDirtyUpperBitsLazy() 48826 - -
test__codesize() 21316 20983 -333
ERC1967FactoryTest testDeployBeaconProxyDeterministicAndCall() 403169 - -
testDeployBeaconProxyDeterministicAndUpgrade() 689718 674846 -14872
testDeployDeterministicAndUpgrade() 465255 465211 -44
test__codesize() 12926 12194 -732
ERC4337Test testIsValidSignatureWrapped() 599977 599989 12
ERC721HooksTest testERC721Hooks() 7854452 7854440 -12
FixedPointMathLibTest testAbsEdgeCases() 468 513 45
testAvg() 462 440 -22
testAvgEdgeCase() 490 468 -22
testAvgSigned() 916 894 -22
testCbrt() 10279 10324 45
testCbrtWad() 12049 12027 -22
testCbrtWadConverged() 24211 24278 67
testCbrtWadMonotonicallyIncreasing() 25877 25789 -88
testDist() 631 697 66
testDistEdgeCases() 523 567 44
testDivWad() 731 687 -44
testDivWadEdgeCases() 399 444 45
testDivWadUp() 2927 2972 45
testDivWadUpZeroDenominatorReverts() 3967 3945 -22
testDivWadZeroDenominatorReverts() 3966 3970 4
testExpWad() 8033 7989 -44
testFactorial() 97546 97569 23
testFullMulDivN() 890 846 -44
testFullMulDivUnchecked() 1578 1600 22
testFullMulDivUpRevertsIfRoundedUpResultOverflowsCase1() 4517 4495 -22
testFullMulDivUpRevertsIfRoundedUpResultOverflowsCase2() 4516 4472 -44
testGcd() 4223 4244 21
testInvMod() 12908 12886 -22
testLambertW0WadMonotonicallyIncreasing() 18356909 18356887 -22
testLambertW0WadMonotonicallyIncreasing2() 4030641 4030686 45
testLambertW0WadRevertsForOutOfDomain() 112681 113153 472
testLambertW0WadWithinBounds() 122404 122360 -44
testLnWad() 2094 2049 -45
testLnWadBig() 2084 2062 -22
testLog10() 75929 75973 44
testLog10Up() 4364 4408 44
testLog2() 265326 265304 -22
testLog256() 22826 22848 22
testLog256Up() 1286 1287 1
testMulDiv() 1867 1911 44
testMulDivEdgeCases() 733 755 22
testMulDivUp() 2125 2146 21
testMulDivUpEdgeCases() 854 831 -23
testMulDivUpZeroDenominator() 4019 4040 21
testMulDivZeroDenominatorReverts() 3996 4082 86
testMulSqrt() 1940987 1943324 2337
testMulWad() 704 682 -22
testMulWadEdgeCases() 718 717 -1
testPackUnpackSci() 129024 129069 45
testRPow() 3306 3283 -23
testRawSDivWadEdgeCases() 11346 - -
testRawSMulWadEdgeCases() 4232 - -
testSDivWad() 836 880 44
testSDivWadEdgeCases() 401 446 45
testSDivWadRoundsTowardsZero() 1183 - -
testSMulWad() 1048 1006 -42
testSMulWadEdgeCases() 1275 1298 23
testSMulWadRoundsTowardsZero() 1783 - -
testSaturatingAdd() 1492 1514 22
testSaturatingMul() 1622 1600 -22
testSci() 1828158 1828136 -22
testSqrtHashedSingle() 54586 54608 22
testSqrtWad() 7936 7958 22
test__codesize() 62241 72293 10052
testExpWadFast() - 29973 -
testExpWadFastGas() - 6988 -
testExpWadFastOverflowReverts() - 15847 -
testExpWadFastSeamsMonotonic() - 268095 -
testExpWadGas() - 8881 -
testLnWadFast() - 27087 -
testLnWadFastGas() - 5043 -
testLnWadFastNegativeReverts() - 18559 -
testLnWadFastOctaveSeamsMonotonic() - 239575 -
testLnWadGas() - 6343 -
FixedPointMathLibWithCLZTest testAbs() 698 676 -22
testAbsEdgeCases() 490 513 23
testAvg() 462 440 -22
testAvgEdgeCase() 445 468 23
testAvgSigned() 916 894 -22
testCbrt() 6222 6267 45
testCbrtWad() 8231 8209 -22
testCbrtWadConverged() 23941 24028 87
testCbrtWadDebug() 7119 7075 -44
testCbrtWadMonotonicallyIncreasing() 25154 25066 -88
testDist() 675 697 22
testDivWad() 731 687 -44
testDivWadEdgeCases() 399 444 45
testDivWadUp() 2949 2972 23
testDivWadUpEdgeCases() 446 469 23
testDivWadZeroDenominatorReverts() 3948 3970 22
testExpWad() 8033 7989 -44
testFactorial() 97524 97569 45
testFullMulDiv() 1099 1143 44
testFullMulDivN() 890 846 -44
testFullMulDivUnchecked() 1622 1600 -22
testFullMulDivUpRevertsIfRoundedUpResultOverflowsCase1() 4450 4495 45
testFullMulDivUpRevertsIfRoundedUpResultOverflowsCase2() 4494 4472 -22
testGcd() 4223 4244 21
testInvMod() 12885 12886 1
testLambertW0WadMonoDebug() 700861 700839 -22
testLambertW0WadMonotonicallyIncreasing() 17296838 17296839 1
testLambertW0WadMonotonicallyIncreasing2() 3731565 3731588 23
testLambertW0WadRevertsForOutOfDomain() 112923 113153 230
testLambertW0WadWithinBounds() 111382 111338 -44
testLerpInt() 6410 6455 45
testLerpUint() 6413 6369 -44
testLnWad() 1648 1626 -22
testLnWadBig() 1661 1639 -22
testLnWadNegativeReverts() 10989 10923 -66
testLnWadOverflowReverts() 3916 3893 -23
testLnWadSmall() 2139 2117 -22
testLog2() 136107 136085 -22
testLog256() 12553 12597 44
testLog256Up() 1858 1859 1
testLog2Up() 159794 159817 23
testMulDivUp() 2125 2146 21
testMulDivUpZeroDenominator() 4041 4040 -1
testMulDivZeroDenominatorReverts() 4018 4082 64
testMulSqrt() 1910558 1912750 2192
testMulWad() 704 682 -22
testMulWadEdgeCases() 695 717 22
testMulWadUp() 778 801 23
testMulWadUpEdgeCases() 768 791 23
testPackUnpackSci() 129024 129069 45
testRPowOverflowReverts() 13229 13119 -110
testSDivWad() 858 880 22
testSDivWadEdgeCases() 401 446 45
testSMulWad() 1028 1006 -22
testSMulWadEdgeCases() 1275 1298 23
testSaturatingAdd() 1491 1514 23
testSaturatingMul() 1599 1600 1
testSci() 1824283 1824239 -44
testSqrt() 31560 31605 45
testSqrtHashedSingle() 38120 38098 -22
testSqrtWad() 5813 5857 44
test__codesize() 62814 73985 11171
testExpWadFast() - 29973 -
testExpWadFastGas() - 6988 -
testExpWadFastOverflowReverts() - 15847 -
testExpWadFastSeamsMonotonic() - 268095 -
testExpWadGas() - 8881 -
testLnWadFast() - 22383 -
testLnWadFastGas() - 3573 -
testLnWadFastNegativeReverts() - 18196 -
testLnWadFastOctaveSeamsMonotonic() - 164899 -
testLnWadGas() - 4933 -
JSONParserLibTest testParseJWTGas() 49818 49819 1
test__codesize() 37554 37555 1
LibBytesTest testBytesInCalldata() 25581 25558 -23
testCheckInCalldata() 362 340 -22
testCmp() 2652 2608 -44
testDirectReturn() 8739 8760 21
testDynamicStructInCalldata() 28326 28304 -22
testDynamicStructInCalldata2() 128958 128980 22
testDynamicStructInCalldataMalformedOffset() 23795 - -
testDynamicStructInCalldataValid() 1898 - -
testEmptyCalldata() 520 542 22
testIndexOfByte() 5396 5416 20
testSplitNullPathAfterHash() 1240 - -
testSplitNullPathCleanScratch() 1255 - -
testSplitNullPathTwoConsecutive() 2269 - -
testStaticStructInCalldata() 131192 131148 -44
testUint8AtPaddingAfterShortValue() 279466 - -
testUint8AtPaddingAfterSpilledValue() 303244 - -
testUint8AtPaddingAfterTaggedLongValue() 492985 - -
testUint8AtStaleByteAfterShrink() 313114 - -
test__codesize() 20101 15355 -4746
LibPRNGTest testLCGGas() 20778 20800 22
testLazyShufflerGet() 298479 298435 -44
testLazyShufflerGrowWithinSameWidth() 47283 - -
testLazyShufflerGrowWithinWideWidth() 69203 - -
testLazyShufflerNoStorageCollisions() 265082 265037 -45
testLazyShufflerProducesShuffledRange2() 9038716 9038738 22
testLazyShufflerRestart() 275009 274986 -23
testLazyShufflerRevertsOnDoubleInit() 71230 71218 -12
testLazyShufflerRevertsOnGrowAcrossWidthBoundary() 72845 - -
testLazyShufflerRevertsOnGrowAcrossWidthBoundaryUndrawn() 49408 - -
testLazyShufflerRevertsOnZeroLengthNext() 49940 49851 -89
testLazyShufflerWideProducesNoDuplicatesAcrossGrow() 262975 - -
testPRNGNext() 16226 16160 -66
testPRNGPartialShuffleDistribution() 7688656 7688699 43
testPRNGShuffle() 712296 712273 -23
testPRNGShuffleBytes() 217395 217417 22
testPRNGShuffleDistribution() 3088824 3088846 22
testPRNGShuffleGas() 1610968 1610923 -45
testStandardNormalWad() 4422920 4422897 -23
test__codesize() 15613 14379 -1234
LibSortTest testGroupSumSigned() 6156 - -
testHasDuplicateGas() 769634 769174 -460
testInsertionSortInts() 79973 79950 -23
testInsertionSortPsuedorandom() 63553 63575 22
testSearchSorted() 118069 118046 -23
testSearchSortedBasicCases() 2178 2200 22
testSearchSortedInts() 120068 120090 22
testSearchSortedWithEmptyArray() 721 677 -44
testSortAddressesReversed() 45520 45497 -23
testSortAddressesSorted() 41176 41133 -43
testSortInts() 887873 887851 -22
testSortMostlySame() 65967 65989 22
testSortOriginalMostlySame() 207232 207254 22
testSortOriginalSorted() 141641 141663 22
testSortPsuedorandom() 140070 140092 22
testSortSorted() 34564 34541 -23
testSortTestOverhead() 103257 103279 22
testSortedDifferenceDifferential() 182399 182422 23
testSortedIntersectionDifferential() 208324 208346 22
testUniquifySorted() 1660 1703 43
testUniquifySortedAddress() 4032 4010 -22
testUniquifySortedWithEmptyArray() 523 545 22
test__codesize() 26730 25386 -1344
LibStringTest testBytesToHexString() 4794 4772 -22
testFromAddressToHexString() 3155 3133 -22
testFromAddressToHexStringWithLeadingZeros() 3088 3154 66
testNormalizeSmallString() 1369 1347 -22
testSetAndGetStringStorage() 2361838 2334334 -27504
testSimpleStringSetAndGetGas() 1203210 1203200 -10
testStringConcat() 4259 4304 45
testStringDirectReturn() 11349 11415 66
testStringEscapeJSON() 38551 38596 45
testStringEscapeJSONHexEncode() 698380 689326 -9054
testStringIndexOf() 17811 17876 65
testStringIndicesOf() 12018 11964 -54
testStringIs7BitASCII() 203700 203678 -22
testStringIs7BitASCIIWithAllowedLookup() 4897 4875 -22
testStringLowerDifferential() 3173405 3222623 49218
testStringLowerOriginal() 1257 1235 -22
testStringPackAndUnpackOne() 735471 724980 -10491
testStringPackAndUnpackTwo() 4702727 982095 -3720632
testStringRepeat() 5276 5259 -17
testStringSlice() 9609 9587 -22
testStringSplit() 20444 20447 3
testStringUpperDifferential() 3401268 3157073 -244195
testStringUpperOriginal() 1256 1234 -22
testToHexStringFixedLengthPositiveNumberLong() 3696 3674 -22
testToHexStringFixedLengthPositiveNumberShort() 982 960 -22
testToHexStringPositiveNumber() 929 907 -22
testToMinimalHexStringNoPrefixPositiveNumber() 3481 3459 -22
testToMinimalHexStringNoPrefixUint256Max() 3419 3397 -22
testToMinimalHexStringUint256Max() 3487 3465 -22
testToSmallString() 5540 5563 23
testToStringPositiveNumberBrutalized() 585089 576036 -9053
testToStringSignedGas() 7234 7212 -22
testToStringUint256MaxBrutalized() 596610 587407 -9203
testToStringZero() 696 674 -22
testToStringZeroBrutalized() 584560 575508 -9052
testUint8AtStringStorage() 155461 155441 -20
test__codesize() 50892 50462 -430
LibTransientTest testEmptyStackPopReverts() 25131 25100 -31
testEmptyStackTopReverts() 3954 3879 -75
testRegistryAB() 450992 474501 23509
testRegistryNotDeployed() 145298 145233 -65
testSetAndGetBytesTransient() 51093 51071 -22
testStackPlacePopBytes() 38064 37865 -199
testUint256IncDecTransient() 182004 451064 269060
test__codesize() 24429 23261 -1168
SafeTransferLibTest testApproveWithMissingReturn() 54368 54380 12
testApproveWithNonContractReverts() 28475 28465 -10
testApproveWithRetry() 1064618 1064630 12
testApproveWithRetryWithNonContractReverts() 28946 28914 -32
testApproveWithReturnsFalseReverts() 31986 31998 12
testApproveWithReturnsTooLittleReverts() 31944 31934 -10
testApproveWithReturnsTooMuch() 54708 54657 -51
testApproveWithRevertingReverts() 31923 31924 1
testApproveWithStandardERC20() 54294 54306 12
testForceSafeTransferETH() 1497811 1497634 -177
testForceSafeTransferETHPooledWithdrawalStaysSolvent() 1081230 - -
testForceSafeTransferETHToRevertingRecipient() 745416 - -
testForceSafeTransferETHWithExactRefund() 602704 - -
testForceSafeTransferETHWithPartialRefund() 602649 - -
testTotalSupplyQuery() 59842 59926 84
testTransferAllETHToContractWithoutFallbackReverts() 32251 32235 -16
testTransferAllWithStandardERC20() 57219 57242 23
testTransferETH() 55619 55597 -22
testTransferETHToContractWithoutFallbackReverts() 32510 32494 -16
testTransferFromWithMissingReturn() 693578 694755 1177
testTransferFromWithNonContractReverts() 29814 29897 83
testTransferFromWithReturnsFalseReverts() 662566 663697 1131
testTransferFromWithReturnsTooLittleReverts() 662586 663697 1111
testTransferFromWithReturnsTooMuch() 694380 695578 1198
testTransferFromWithRevertingReverts() 652664 653774 1110
testTransferFromWithStandardERC20() 695036 696167 1131
testTransferWithMissingReturn() 680260 681458 1198
testTransferWithNonContractReverts() 28481 28471 -10
testTransferWithReturnsFalseReverts() 656870 658047 1177
testTransferWithReturnsTooLittleReverts() 657006 658116 1110
testTransferWithReturnsTooMuch() 680599 681688 1089
testTransferWithRevertingReverts() 657027 658158 1131
testTransferWithStandardERC20() 680740 681850 1110
testTryTransferAllETH() 228733 228689 -44
testTryTransferETH() 228692 228736 44
test__codesize() 74961 75035 74
SignatureCheckerLibTest testERC6492AllowSideEffectsPostDeploy() 636117 636129 12
testERC6492AllowSideEffectsPreDeploy() 671310 671322 12
testERC6492PostDeploy() 636424 636436 12
testERC6492PreDeploy() 1524744 1524780 36
testERC6492WithoutRevertingVerifier() 272486 272606 120
WETHTest testWithdrawToContractWithoutReceiveReverts() 233077 233065 -12

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