diff --git a/.github/ISSUE_TEMPLATE/000-bug-report.yml b/.github/ISSUE_TEMPLATE/000-bug-report.yml index a74b000..015de1d 100644 --- a/.github/ISSUE_TEMPLATE/000-bug-report.yml +++ b/.github/ISSUE_TEMPLATE/000-bug-report.yml @@ -23,7 +23,7 @@ body: attributes: label: Bigmath-FFM Version description: The version of Bigmath-FFM you were using. - placeholder: "Example: 0.1.0" + placeholder: "Example: 0.2.0" validations: required: true - type: dropdown diff --git a/.github/workflows/publish-on-release.yml b/.github/workflows/publish-on-release.yml index fa0886a..047628e 100644 --- a/.github/workflows/publish-on-release.yml +++ b/.github/workflows/publish-on-release.yml @@ -33,7 +33,7 @@ jobs: uses: ./.github/workflows/native-artifacts.yml package: - name: Package and Verify the Release JAR + name: Package the Release JAR needs: native runs-on: ubuntu-latest permissions: @@ -77,7 +77,7 @@ jobs: retention-days: 7 github-release: - name: Upload Verified JAR to GitHub Release + name: Upload the Release JAR to GitHub Release needs: package runs-on: ubuntu-latest permissions: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c475e33..93ea2f0 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -64,7 +64,7 @@ jobs: - name: Read version id: version run: echo "value=$(grep -oP 'mod_version\s*=\s*\K.*' gradle.properties | tail -1)" >> "$GITHUB_OUTPUT" - - name: Publish the packaged JAR to Maven + - name: Publish the Java and Kotlin artifacts to Maven if: ${{ !inputs.simulate }} env: MAVEN_URL: ${{ secrets.MAVEN_URL }} @@ -75,6 +75,7 @@ jobs: test -n "$MAVEN_USER" test -n "$MAVEN_PASSWORD" ./gradlew publishMavenJavaPublicationToReleaseRepository \ + :bigmath-ffm-kt:publishMavenJavaPublicationToReleaseRepository \ "-PreleaseJarFile=${{ steps.jar.outputs.path }}" \ -x releaseJar -x cmakeConfigure -x buildNative -x copyNativeLib -x processResources diff --git a/CHANGELOG.md b/CHANGELOG.md index e1ada83..3cde2db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,26 +1,73 @@ # Changelog -## [Unreleased] +## [0.2.0] - 2026-08-31 ### Added -- Initial project structure with Gradle version catalog and modular scripts -- BigInt wrapper for GMP `mpz_t` via Java FFM API -- BigDeci wrapper for MPFR `mpfr_t` via Java FFM API -- Int128 type with native C++ implementation -- Locale-aware formatting for BigInt, BigDeci, Int128 -- Immutable `BigNumberFormat` API with `DecimalFormat` patterns, locale symbols, compact units, scientific fallback, and all supported numeric inputs -- Native formatting pipeline shared by BigInt, BigDeci, Int128, primitive, and JDK big-number inputs -- Multi-platform CMake native library build -- Tiered multiplication algorithms: schoolbook → Karatsuba → NTT/FFT -- Binary GCD, fast exponentiation by squaring, product tree factorial -- GitHub Actions CI with PR label-driven workflows -- vcpkg manifest for Windows dependency management -- Six-platform release artifacts with one JAR shared by GitHub Releases and Maven + +- Immutable, thread-safe `BigNumberFormat` with `DecimalFormat` patterns, + localized patterns and symbols, currency/percent/per-mille affixes, compact + units, milli input, application units, scientific fallback, all Java rounding + modes, and overloads for Bigmath, primitive, and JDK big-number inputs. +- Native descriptor-driven formatting pipeline and bounded per-formatter result + cache keyed by Native handle ID/version or Int128 words. +- `BigmathRuntime`, `RuntimeOptions`, and immutable `RuntimeDiagnostics` for + Java-only configuration, asynchronous initialization, capability reporting, + product-cache metrics, calibration state, thresholds, workspace use, and CPU + fallback counts. +- Thread-confined `NativeCalculationScope` and scoped Kotlin BigInt/BigDeci + expression DSLs that automatically release intermediate Native handles. +- Native handle IDs and mutation versions, direct handle-returning FFM calls, + byte-based `BigInteger`/`BigDecimal` interop, and explicit no-GMP capability + errors. +- Adaptive process-wide product cache with canonical handle/version/backend keys, + two-hit admission, a 16-result/64 MiB byte-LRU budget, and diagnostics. +- Bounded per-device CUDA workspace pools with explicit streams, caller-managed + cuFFT work areas, pinned transfers, asynchronous copies, calibrated CPU/cuFFT/ + NTT dispatch, and persistent hardware-specific calibration profiles. +- GPU-resident sliding-window modular exponentiation using Montgomery reduction + for odd moduli and Barrett reduction for even moduli, with atomic CPU fallback. +- Six release classifiers: Linux, macOS, and Windows on x86-64 and aarch64. Full + release artifacts include GMP/MPFR and architecture-matched runtime notices. ### Changed -- Number formatting now compiles Java pattern and locale metadata once and performs numeric conversion, scaling, rounding, grouping, localization, and output assembly in Native code -- Formatter result caching uses Native handle ID/version keys for BigInt and BigDeci and word keys for Int128 -- Accelerated product results now use canonical handle ID/version/backend keys, two-hit admission, and a process-wide 16-entry/64 MiB byte-LRU cache with diagnostic metrics + +- This is a breaking Java, Kotlin, Native binding, and platform-support release. +- Number formatting now compiles pattern/locale metadata in Java once; all actual + conversion, scaling, rounding, grouping, digit localization, and assembly run + in Native code. +- BigInt parsing and `doubleValue()` no longer require decimal Native round trips; + full-width Int128 division and portable MSVC multiplication were corrected and + optimized. +- BigDeci GPU multiplication reuses significand scratch and returns directly to + MPFR when the calibrated CUDA attempt is unavailable or fails. +- Runtime backend/device/cache/calibration policy is configured exclusively via + Java API. Calibration completes before AUTO dispatch enables a candidate GPU + path and NTT remains bounded by its valid `2^23` transform order. +- `native/` is an ignored staging area for remote artifacts. Release packaging + aggregates those six artifacts with Gradle and does not build Native code in + the packaging job. +- Windows release artifacts use MSVC and retain the architecture-matched + Microsoft and GNU/MinGW runtime closure required on minimal hosts, including + libstdc++, libgcc, and winpthreads notices. ### Removed -- Removed `BigInt`, `BigDeci`, and `Int128` `toFormattedString(...)`; use `BigNumberFormat.ofPattern(...)`, `readable()`, or `scientific()` + +- Removed `BigInt`, `BigDeci`, and `Int128` `toFormattedString(...)`; use + `BigNumberFormat.ofPattern(...)`, `readable()`, or `scientific()`. +- Removed global Kotlin BigInt/BigDeci operators; use `bigIntExpression` and + `bigDeciExpression`. Int128 operators remain global. +- Removed Android and all unknown/implicit platform fallbacks. Unsupported hosts + now fail before attempting to load Native code. +- Removed old formatting descriptors/exports/caches and unused custom Karatsuba, + binary GCD, product-tree factorial, and generic convolution implementations. +- Removed runtime CUDA environment switches and load-time CUDA probing. + +### Fixed + +- Corrected CUDA dispatch so both operand sizes participate in the cost decision. +- Corrected NTT root-order bounds, shared workspace accounting, and pool + saturation fallback. +- Corrected JAR Native extraction, same-directory dependency staging, and cleanup + behavior for packaged resources. +- Corrected Windows portable low-128 multiplication and added architecture-specific + MSVC paths where supported. diff --git a/README.md b/README.md index 5b43330..b1538c2 100644 --- a/README.md +++ b/README.md @@ -13,11 +13,20 @@ Cross-platform high-performance big integer & decimal library for Java FFM (back ## Supported Platforms -| OS | Architecture | GMP/MPFR | Int128 | -|---------|-----------------|--------------------------------------|----------| -| Linux | x86-64, aarch64 | `apt install libgmp-dev libmpfr-dev` | built-in | -| macOS | x86-64, aarch64 | `brew install gmp mpfr` | built-in | -| Windows | x86-64, aarch64 | vcpkg (`x64-windows` / `arm64-windows`) with MSVC | built-in | +Bigmath-FFM 0.2.0 supports exactly these release classifiers: + +| OS | Architectures | Classifiers | +|---------|---------------|-------------| +| Linux | x86-64, aarch64 | `linux-x86-64`, `linux-aarch64` | +| macOS | x86-64, aarch64 | `macos-x86-64`, `macos-aarch64` | +| Windows | x86-64, aarch64 | `windows-x86-64`, `windows-aarch64` | + +Release artifacts include GMP, MPFR, and the architecture-matched runtime +libraries needed on a minimal host. Android, 32-bit targets, RISC-V, and other +OS/architecture combinations fail before Native loading. + +Linux glibc and macOS deployment baselines follow the current GitHub-hosted +runner toolchains. They are not frozen and can move when runner images change. ## Quick Start @@ -26,14 +35,15 @@ import com.modularmc.bigmath.BigInt; import com.modularmc.bigmath.BigDeci; import com.modularmc.bigmath.BigNumberFormat; -BigInt a = BigInt.fromString("12345678901234567890", 10); -BigInt b = BigInt.fromLong(42); -BigInt sum = a.add(b); -System.out.println(sum); // 12345678901234567932 -System.out.println(BigNumberFormat.readable().format(sum)); // compact output - -BigDeci pi = BigDeci.fromString("3.141592653589793", 128); -BigDeci area = pi.multiply(pi); +try (BigInt a = BigInt.fromString("12345678901234567890", 10); + BigInt b = BigInt.fromLong(42); + BigInt sum = a.add(b); + BigDeci pi = BigDeci.fromString("3.141592653589793", 128); + BigDeci area = pi.multiply(pi)) { + System.out.println(sum); // 12345678901234567932 + System.out.println(BigNumberFormat.readable().format(sum)); + System.out.println(area); +} ``` ### Number formatting @@ -72,6 +82,35 @@ The 0.2.0 migration from the removed instance formatting methods is: | Readable compact units | `BigNumberFormat.readable().format(value)` | | Scientific output | `BigNumberFormat.scientific().format(value)` | +### Runtime configuration and diagnostics + +Runtime options are configured only through Java, before the first Native-backed +value is initialized. There are no environment-variable or system-property +overrides for cache, device, calibration, or backend policy. + +```java +import com.modularmc.bigmath.BigmathRuntime; +import com.modularmc.bigmath.RuntimeDiagnostics; +import com.modularmc.bigmath.RuntimeOptions; + +BigmathRuntime.configure(RuntimeOptions.builder() + .productCacheEnabled(true) + .cpuProductCacheBytes(64L * 1024 * 1024) + .automaticCudaDevice() + .cudaBackend(RuntimeOptions.CudaBackend.AUTO) + .build()); + +RuntimeDiagnostics diagnostics = BigmathRuntime.initializeAsync().join(); +System.out.println(diagnostics.cuda().statusMessage()); +``` + +The default AUTO policy keeps candidate operations on CPU until calibration is +ready. Calibration profiles are invalidated by Native build, ABI, CPU, GPU UUID, +driver/runtime, GMP, and MPFR identity and are stored with an OS-standard cache +path, process lock, and validated same-directory replacement. Device workspaces +share a bounded per-device budget. NTT is selected only for calibrated transform sizes where it +is correct and consistently at least 10% faster than cuFFT. + ### Kotlin expressions BigInt and BigDeci operators are available only inside their calculation @@ -87,13 +126,16 @@ The caller remains responsible for closing `integerResult` and `decimalResult`. Int128 operators remain available globally because Int128 does not allocate a native handle per result. +See [Migrating to Bigmath-FFM 0.2.0](docs/migration-0.2.0.md) for the complete +breaking-change and replacement guide. + ## Building ### Prerequisites - Java 23+ -- CMake 3.20+ -- GMP 6.x + MPFR 4.x (optional; stubs built otherwise) +- CMake 3.21+ +- GMP 6.x + MPFR 4.x for a full BigInt/BigDeci build - CUDA Toolkit with `nvcc` for experimental CUDA builds on Linux x86-64 or Windows x86-64 ### Gradle @@ -102,14 +144,33 @@ not allocate a native handle per result. ./gradlew assemble ``` -Native libraries are built automatically via CMake. Set `-DUSE_GMP=OFF` to skip GMP/MPFR. +`assemble` builds the current host's full Native library through CMake. The +release pipeline instead runs `releaseJar` against the six downloaded remote +artifacts and does not rebuild Native code in the packaging job. + +The normal Gradle build requires GMP/MPFR and fails when they are unavailable. +The explicit Int128-only developer mode is a direct CMake configuration: + +```bash +cmake -S src/main/cpp -B build/native -DUSE_GMP=OFF +cmake --build build/native --target install +``` + +`USE_GMP=OFF` is not a release configuration and does not provide BigInt or +BigDeci capability. + +For repository development, `native/` is an ignored staging area for artifacts +downloaded from remote CI. Local verification should compile Java/Kotlin and use +those downloaded binaries; project development does not require a local Native +build. ### Experimental CUDA -This branch contains experimental CUDA acceleration for the BigInt multiplication path. -On Linux x86-64 and Windows x86-64, native configuration requires the CUDA toolkit and -links against CUDA runtime and cuFFT. Windows builds use MSVC and the `x64-windows` -vcpkg triplet. +CUDA-enabled development artifacts are produced separately for Linux x86-64 and +Windows x86-64. The standard six-platform release JAR remains usable without a +CUDA runtime. CUDA builds use cuFFT plus an exact dual-prime NTT path, bounded +workspace pools, calibrated dispatch, GPU-resident odd/even modular +exponentiation, and CPU fallback before any partial result is exposed. ```bash cmake --preset cuda-linux-release @@ -121,10 +182,10 @@ cmake --preset cuda-windows-msvc-release cmake --build build/native --target install ``` -Set `BIGMATH_CUDA_ARCH` or pass `-PbigmathCudaArch=` to override the default -`native` CUDA architecture detection. At runtime the native library probes CUDA once -when it is loaded, caches the device status, and automatically falls back to the CPU -path when no usable CUDA device is available. +Pass `-PbigmathCudaArch=` when a remote or direct Gradle Native build needs +an explicit architecture list. Runtime backend selection is performed only with +`RuntimeOptions`; legacy environment switches such as `BIGMATH_CUDA_NTT` are not +supported. Gradle can also discover common local tool paths when they are not on `PATH`, including CLion's bundled CMake/Ninja and the default Windows CUDA Toolkit install directory. @@ -166,12 +227,16 @@ closure needed on a minimal host. This includes the Microsoft VC++ runtime and, when required by GMP, MPFR, or another bundled dependency, the GNU libstdc++, libgcc, and MinGW-w64 winpthreads runtimes together with their notices. -Users can replace compatible shared libraries by: +Advanced users can point the loader at a replacement library by: - setting `-Dbigmath.native.path=/absolute/path/to/library` - replacing files in `native//` - using the normal platform library search path +The replacement must match the Java bindings shipped in the same release. +Bigmath-FFM does not promise compatibility for an external C ABI or for Native +libraries taken from another release/build. + Third-party component notices and source pointers are documented in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and packaged into `META-INF/THIRD_PARTY_NOTICES.md` in built resources. diff --git a/bigmath-ffm-kt/build.gradle b/bigmath-ffm-kt/build.gradle index 94b3f38..2edcf13 100644 --- a/bigmath-ffm-kt/build.gradle +++ b/bigmath-ffm-kt/build.gradle @@ -38,6 +38,19 @@ publishing { } } } + + if (System.getenv("MAVEN_URL")) { + repositories { + maven { + name = "release" + url = uri(System.getenv("MAVEN_URL")) + credentials { + username = System.getenv("MAVEN_USER") + password = System.getenv("MAVEN_PASSWORD") + } + } + } + } } tasks.withType(JavaCompile).configureEach { diff --git a/docs/migration-0.2.0.md b/docs/migration-0.2.0.md new file mode 100644 index 0000000..dbbcc58 --- /dev/null +++ b/docs/migration-0.2.0.md @@ -0,0 +1,113 @@ +# Migrating to Bigmath-FFM 0.2.0 + +Bigmath-FFM 0.2.0 is a breaking Java, Kotlin, Native binding, and platform +release. Java callers should rebuild against 0.2.0 and deploy the Java classes +and Native artifacts from the same build together. + +## Supported platforms + +The supported classifiers are exactly: + +- `linux-x86-64` +- `linux-aarch64` +- `macos-x86-64` +- `macos-aarch64` +- `windows-x86-64` +- `windows-aarch64` + +Android and all other OS/architecture combinations are unsupported and now fail +before Native loading. Release artifacts provide full GMP/MPFR capability. The +explicit `USE_GMP=OFF` CMake mode remains an Int128-only developer build and is +not a release artifact. + +## Number formatting + +The instance `toFormattedString(...)` methods on `BigInt`, `BigDeci`, and +`Int128` were removed. Create an immutable formatter and reuse it: + +```java +BigNumberFormat grouped = BigNumberFormat.ofPattern("#,##0"); +String text = grouped.format(value); +``` + +Migration mapping: + +| Previous behavior | 0.2.0 replacement | +|---|---| +| Grouped integer output | `BigNumberFormat.ofPattern("#,##0").format(value)` | +| Compact unit output | `BigNumberFormat.readable().format(value)` | +| Scientific output | `BigNumberFormat.scientific().format(value)` | + +`ofPattern(...)` follows ordinary `DecimalFormat` pattern and locale behavior; +it does not add compact suffixes. Use `compactUnits(true)` only when compact +1000-based suffixes are wanted. A formatter captures the FORMAT locale when it +is built and does not follow later default-locale changes. + +## Runtime configuration + +Cache, CUDA device/backend, workspace, and calibration options are configured +only through Java. Configure before the first `BigInt` or `BigDeci` use: + +```java +BigmathRuntime.configure(RuntimeOptions.builder() + .productCacheEnabled(true) + .cpuProductCacheBytes(64L * 1024 * 1024) + .gpuWorkspaceFraction(0.25) + .gpuWorkspaceMaxBytes(512L * 1024 * 1024) + .automaticCudaDevice() + .cudaBackend(RuntimeOptions.CudaBackend.AUTO) + .build()); + +RuntimeDiagnostics diagnostics = BigmathRuntime.initializeAsync().join(); +``` + +Calling `configure` after Native initialization has started throws +`IllegalStateException`. Runtime environment variables and system properties no +longer override these policies. `bigmath.native.path` remains a loader location, +not a runtime tuning option. + +## Kotlin expressions + +Global BigInt and BigDeci arithmetic operators were removed because every +intermediate operator result owns a Native handle. Use scoped expressions: + +```kotlin +val integerResult = bigIntExpression { a + b * c } +val decimalResult = bigDeciExpression { x / y + z } +``` + +The lambda result is detached and returned to the caller; other intermediates +are closed automatically. The caller must close the returned value. Int128 +operators remain global because Int128 values do not own Native handles. + +Java code can use `NativeCalculationScope` directly when a calculation creates +several temporary BigInt or BigDeci values. Ordinary allocating methods and +`set`/`*Into` remain available; continue closing every owned value. + +## BigInteger and BigDecimal interop + +Interop no longer transfers decimal strings. `BigInteger` uses two's-complement +bytes, while `BigDecimal` uses unscaled two's-complement bytes plus scale. No +source change is required for callers using the public conversion methods, but +Java and Native components from older releases must not be mixed. + +## Native artifacts and ABI + +Native handles now carry an ID and mutation version and FFM constructors and +arithmetic exports return handles directly. Old Native libraries are rejected +by the ABI handshake. Bigmath-FFM does not promise an external C ABI or +cross-release Native compatibility. + +`bigmath.native.path` can still select an explicit library, but that library and +its same-directory dependencies must come from a build compatible with the +current Java bindings. Windows minimal-host packages retain the Microsoft VC++ +runtime plus any required GNU libstdc++, libgcc, and MinGW-w64 winpthreads DLLs +and notices. + +## Repository build workflow + +The repository `native/` directory is ignored and is used to stage remote CI +artifacts for local Java/public-API verification. Release packaging aggregates +the six remote artifacts with Gradle and does not build Native code in the +packaging job. Local Native builds are not required for normal project +development. diff --git a/gradle.properties b/gradle.properties index ddd76a6..c3318ba 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,7 +5,7 @@ org.gradle.caching = true mod_id = bigmathffm mod_name = BigmathFFM -mod_version = 0.1.0 +mod_version = 0.2.0 mod_description = Cross-platform high-performance big integer & decimal library for Java FFM mod_license = GNU LGPL 3.0 mod_url = https://github.com/ModularMCLib/Bigmath-FFM diff --git a/src/main/cpp/algos.cpp b/src/main/cpp/algos.cpp index b38963a..fafa520 100644 --- a/src/main/cpp/algos.cpp +++ b/src/main/cpp/algos.cpp @@ -2,7 +2,6 @@ #include "cuda_convolution.h" #include "cuda_runtime_state.h" #include -#include #include #include #include @@ -16,184 +15,8 @@ namespace bigmath { -// ---- Helper: add/sub limb arrays (no GMP dependency) ---- -static void add_limbs(limb_t *out, const limb_t *a, int n) { - if (!out || !a || n <= 0) return; - limb_t carry = 0; - for (int i = 0; i < n; i++) { - limb_t sum = out[i] + a[i] + carry; - carry = (sum < a[i] || (carry && sum == a[i])) ? 1 : 0; - out[i] = sum; - } - for (int i = n; carry; i++) { - limb_t sum = out[i] + carry; - carry = (sum < carry) ? 1 : 0; - out[i] = sum; - } -} - -static void sub_limbs(limb_t *out, const limb_t *a, int n) { - if (!out || !a || n <= 0) return; - limb_t borrow = 0; - for (int i = 0; i < n; i++) { - limb_t diff = out[i] - a[i] - borrow; - borrow = (out[i] < a[i] + borrow) ? 1 : 0; - out[i] = diff; - } - for (int i = n; borrow; i++) { - limb_t diff = out[i] - borrow; - borrow = (out[i] < borrow) ? 1 : 0; - out[i] = diff; - } -} - -// ---- Schoolbook multiplication (base case for Karatsuba) ---- -static void schoolbook_mul(limb_t *out, const limb_t *a, int alen, const limb_t *b, int blen) { - if (!out || !a || !b || alen <= 0 || blen <= 0) return; - for (int i = 0; i < alen + blen; i++) out[i] = 0; - for (int i = 0; i < alen; i++) { - uint64_t carry = 0; - uint32_t a_lo32 = (uint32_t)a[i]; - uint32_t a_hi32 = (uint32_t)(a[i] >> 32); - for (int j = 0; j < blen; j++) { - uint32_t b_lo32 = (uint32_t)b[j]; - uint32_t b_hi32 = (uint32_t)(b[j] >> 32); - - uint64_t p00 = (uint64_t)a_lo32 * b_lo32; - uint64_t p01 = (uint64_t)a_lo32 * b_hi32; - uint64_t p10 = (uint64_t)a_hi32 * b_lo32; - uint64_t p11 = (uint64_t)a_hi32 * b_hi32; - - uint64_t mid = p01 + p10; - uint64_t mid_carry = (mid < p01) ? (1ULL << 32) : 0; - - uint64_t mid_lo = (mid & 0xFFFFFFFFULL) << 32; - uint64_t mid_hi = (mid >> 32) | mid_carry; - - uint64_t lo = p00 + mid_lo; - uint64_t lo_carry = (lo < p00) ? 1ULL : 0ULL; - uint64_t hi = p11 + mid_hi + lo_carry + carry; - - lo += out[i + j]; - if (lo < out[i + j]) hi++; - - out[i + j] = lo; - carry = hi; - } - out[i + blen] += carry; - } -} - -// ---- Karatsuba Multiplication (O(n^1.585), no GMP dependency) ---- -void karatsuba_mul(limb_t *out, const limb_t *a, int alen, const limb_t *b, int blen) { - if (alen == 0 || blen == 0) return; - if (alen == 1 && blen == 1) { - out[0] = a[0] * b[0]; - out[1] = 0; - return; - } - if (alen + blen <= KARATSUBA_THRESHOLD) { - schoolbook_mul(out, a, alen, b, blen); - return; - } - - int n = (std::max(alen, blen) + 1) / 2; - int a_lo_len = std::min(n, alen); - int a_hi_len = std::max(0, alen - n); - int b_lo_len = std::min(n, blen); - int b_hi_len = std::max(0, blen - n); - - const limb_t *a_lo = a; - const limb_t *a_hi = a + n; - const limb_t *b_lo = b; - const limb_t *b_hi = b + n; - - int sum_a_len = std::max(a_lo_len, a_hi_len) + 1; - int sum_b_len = std::max(b_lo_len, b_hi_len) + 1; - int max_size = 2 * n * 2; - auto sum_a = limb_alloc(sum_a_len); - auto sum_b = limb_alloc(sum_b_len); - auto prod_lo = limb_alloc(max_size); - auto prod_sum = limb_alloc(max_size); - - if (!sum_a || !sum_b || !prod_lo || !prod_sum) { - free(sum_a); free(sum_b); free(prod_lo); free(prod_sum); - return; - } - - for (int i = 0; i < sum_a_len; i++) sum_a[i] = 0; - if (a_lo_len > 0) memcpy(sum_a, a_lo, a_lo_len * sizeof(limb_t)); - if (a_hi_len > 0) add_limbs(sum_a, a_hi, a_hi_len); - - for (int i = 0; i < sum_b_len; i++) sum_b[i] = 0; - if (b_lo_len > 0) memcpy(sum_b, b_lo, b_lo_len * sizeof(limb_t)); - if (b_hi_len > 0) add_limbs(sum_b, b_hi, b_hi_len); - - // prod_lo = a_lo * b_lo (in low half) - karatsuba_mul(prod_lo, a_lo, a_lo_len, b_lo, b_lo_len); - - // prod_hi = a_hi * b_hi (in high half) - karatsuba_mul(prod_lo + 2 * n, a_hi, a_hi_len, b_hi, b_hi_len); - - // prod_sum = sum_a * sum_b - int sa_actual = sum_a_len; - while (sa_actual > 0 && sum_a[sa_actual - 1] == 0) sa_actual--; - if (sa_actual == 0) sa_actual = 1; - int sb_actual = sum_b_len; - while (sb_actual > 0 && sum_b[sb_actual - 1] == 0) sb_actual--; - if (sb_actual == 0) sb_actual = 1; - karatsuba_mul(prod_sum, sum_a, sa_actual, sum_b, sb_actual); - - // middle = prod_sum - prod_lo - prod_hi_shifts - sub_limbs(prod_sum, prod_lo, max_size); - sub_limbs(prod_sum, prod_lo + 2 * n, max_size - 2 * n); - - // out = prod_lo + middle << n + prod_hi << 2n - for (int i = 0; i < max_size; i++) out[i] = 0; - memcpy(out, prod_lo, (a_lo_len + b_lo_len) * sizeof(limb_t)); - add_limbs(out + n, prod_sum, max_size - n); - - free(sum_a); - free(sum_b); - free(prod_lo); - free(prod_sum); -} - #ifndef BIGMATH_NO_GMP -// ---- Binary GCD (Stein's algorithm) ---- -void binary_gcd(mpz_ptr out, mpz_ptr a, mpz_ptr b) { - if (mpz_sgn(a) == 0) { mpz_set(out, b); mpz_abs(out, out); return; } - if (mpz_sgn(b) == 0) { mpz_set(out, a); mpz_abs(out, out); return; } - - mpz_t u, v; - mpz_init_set(u, a); - mpz_init_set(v, b); - mpz_abs(u, u); - mpz_abs(v, v); - - int shift = 0; - while (mpz_even_p(u) && mpz_even_p(v)) { - mpz_tdiv_q_2exp(u, u, 1); - mpz_tdiv_q_2exp(v, v, 1); - shift++; - } - while (mpz_sgn(u) != 0) { - while (mpz_even_p(u)) mpz_tdiv_q_2exp(u, u, 1); - while (mpz_even_p(v)) mpz_tdiv_q_2exp(v, v, 1); - if (mpz_cmp(u, v) >= 0) { - mpz_sub(u, u, v); - mpz_tdiv_q_2exp(u, u, 1); - } else { - mpz_sub(v, v, u); - mpz_tdiv_q_2exp(v, v, 1); - } - } - mpz_mul_2exp(out, v, shift); - mpz_clear(u); - mpz_clear(v); -} - // ---- Exponentiation by Squaring ---- void fast_pow(mpz_ptr out, mpz_ptr base, uint64_t exp) { mpz_set_ui(out, 1); @@ -339,37 +162,6 @@ void modpow(mpz_ptr out, mpz_ptr base, mpz_ptr exp, mpz_ptr mod) { mpz_powm(out, base, exp, mod); } -// ---- Product Tree Factorial ---- -static void product_tree(mpz_ptr out, uint64_t a, uint64_t b) { - if (a == b) { - mpz_set_ui(out, a); - return; - } - if (a + 1 == b) { - mpz_set_ui(out, a); - mpz_mul_ui(out, out, b); - return; - } - uint64_t mid = a + (b - a) / 2; - mpz_t left, right; - mpz_init(left); - mpz_init(right); - product_tree(left, a, mid); - product_tree(right, mid + 1, b); - mpz_mul(out, left, right); - mpz_clear(left); - mpz_clear(right); -} - -void product_tree_factorial(mpz_ptr out, uint64_t n) { - if (n <= 1) { mpz_set_ui(out, 1); return; } - if (n < 128) { - mpz_fac_ui(out, n); - return; - } - product_tree(out, 2, n); -} - static void export_abs_mpz_to_u16_digits(mpz_ptr value, mp_bitcnt_t bits, std::vector &out); static void export_abs_mpz_to_digits(mpz_ptr value, mp_bitcnt_t bits, unsigned bits_per_digit, std::vector &out); @@ -944,9 +736,7 @@ void accelerated_mul( #else // Stubs when GMP not available -void binary_gcd(mpz_ptr, mpz_ptr, mpz_ptr) {} void fast_pow(mpz_ptr, mpz_ptr, uint64_t) {} -void product_tree_factorial(mpz_ptr, uint64_t) {} void fft_multiply(mpz_ptr, mpz_ptr, mpz_ptr, const caching::ProductCacheKey *) {} void fft_multiply_into(mpz_ptr, mpz_ptr, mpz_ptr, const caching::ProductCacheKey *) {} void accelerated_mul(mpz_ptr, mpz_ptr, mpz_ptr, const caching::ProductCacheKey *) {} diff --git a/src/main/cpp/algos.h b/src/main/cpp/algos.h index 7b580cd..a6d10ae 100644 --- a/src/main/cpp/algos.h +++ b/src/main/cpp/algos.h @@ -4,9 +4,6 @@ #include "caching/product_cache.h" #include -#include -#include -#include #if __has_include() #include @@ -19,25 +16,15 @@ typedef struct __bigmath_mpz *mpz_ptr; namespace bigmath { -constexpr int KARATSUBA_THRESHOLD = 32; -constexpr int ALGO_THRESHOLD = 64; -constexpr int NTT_THRESHOLD = 4096; - -using limb_t = uint64_t; +constexpr int NTT_THRESHOLD = 4096; enum class DirectCudaBackend { CUFFT, NTT }; -void karatsuba_mul(limb_t *out, const limb_t *a, int alen, const limb_t *b, int blen); - -void binary_gcd(mpz_ptr out, mpz_ptr a, mpz_ptr b); - void fast_pow(mpz_ptr out, mpz_ptr base, uint64_t exp); -void product_tree_factorial(mpz_ptr out, uint64_t n); - void fft_multiply( mpz_ptr out, mpz_ptr a, @@ -80,10 +67,6 @@ bool cuda_dispatch_favorable(uint64_t left_bits, uint64_t right_bits, bool squar void modpow(mpz_ptr out, mpz_ptr base, mpz_ptr exp, mpz_ptr mod); -inline limb_t *limb_alloc(int n) { - return static_cast(calloc(n, sizeof(limb_t))); -} - } #endif /* BIGMATH_ALGOS_H */ diff --git a/src/main/java/com/modularmc/bigmath/BigDeci.java b/src/main/java/com/modularmc/bigmath/BigDeci.java index a894912..b8a59fd 100644 --- a/src/main/java/com/modularmc/bigmath/BigDeci.java +++ b/src/main/java/com/modularmc/bigmath/BigDeci.java @@ -17,6 +17,11 @@ * {@link #close()} to free the underlying resource. A cleaner is retained only * as a fallback for abandoned owned values. *

+ * The ordinary arithmetic methods allocate and return a new native-backed + * value, leaving the original operands unchanged. For hot loops, {@code set} + * and {@code *Into} methods mutate the current native value so callers can + * reuse an existing result object and avoid repeated native allocations. + *

* Constants {@link #ZERO}, {@link #ONE}, {@link #TWO}, {@link #TEN}, and * {@link #NEGATIVE_ONE} are permanent read-only handles and reject both * mutation and {@link #close()}. diff --git a/src/main/java/com/modularmc/bigmath/BigmathFFM.java b/src/main/java/com/modularmc/bigmath/BigmathFFM.java index 827b29b..32ce0c2 100644 --- a/src/main/java/com/modularmc/bigmath/BigmathFFM.java +++ b/src/main/java/com/modularmc/bigmath/BigmathFFM.java @@ -174,7 +174,7 @@ MethodHandle requiredMetadataDowncall(String name, FunctionDescriptor descriptor return lookup.find(name) .map(symbol -> linker.downcallHandle(symbol, descriptor)) .orElseThrow(() -> new LinkageError( - "Loaded Bigmath native library does not expose ABI v2 metadata symbol: " + name + "Loaded Bigmath native library does not expose required ABI metadata symbol: " + name )); } diff --git a/src/main/java/com/modularmc/bigmath/BigmathRuntime.java b/src/main/java/com/modularmc/bigmath/BigmathRuntime.java index ba34bd8..5a3bfa1 100644 --- a/src/main/java/com/modularmc/bigmath/BigmathRuntime.java +++ b/src/main/java/com/modularmc/bigmath/BigmathRuntime.java @@ -6,7 +6,10 @@ import java.util.Objects; import java.util.concurrent.CompletableFuture; -/** Process-wide configuration and diagnostics entry point for the Bigmath Native runtime. */ +/** + * Process-wide configuration and diagnostics entry point for the Bigmath Native runtime. + * Runtime options are captured by the first Native-backed API use and cannot be changed afterward. + */ @NullMarked public final class BigmathRuntime { @@ -19,9 +22,9 @@ private BigmathRuntime() { } /** - * Replaces the runtime options used by the first Native initialization. + * Replaces the runtime options used by the first Native-backed API call. * - * @throws IllegalStateException if Native initialization has already started + * @throws IllegalStateException if any Native-backed API has already started initialization */ public static void configure(RuntimeOptions configuredOptions) { Objects.requireNonNull(configuredOptions, "configuredOptions"); @@ -33,7 +36,11 @@ public static void configure(RuntimeOptions configuredOptions) { } } - /** Starts Native initialization on the common asynchronous executor. Calls are idempotent. */ + /** + * Starts Native initialization on the common asynchronous executor. The returned future completes + * after device probing and calibration finish and contains the resulting diagnostics snapshot. + * Repeated calls return the same future. + */ public static CompletableFuture initializeAsync() { synchronized (LOCK) { if (initialization == null) { @@ -47,7 +54,10 @@ public static CompletableFuture initializeAsync() { } } - /** Returns a current read-only snapshot, initializing the Native runtime if necessary. */ + /** + * Returns a current read-only snapshot, initializing the Native runtime and waiting for device + * probing and calibration if necessary. + */ public static RuntimeDiagnostics diagnostics() { return BigmathFFM.getInstance().runtimeDiagnostics(); } diff --git a/src/main/java/com/modularmc/bigmath/FunctionDescriptors.java b/src/main/java/com/modularmc/bigmath/FunctionDescriptors.java index 152c53e..befab47 100644 --- a/src/main/java/com/modularmc/bigmath/FunctionDescriptors.java +++ b/src/main/java/com/modularmc/bigmath/FunctionDescriptors.java @@ -16,7 +16,7 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) final class FunctionDescriptors { - // --- Native ABI v2 --- + // --- Current internal Native ABI --- static final FunctionDescriptor ABI_VERSION = FunctionDescriptor.of(ValueLayout.JAVA_INT); static final FunctionDescriptor ABI_STRING = FunctionDescriptor.of(ValueLayout.ADDRESS); diff --git a/src/main/java/com/modularmc/bigmath/RuntimeOptions.java b/src/main/java/com/modularmc/bigmath/RuntimeOptions.java index dda5238..e3b55a8 100644 --- a/src/main/java/com/modularmc/bigmath/RuntimeOptions.java +++ b/src/main/java/com/modularmc/bigmath/RuntimeOptions.java @@ -5,7 +5,14 @@ import java.time.Duration; import java.util.Objects; -/** Immutable options captured when the Bigmath Native runtime is initialized. */ +/** + * Immutable options captured when the Bigmath Native runtime is initialized. + *

+ * Defaults enable the product cache with a 64 MiB host budget, reserve 25% of + * available device memory up to 512 MiB for CUDA workspaces, allow about ten + * seconds for calibration, and automatically select both the CUDA device and + * backend. + */ @NullMarked public final class RuntimeOptions {