Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/000-bug-report.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/publish-on-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand All @@ -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

Expand Down
83 changes: 65 additions & 18 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
115 changes: 90 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -121,10 +182,10 @@ cmake --preset cuda-windows-msvc-release
cmake --build build/native --target install
```

Set `BIGMATH_CUDA_ARCH` or pass `-PbigmathCudaArch=<arch>` 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=<arch>` 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.
Expand Down Expand Up @@ -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/<classifier>/`
- 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.
13 changes: 13 additions & 0 deletions bigmath-ffm-kt/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading