From 7d275157da2a7fc372008aabc890dcbfd14d83db Mon Sep 17 00:00:00 2001 From: Joseph Wood Date: Sat, 5 Dec 2026 15:31:23 -0500 Subject: [PATCH] perf: reduce ECM traversal and Tonelli-Shanks setup overhead Read ECM scalar bits directly instead of updating multiprecision masks. Use GMP's Legendre symbol for the Tonelli-Shanks nonresidue search, preserving curve calculations and selected roots. Add manual native regression checks and exact ECM factor tests for serial and parallel execution. --- .github/development/test-ecm-bit-traversal.R | 123 +++++++++++++++++++ .github/development/test-tonelli-shanks.R | 114 +++++++++++++++++ .github/development/testing.md | 56 +++++++++ NEWS.md | 2 + inst/NEWS.Rd | 4 + src/LenstraECM.cpp | 26 ++-- src/TonelliShanks.cpp | 9 +- tests/testthat/testPrimeFactorizeBig.R | 14 +++ 8 files changed, 323 insertions(+), 25 deletions(-) create mode 100644 .github/development/test-ecm-bit-traversal.R create mode 100644 .github/development/test-tonelli-shanks.R diff --git a/.github/development/test-ecm-bit-traversal.R b/.github/development/test-ecm-bit-traversal.R new file mode 100644 index 0000000..ea6e634 --- /dev/null +++ b/.github/development/test-ecm-bit-traversal.R @@ -0,0 +1,123 @@ +# Manual development checks; not invoked by R CMD check or CI. +# Rscript --vanilla .github/development/test-ecm-bit-traversal.R [source-root] + +main <- function(root) { + root <- normalizePath(root, winslash = "/", mustWork = TRUE) + source <- readLines(file.path(root, "src", "LenstraECM.cpp")) + first <- grep("^void ecm_add\\(", source) + multiply <- grep("^void ecm_multiply\\(", source) + after <- grep("^void InnerLoop\\(", source) + stopifnot(length(first) == 1L, length(multiply) == 1L, + length(after) == 1L, first < multiply, multiply < after) + + # Compile current production functions verbatim. The symbolic version + # substitutes only point addition/doubling, independently checking which + # scalar the production traversal computes without copying its bit loop. + arithmetic <- source[seq.int(first, after - 1L)] + traversal <- source[seq.int(multiply, after - 1L)] + symbolic <- ' +std::size_t additions = 0, doublings = 0; +void ecm_add(const mpz_class &x1, const mpz_class &x2, + const mpz_class &y1, const mpz_class &y2, + const mpz_class &, const mpz_class &, const mpz_class &, + mpz_class &t1, mpz_class &t2, mpz_class &, mpz_class &) { + ++additions; + t1 = x1 + y1; + t2 = x2 + y2; +} +void ecm_double(const mpz_class &x1, const mpz_class &x2, + const mpz_class &, const mpz_class &, const mpz_class &, + mpz_class &t1, mpz_class &t2, mpz_class &, mpz_class &) { + ++doublings; + t1 = 2 * x1; + t2 = 2 * x2; +} +' + wrapper <- ' +[[cpp11::register]] +bool check_ecm_bits(std::string scalar) { + const mpz_class k(scalar), z1 = 1, z2 = 2, c1 = 0, c2 = 0, n = 1000003; + if (k < 0) throw std::runtime_error("ECM scalars must be nonnegative"); + mpz_class x1 = z1, x2 = z2, t1, t2, t3, t4, q1, q2; + symbolic::additions = symbolic::doublings = 0; + symbolic::ecm_multiply(k, z1, z2, c1, c2, x1, x2, n, + t1, t2, t3, t4, q1, q2); + // Production uses positive k. Preserve the historical zero-input result + // too: it performs the initial doubling and leaves q at the input point. + const mpz_class expected = k > 0 ? k : mpz_class(1); + const std::size_t remaining = mpz_sizeinbase(k.get_mpz_t(), 2) - 1; + return q1 == expected && q2 == 2 * expected && + x1 == expected + 1 && x2 == 2 * (expected + 1) && + symbolic::additions == remaining && symbolic::doublings == remaining + 1; +} + +[[cpp11::register]] +cpp11::writable::strings ecm_coordinates(std::string scalar, std::string modulus) { + const mpz_class k(scalar), n(modulus); + // The production curve parameterization for seed s = 17. + const mpz_class u = 284, v = 68; + mpz_class x = u * u * u, z = v * v * v, t = v - u; + mpz_powm_ui(t.get_mpz_t(), t.get_mpz_t(), 3, n.get_mpz_t()); + const mpz_class c1 = (t * (3 * u + v)) % n, c2 = (4 * x * v) % n; + const mpz_class z1 = x, z2 = z; + mpz_class t1, t2, t3, t4, q1, q2; + arithmetic::ecm_multiply(k, z1, z2, c1, c2, x, z, n, + t1, t2, t3, t4, q1, q2); + return {x.get_str(), z.get_str(), q1.get_str(), q2.get_str()}; +} +' + code <- paste(c( + '#include ', '#include ', '#include ', + 'namespace arithmetic {', arithmetic, '}', + 'namespace symbolic {', symbolic, traversal, '}', wrapper + ), collapse = "\n") + oldLibs <- Sys.getenv("PKG_LIBS", unset = NA_character_) + on.exit(if (is.na(oldLibs)) Sys.unsetenv("PKG_LIBS") else + Sys.setenv(PKG_LIBS = oldLibs), add = TRUE) + Sys.setenv(PKG_LIBS = paste(Sys.getenv("PKG_LIBS"), "-lgmp")) + native <- new.env(parent = globalenv()) + cpp11::cpp_source(code = code, env = native, cxx_std = "CXX14") + + two <- gmp::as.bigz(2) + cases <- as.character(0:512) + for (bit in c(1L, 2L, 3L, 7L, 8L, 15L, 16L, 31L, 32L, 33L, + 63L, 64L, 65L, 127L, 128L, 129L, 255L, 256L, 257L)) { + boundary <- two^bit + cases <- c(cases, as.character(boundary + (-1:1)), + as.character(boundary + two^(bit %/% 2L) + 1L)) + } + # Long sparse, dense, and alternating patterns exercise sizes reached in + # later ECM stages, without a timing assertion or a full factorization. + dense <- two^65000L - 1L + cases <- unique(c(cases, as.character(two^64999L + two^32768L + 1L), + as.character(dense), as.character(dense %/% 3L))) + for (scalar in cases) stopifnot(native$check_ecm_bits(scalar)) + + # Exact projective outputs captured from the pre-change production helper + # at 6ff4e51; both adjacent ladder points must remain identical. + fixtures <- read.table(text = ' +1000003 1 997280 206483 22906304 314432 +1000003 2 938523 923418 997280 206483 +1000003 3 740001 371953 938523 923418 +1000003 4294967297 951532 402919 542491 806749 +1000003 18446744073709551617 169848 797596 747102 743960 +1000003 340282366920938463481821351505477763073 147971 288710 123029 59474 +1000036000099 1 436983308223 939719025631 22906304 314432 +1000036000099 2 83746189758 165136418823 436983308223 939719025631 +1000036000099 3 488780206335 639014288989 83746189758 165136418823 +1000036000099 4294967297 324623925398 963752294166 510117072836 242551534399 +1000036000099 18446744073709551617 689125237217 532937396401 134513150638 58148918404 +1000036000099 340282366920938463481821351505477763073 118026502049 33394388892 901637827934 743046288606 +', colClasses = "character") + for (i in seq_len(nrow(fixtures))) { + expected <- unname(unlist(fixtures[i, 3:6])) + stopifnot(identical(native$ecm_coordinates(fixtures[i, 2], fixtures[i, 1]), + expected)) + } + cat(sprintf("Passed %d ECM traversal cases and %d coordinate fixtures.\n", + length(cases), nrow(fixtures))) +} + +args <- commandArgs(trailingOnly = TRUE) +stopifnot(length(args) <= 1L) +main(if (length(args)) args[[1L]] else ".") diff --git a/.github/development/test-tonelli-shanks.R b/.github/development/test-tonelli-shanks.R new file mode 100644 index 0000000..a2d7b65 --- /dev/null +++ b/.github/development/test-tonelli-shanks.R @@ -0,0 +1,114 @@ +# Manual development checks; not invoked by R CMD check or CI. +# Rscript --vanilla .github/development/test-tonelli-shanks.R [source-root] +# The optional root permits comparison with the unoptimized checkout. + +main <- function(root) { + root <- normalizePath(root, winslash = "/", mustWork = TRUE) + source <- normalizePath(file.path(root, "src", "TonelliShanks.cpp"), + winslash = "/", mustWork = TRUE) + stopifnot(sum(grepl("^void TonelliShanksC\\(", readLines(source))) == 1L) + + # Include the production helper unchanged. No copy of its implementation + # or test-only entry point is added to the installed package. + wrapper <- ' +[[cpp11::register]] +cpp11::writable::strings run_tonelli_roots( + cpp11::strings values, cpp11::strings moduli +) { + if (values.size() != moduli.size()) { + cpp11::stop("Mismatched Tonelli fixture vectors"); + } + cpp11::writable::strings roots(values.size()); + mpz_class value, modulus, root; + for (R_xlen_t i = 0; i < values.size(); ++i) { + value = std::string(values[i]); + modulus = std::string(moduli[i]); + TonelliShanksC(value, modulus, root); + roots[i] = root.get_str(); + } + return roots; +} +' + code <- paste(c('#include ', + sprintf('#include %s', encodeString(source, quote = '"')), + wrapper), collapse = "\n") + oldLibs <- Sys.getenv("PKG_LIBS", unset = NA_character_) + on.exit(if (is.na(oldLibs)) Sys.unsetenv("PKG_LIBS") else + Sys.setenv(PKG_LIBS = oldLibs), add = TRUE) + Sys.setenv(PKG_LIBS = paste(Sys.getenv("PKG_LIBS"), "-lgmp")) + native <- new.env(parent = globalenv()) + cpp11::cpp_source(code = code, env = native, cxx_std = "CXX14") + + verify <- function(values, moduli, expected = NULL) { + stopifnot(length(values) == length(moduli), + all(values > 0), all(moduli > 2), + all(gmp::isprime(moduli) > 0)) + actual <- gmp::as.bigz(native$run_tonelli_roots( + as.character(values), as.character(moduli) + )) + # Congruence permits either signed representative. Exact fixtures + # below additionally preserve the root selected by the old helper. + stopifnot(all((actual * actual) %% moduli == values %% moduli), + all(abs(actual) < moduli)) + if (!is.null(expected)) stopifnot(identical(actual, expected)) + length(actual) + } + + # Exhaust every nonzero quadratic residue for odd primes through 257. + # Squaring 1..(p-1)/2 yields each residue exactly once. Repeat with inputs + # greater than p to exercise reduction without changing the residue. + smallPrimes <- (3L:257L)[gmp::isprime(gmp::as.bigz(3L:257L)) > 0L] + stopifnot(identical(sort(unique(smallPrimes %% 8L)), c(1L, 3L, 5L, 7L))) + values <- moduli <- integer(0) + for (p in smallPrimes) { + squares <- seq_len((p - 1L) %/% 2L)^2L %% p + values <- c(values, squares, squares + 17L * p) + moduli <- c(moduli, rep(p, 2L * length(squares))) + } + count <- verify(gmp::as.bigz(values), gmp::as.bigz(moduli)) + + # Exact roots recorded from baseline 6ff4e51. These cover all odd residue + # classes modulo 8 and 16-, 40-, and 101-digit prime moduli. The p=1 mod8 + # cases 73, 241, and 1009 need first nonresidues 5, 7, and 11 respectively. + # Store whether the baseline selected seed or its opposite modulo p. + moduli <- gmp::as.bigz(c( + "3", + "5", + "7", + "17", + "41", + "73", + "97", + "241", + "1009", + "1201", + "1000000000000241", + "1000000000000091", + "1000000000000037", + "1000000000000159", + "1000000000000000000000000000000000000081", + "1000000000000000000000000000000000000003", + "1000000000000000000000000000000000000037", + "1000000000000000000000000000000000000087", + "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002809", + "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000267", + "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000949", + "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001983" + )) + seeds <- gmp::as.bigz(c(2L, rep(11L, 9L), rep(123456789L, 12L))) + opposite <- c( + TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, + TRUE, FALSE, FALSE, FALSE, + FALSE, FALSE, TRUE, FALSE, + FALSE, FALSE, TRUE, TRUE + ) + expected <- seeds %% moduli + expected[opposite] <- moduli[opposite] - expected[opposite] + count <- count + verify(seeds^2L + 17L * moduli, moduli, expected) + cat(sprintf("All %d native Tonelli-Shanks cases passed (%d exact baseline roots).\n", + count, length(expected))) +} + +args <- commandArgs(trailingOnly = TRUE) +stopifnot(length(args) <= 1L) +main(if (length(args)) args[[1L]] else ".") diff --git a/.github/development/testing.md b/.github/development/testing.md index 7ac4ccd..ed0b319 100644 --- a/.github/development/testing.md +++ b/.github/development/testing.md @@ -137,6 +137,32 @@ Use fixed inputs for regressions and keep timing assertions out of correctness tests. For threaded algorithm changes, compare known factor lists and products in serial and parallel runs as appropriate to the changed path. +## ECM bit traversal native regression checks + +Run the development-only [runner](test-ecm-bit-traversal.R) from the repository +root: + +```sh +Rscript --vanilla .github/development/test-ecm-bit-traversal.R [source-root] +``` + +The optional source root defaults to the working directory. The runner extracts +`ecm_add()`, `ecm_double()`, and `ecm_multiply()` verbatim; unique source anchors +must remain valid. It also compiles the same traversal against symbolic +addition/doubling to independently verify scalar bit order and the number of +ladder steps. Cases include zero and one, small scalars, powers of two and their +neighbors across 32/64-bit boundaries, and sparse/dense/alternating scalars up +to 65,000 bits. Fixed pre-change projective-coordinate fixtures check the actual +curve arithmetic as well as the symbolic traversal. + +This runner uses the existing manual `cpp11::cpp_source()` prerequisites listed +below. It adds no installed package entry point, CI job, or package dependency; +`.github` remains excluded from the source archive. There are no timing +assertions or sanitizers. The public regression in +[testPrimeFactorizeBig.R](../../tests/testthat/testPrimeFactorizeBig.R) verifies +exact factors and reconstruction of a fixed input with one and two threads. +A baseline statistics run confirmed it survives initial rho and reaches ECM. + ## Constrained Pollard rho native regression checks Run the internal helper checks from the repository root: @@ -279,6 +305,36 @@ compare complete outputs outside the timed call. Record medians and any cleanup cost; keep timing assertions out of correctness tests. Results and source revisions belong in [DEFERRED_ISSUES.md](DEFERRED_ISSUES.md). +## Tonelli-Shanks native regression checks + +Run the internal root checks from the repository root: + +```sh +Rscript --vanilla .github/development/test-tonelli-shanks.R +``` + +The [runner](test-tonelli-shanks.R) includes the current production +`TonelliShanks.cpp` unchanged in a temporary `cpp11::cpp_source()` wrapper. +It requires the manual development dependencies listed for the rho runner, +plus GMP's headers and library. An optional source-root argument runs the +same checks against another checkout; the helper declaration must be unique. + +The cases exhaust nonzero quadratic residues for odd primes through 257, +with reduced and non-reduced inputs, and check their modular squares. +Twenty-two exact-root fixtures recorded from baseline `6ff4e51` additionally +cover all odd prime residue classes modulo 8, nonresidue searches requiring +candidates up to 11, and 16-, 40-, and 101-digit prime moduli. These preserve +which of the two roots the existing algorithm selects. The production change +only replaces the Euler-criterion powers used to search for a nonresidue; +the subsequent Tonelli-Shanks iterations remain unchanged. + +The existing fixed 162-bit semiprime regression in +[testQuadraticSieve.R](../../tests/testthat/testQuadraticSieve.R) checks exact +factors and reconstruction through MPQS in serial and parallel. The native +runner supplies direct coverage of the root-selection branches; it adds no +installed entry point and remains excluded from the package archive and CI. +No timing assertion, sanitizer, or additional CI dependency is used. + ## Native diagnostics and performance studies Run crash reproductions in separate R processes. For native helpers, retain diff --git a/NEWS.md b/NEWS.md index 253abe5..86c7751 100644 --- a/NEWS.md +++ b/NEWS.md @@ -13,6 +13,8 @@ ## Improvements +* Reduced ECM scalar-traversal overhead by reading bits directly while preserving curve calculations and search order. +* Reduced Tonelli–Shanks polynomial setup work by using GMP's Legendre symbol for the nonresidue search, preserving the selected roots. * Simplified parallel polynomial batch timing to use floating-point seconds while retaining the existing work estimates, 15/30-second budgets, and serial fallback. Batch sizes can differ near timing boundaries. * Added a load-time check that the compiled library version matches the R package version, with reinstall guidance for mismatched installations. * Added a package citation, available through `citation("RcppBigIntAlgos")`. diff --git a/inst/NEWS.Rd b/inst/NEWS.Rd index 99916f9..ce4206c 100644 --- a/inst/NEWS.Rd +++ b/inst/NEWS.Rd @@ -35,6 +35,10 @@ } \subsection{Improvements}{ \itemize{ + \item Reduced ECM scalar-traversal overhead by reading bits directly + while preserving curve calculations and search order. + \item Reduced Tonelli-Shanks polynomial setup work by using GMP's + Legendre symbol for the nonresidue search, preserving the selected roots. \item Simplified parallel polynomial batch timing to use floating-point seconds while retaining the existing work estimates, 15/30-second budgets, and serial fallback. Batch sizes can differ near timing boundaries. diff --git a/src/LenstraECM.cpp b/src/LenstraECM.cpp index e2463a5..670a10f 100644 --- a/src/LenstraECM.cpp +++ b/src/LenstraECM.cpp @@ -153,8 +153,7 @@ void ecm_multiply(const mpz_class &k, const mpz_class &z1, const mpz_class &c2, mpz_class &x1, mpz_class &x2, const mpz_class &n, mpz_class &t1, mpz_class &t2, mpz_class &t3, mpz_class &t4, - mpz_class &q1, mpz_class &q2, mpz_class &b, - mpz_class &test) { + mpz_class &q1, mpz_class &q2) { q1 = x1; q2 = x2; @@ -164,20 +163,11 @@ void ecm_multiply(const mpz_class &k, const mpz_class &z1, x1 = t1; x2 = t2; - b = k / 2; - test = -b; - test &= b; + // The initial points account for the leading bit; visit the rest in order. + for (mp_bitcnt_t bit = mpz_sizeinbase(k.get_mpz_t(), 2) - 1; bit > 0;) { + --bit; - while (cmp(b, test) > 0) { - b ^= test; - test = -b; - test &= b; - } - - for (; cmp(b, 0) > 0; b /= 2) { - test = b & k; - - if (cmp(test, 0)) { + if (mpz_tstbit(k.get_mpz_t(), bit)) { ecm_add(x1, x2, q1, q2, z1, z2, n, t1, t2, t3, t4); q1 = t1; @@ -205,9 +195,9 @@ void InnerLoop(std::size_t strt, std::size_t myEnd, const mpz_class &k, mpz_class &g, const mpz_class &n, std::vector &res, int idx) { - mpz_class u, v, x, z, b, t; + mpz_class u, v, x, z, t; mpz_class x1, x2, c1, c2, q1, q2; - mpz_class t1, t2, t3, t4, t5; + mpz_class t1, t2, t3, t4; for (unsigned long int s = strt; s < myEnd; ++s) { u = s * s - 5; @@ -227,7 +217,7 @@ void InnerLoop(std::size_t strt, std::size_t myEnd, const mpz_class &k, x2 = z; ecm_multiply(k, x1, x2, c1, c2, x, z, - n, t1, t2, t3, t4, q1, q2, b, t5); + n, t1, t2, t3, t4, q1, q2); g = gcd(q2, n); if (g > 1 && g < n) { diff --git a/src/TonelliShanks.cpp b/src/TonelliShanks.cpp index 3309a15..d65acfa 100644 --- a/src/TonelliShanks.cpp +++ b/src/TonelliShanks.cpp @@ -46,14 +46,9 @@ void TonelliShanksC( TS_3 = 2; TS_8 = 1; - TS_9 = TS_0 / 2; - mpz_powm(TS_1.get_mpz_t(), TS_3.get_mpz_t(), - TS_9.get_mpz_t(), p.get_mpz_t()); - - while (cmp(TS_1, 1) == 0) { + // The modulus is an odd prime; keep the same first nonresidue. + while (mpz_legendre(TS_3.get_mpz_t(), p.get_mpz_t()) == 1) { ++TS_3; - mpz_powm(TS_1.get_mpz_t(), TS_3.get_mpz_t(), - TS_9.get_mpz_t(), p.get_mpz_t()); } mpz_div_2exp(TS_9.get_mpz_t(), TS_0.get_mpz_t(), pow2); diff --git a/tests/testthat/testPrimeFactorizeBig.R b/tests/testthat/testPrimeFactorizeBig.R index 959481f..15adaec 100644 --- a/tests/testthat/testPrimeFactorizeBig.R +++ b/tests/testthat/testPrimeFactorizeBig.R @@ -68,6 +68,20 @@ test_that("primeFactorizeBig generates correct numbers with elliptic curve", { test2[order(asNumeric(test2))]) }) +test_that("primeFactorizeBig preserves exact ECM factors in serial and parallel", { + ## This fixed 25-digit input survives the initial bounded rho pass and + ## reaches ECM even though skipPolRho disables only extended rho. + expected <- as.bigz(c("1000000000039", "1000000000061")) + input <- prod(expected) + + for (threads in c(1L, 2L)) { + factors <- primeFactorizeBig(input, nThreads = threads, + skipPolRho = TRUE, skipECM = FALSE) + expect_identical(factors, expected) + expect_identical(prod(factors), input) + } +}) + test_that("primeFactorizeBig generates correct numbers with multiple threads", { capture.output(test <- nextprime(urand.bigz(2, 82, 8191)), file = nullfile())