diff --git a/.github/workflows/native-build.yml b/.github/workflows/native-build.yml index 6e3b546..5686c45 100644 --- a/.github/workflows/native-build.yml +++ b/.github/workflows/native-build.yml @@ -31,3 +31,113 @@ jobs: needs: check if: needs.check.outputs.native == 'true' uses: ./.github/workflows/native-artifacts.yml + + cuda-native: + name: cuda-${{ matrix.classifier }} + needs: check + if: needs.check.outputs.native == 'true' + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + platform: linux + classifier: linux-x86-64 + main_library: libbigmath_ffm.so + - os: windows-2022 + platform: windows + classifier: windows-x86-64 + main_library: bigmath_ffm.dll + vcpkg_triplet: x64-windows + runs-on: ${{ matrix.os }} + env: + VCPKG_BINARY_SOURCES: clear;files,${{ github.workspace }}/.vcpkg-cache,readwrite + steps: + - uses: actions/checkout@v4 + + - name: Configure MSVC + if: matrix.platform == 'windows' + uses: ilammy/msvc-dev-cmd@v1 + with: + arch: x64 + + - name: Configure MSVC compiler environment + if: matrix.platform == 'windows' + shell: pwsh + run: | + $cl = (Get-Command cl.exe -ErrorAction Stop).Source + "CC=$cl" >> $env:GITHUB_ENV + "CXX=$cl" >> $env:GITHUB_ENV + "BIGMATH_WINDOWS_COMPILER=msvc" >> $env:GITHUB_ENV + + - name: Restore vcpkg binary cache + if: matrix.platform == 'windows' + id: vcpkg-cache + uses: actions/cache/restore@v4 + with: + path: .vcpkg-cache + key: cuda-vcpkg-${{ matrix.classifier }}-${{ hashFiles('vcpkg.json') }}-${{ github.run_id }}-${{ github.run_attempt }} + restore-keys: | + cuda-vcpkg-${{ matrix.classifier }}-${{ hashFiles('vcpkg.json') }}- + vcpkg-binary-${{ matrix.classifier }}-${{ hashFiles('vcpkg.json') }}- + + - name: Install Linux dependencies + if: matrix.platform == 'linux' + run: | + sudo apt-get update -o Acquire::Retries=3 + sudo apt-get install -y cmake libgmp-dev libmpfr-dev ninja-build + + - name: Install Windows dependencies + if: matrix.platform == 'windows' + shell: pwsh + run: | + vcpkg install --triplet '${{ matrix.vcpkg_triplet }}' + "CMAKE_PREFIX_PATH=${{ github.workspace }}\vcpkg_installed\${{ matrix.vcpkg_triplet }}" >> $env:GITHUB_ENV + "BIGMATH_VCPKG_TRIPLET=${{ matrix.vcpkg_triplet }}" >> $env:GITHUB_ENV + + - name: Install CUDA toolkit + uses: Jimver/cuda-toolkit@v0.2.35 + with: + cuda: '13.2.0' + + - uses: actions/setup-java@v4 + with: + java-version: '23' + distribution: 'temurin' + + - uses: gradle/actions/setup-gradle@v4 + + - name: Build CUDA Native library + if: matrix.platform == 'linux' + shell: bash + run: | + chmod +x gradlew .github/scripts/stage-native-runtime-unix.sh + ./gradlew buildNative -PbigmathEnableCuda=true '-PbigmathCudaArch=75;80;86;89;90' \ + '-PbigmathBuildId=${{ github.sha }}' + .github/scripts/stage-native-runtime-unix.sh \ + '${{ matrix.platform }}' '${{ matrix.classifier }}' '${{ matrix.main_library }}' + + - name: Build CUDA Native library + if: matrix.platform == 'windows' + shell: pwsh + run: | + .\gradlew.bat buildNative -PbigmathEnableCuda=true '-PbigmathCudaArch=75;80;86;89;90' ` + '-PbigmathBuildId=${{ github.sha }}' + if ($LASTEXITCODE -ne 0) { throw "Gradle buildNative failed with exit code $LASTEXITCODE" } + .github/scripts/stage-native-runtime-windows.ps1 ` + -Label '${{ matrix.classifier }}' -Triplet '${{ matrix.vcpkg_triplet }}' + + - name: Save vcpkg binary cache + if: matrix.platform == 'windows' && !cancelled() + uses: actions/cache/save@v4 + with: + path: .vcpkg-cache + key: ${{ steps.vcpkg-cache.outputs.cache-primary-key }} + + - name: Upload CUDA Native artifact + uses: actions/upload-artifact@v4 + with: + name: cuda-native-${{ matrix.classifier }} + path: native/${{ matrix.classifier }}/ + if-no-files-found: error + retention-days: 7 diff --git a/gradle/scripts/resources.gradle b/gradle/scripts/resources.gradle index f286172..f377f54 100644 --- a/gradle/scripts/resources.gradle +++ b/gradle/scripts/resources.gradle @@ -232,6 +232,7 @@ def cmakeConfigure = tasks.register('cmakeConfigure', Exec) { "-DCMAKE_MAKE_PROGRAM=${ninjaExecutable.absolutePath.replace('\\', '/')}", "-DCMAKE_BUILD_TYPE=${project.findProperty('buildType') ?: 'Release'}", "-DCMAKE_INSTALL_PREFIX=${cmakeBuildDir}", + "-DBIGMATH_BUILD_ID=${project.findProperty('bigmathBuildId') ?: 'development'}", "-DUSE_GMP=ON" ] if (cmakePrefixPath) { diff --git a/scripts/cuda-bench.sh b/scripts/cuda-bench.sh index 5f63248..47d769f 100644 --- a/scripts/cuda-bench.sh +++ b/scripts/cuda-bench.sh @@ -4,15 +4,15 @@ # benchmark the GPU multiply path against GMP on this machine's NVIDIA GPU. # # No local CUDA/MSVC build toolchain is required: the .dll/.so is downloaded -# from the latest successful "Native Build" workflow run (which compiles with -# BIGMATH_ENABLE_CUDA=true). At runtime the library probes the local GPU and -# uses it automatically. +# from the dedicated x86-64 CUDA artifact in the latest successful "Native +# Build" workflow run. Runtime backend selection is configured through the +# Java API. # # Usage: # scripts/cuda-bench.sh # auto: latest run on current branch # scripts/cuda-bench.sh --run # a specific Native Build run # scripts/cuda-bench.sh --sizes 80000 160000 # custom digit sizes for the sweep -# scripts/cuda-bench.sh --skip-download # reuse build/native/lib as-is +# scripts/cuda-bench.sh --skip-download # reuse native// as-is # # Requires: gh (authenticated), a JDK 23+ on PATH, and NVIDIA driver + CUDA # runtime DLLs reachable (e.g. CUDA toolkit bin/x64 on PATH for cudart/cufft). @@ -35,7 +35,7 @@ case "$(uname -s)" in Linux) CLASSIFIER="linux-x86-64"; LIB="libbigmath_ffm.so"; SEP=':';; *) echo "CUDA artifacts are only published for linux-x86-64 / windows-x86-64" >&2; exit 1;; esac -LIBDIR="build/native/lib" +LIBDIR="native/$CLASSIFIER" if [ "$SKIP_DL" = 0 ]; then echo "== Locating latest successful Native Build run" @@ -46,37 +46,32 @@ if [ "$SKIP_DL" = 0 ]; then [ -n "$RUN_ID" ] || RUN_ID="$(gh run list --workflow=native-build.yml --status success \ --limit 1 --json databaseId -q '.[0].databaseId')" fi - echo " run=$RUN_ID artifact=native-libs-$CLASSIFIER" - rm -rf "$LIBDIR"; mkdir -p "$LIBDIR" - gh run download "$RUN_ID" -n "native-libs-$CLASSIFIER" -D "$LIBDIR" + echo " run=$RUN_ID artifact=cuda-native-$CLASSIFIER" + rm -rf "$LIBDIR" + mkdir -p "$LIBDIR" + gh run download "$RUN_ID" -n "cuda-native-$CLASSIFIER" -D "$LIBDIR" fi [ -f "$LIBDIR/$LIB" ] || { echo "native lib missing: $LIBDIR/$LIB" >&2; exit 1; } echo " staged: $LIBDIR/$LIB" -echo "== Compiling main + CUDA harnesses" -./gradlew -q classes -mkdir -p build/cudacheck -javac --release 23 -cp "build/classes/java/main" -d build/cudacheck \ - src/jmh/java/com/modularmc/bigmath/CudaCheck.java \ - src/jmh/java/com/modularmc/bigmath/CudaSweep.java \ - src/jmh/java/com/modularmc/bigmath/CudaVerify.java +echo "== Compiling main + CUDA harnesses with Gradle" +./gradlew -q classes compileJmhJava -CP="build/classes/java/main${SEP}build/cudacheck" +CP="build/classes/java/main${SEP}build/classes/java/jmh" JAVA_OPTS=(--enable-native-access=ALL-UNNAMED -Dbigmath.native.path="$PWD/$LIBDIR/$LIB") -echo "== Verifying GPU execution (CudaCheck)" -java "${JAVA_OPTS[@]}" -cp "$CP" com.modularmc.bigmath.CudaCheck 2>/dev/null | grep -E 'cuda|device|status|multiplyCount|CUDA' +echo "== Runtime diagnostics (AUTO)" +java "${JAVA_OPTS[@]}" -cp "$CP" com.modularmc.bigmath.CudaCheck AUTO \ + | grep -E 'Backend|backend|calibration|device|status|cpuFallbacks' -# Correctness gate: bit-exact vs GMP. set -e aborts the run on any mismatch, so a -# kernel rewrite cannot pass benchmarking while producing wrong products. -echo "== Correctness [cuFFT FP64 path] vs GMP" -java "${JAVA_OPTS[@]}" -cp "$CP" com.modularmc.bigmath.CudaVerify 2>/dev/null -echo "== Correctness [integer-NTT path] vs GMP (BIGMATH_CUDA_NTT=1)" -BIGMATH_CUDA_NTT=1 java "${JAVA_OPTS[@]}" -cp "$CP" com.modularmc.bigmath.CudaVerify 2>/dev/null +# Existing correctness harnesses exercise only public APIs. set -e aborts on a +# mismatch before benchmark rows are produced. +echo "== Correctness [cuFFT FP64 path]" +java "${JAVA_OPTS[@]}" -cp "$CP" com.modularmc.bigmath.CudaVerify CUFFT $SIZES +echo "== Correctness [integer-NTT path]" +java "${JAVA_OPTS[@]}" -cp "$CP" com.modularmc.bigmath.CudaVerify NTT $SIZES -echo "== Sweep [cuFFT FP64 path]" -java "${JAVA_OPTS[@]}" -cp "$CP" com.modularmc.bigmath.CudaSweep $SIZES - -echo "== Sweep [integer-NTT path] (BIGMATH_CUDA_NTT=1)" -echo " (identical to the cuFFT row above if the loaded lib predates the int-NTT kernel)" -BIGMATH_CUDA_NTT=1 java "${JAVA_OPTS[@]}" -cp "$CP" com.modularmc.bigmath.CudaSweep $SIZES +for backend in CPU CUFFT NTT AUTO; do + echo "== Sweep [$backend]" + java "${JAVA_OPTS[@]}" -cp "$CP" com.modularmc.bigmath.CudaSweep "$backend" $SIZES +done diff --git a/src/jmh/java/com/modularmc/bigmath/CudaCheck.java b/src/jmh/java/com/modularmc/bigmath/CudaCheck.java index d8784ab..0d0fa7e 100644 --- a/src/jmh/java/com/modularmc/bigmath/CudaCheck.java +++ b/src/jmh/java/com/modularmc/bigmath/CudaCheck.java @@ -1,13 +1,12 @@ package com.modularmc.bigmath; +import java.util.Locale; + /** - * Diagnostic main that proves whether the loaded native library actually - * executes multiplications on the GPU. + * Diagnostic main for the configured Native multiplication backend. *

- * It prints CUDA availability/device info, then runs a handful of distinct - * large multiplies and reports the delta of the native {@code cudaMultiplyCount} - * counter. A non-zero delta means the GPU convolution path ran; zero means the - * library fell back to CPU/GMP. + * It configures the requested backend through {@link BigmathRuntime}, prints the + * public runtime diagnostics, then runs a handful of distinct large multiplies. *

* Run via {@code scripts/cuda-bench.sh} (which stages a CUDA-enabled native lib), * or manually: @@ -15,37 +14,46 @@ * java --enable-native-access=ALL-UNNAMED \ * -Dbigmath.native.path=build/native/lib/bigmath_ffm.dll \ * -cp build/classes/java/main;build/cudacheck \ - * com.modularmc.bigmath.CudaCheck [digits] + * com.modularmc.bigmath.CudaCheck [AUTO|CPU|CUFFT|NTT] [digits] * */ public final class CudaCheck { public static void main(String[] args) { - System.out.println("cudaAvailable = " + BigmathFFM.cudaAvailable()); - System.out.println("deviceCount = " + BigmathFFM.cudaDeviceCount()); - System.out.println("deviceName = " + BigmathFFM.cudaDeviceName()); - System.out.println("status = " + BigmathFFM.cudaStatusMessage()); + RuntimeOptions.CudaBackend backend = args.length > 0 + ? RuntimeOptions.CudaBackend.valueOf(args[0].toUpperCase(Locale.ROOT)) + : RuntimeOptions.CudaBackend.AUTO; + BigmathRuntime.configure(RuntimeOptions.builder() + .cudaBackend(backend) + .productCacheEnabled(false) + .build()); + RuntimeDiagnostics before = BigmathRuntime.initializeAsync().join(); + System.out.println("requestedBackend = " + backend); + System.out.println("activeBackend = " + before.cuda().activeBackend()); + System.out.println("calibration = " + before.cuda().calibrationStatus()); + System.out.println("deviceCount = " + before.cuda().deviceCount()); + System.out.println("deviceName = " + before.cuda().deviceName()); + System.out.println("status = " + before.cuda().statusMessage()); - int n = args.length > 0 ? Integer.parseInt(args[0]) : 80000; + int n = args.length > 1 ? Integer.parseInt(args[1]) : 80000; StringBuilder sb = new StringBuilder(n); sb.append('9'); for (int i = 1; i < n; i++) sb.append((char) ('0' + (i * 7 + 3) % 10)); String s = sb.toString(); - long before = BigmathFFM.cudaMultiplyCount(); try (BigInt a = BigInt.fromString(s, 10); BigInt b = BigInt.fromString(new StringBuilder(s).reverse().toString(), 10)) { for (int k = 0; k < 5; k++) { try (BigInt shifted = a.shiftLeft(k * 64L); BigInt r = shifted.multiply(b)) { - if (r == null) System.out.println("null result"); + blackhole ^= r.hashCode(); } } } - long after = BigmathFFM.cudaMultiplyCount(); - System.out.println("multiplyCount before=" + before + " after=" + after - + " (delta=" + (after - before) + ")"); - System.out.println(after > before - ? ">>> CUDA path EXECUTED the multiplications" - : ">>> CUDA did NOT run (CPU/GMP fallback)"); + RuntimeDiagnostics after = BigmathRuntime.diagnostics(); + System.out.println("cpuFallbacks before=" + before.cpuFallbackCount() + + " after=" + after.cpuFallbackCount() + + " (delta=" + (after.cpuFallbackCount() - before.cpuFallbackCount()) + ")"); } + + private static long blackhole; } diff --git a/src/jmh/java/com/modularmc/bigmath/CudaSweep.java b/src/jmh/java/com/modularmc/bigmath/CudaSweep.java index 0bdccaa..7d90376 100644 --- a/src/jmh/java/com/modularmc/bigmath/CudaSweep.java +++ b/src/jmh/java/com/modularmc/bigmath/CudaSweep.java @@ -1,84 +1,83 @@ package com.modularmc.bigmath; -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; import java.util.Arrays; +import java.util.Locale; import java.util.SplittableRandom; /** - * Standalone CUDA-vs-GMP multiply sweep across large operand sizes. + * Standalone public-API multiply sweep across large operand sizes. *

- * Uses {@value #PAIRS} distinct operand pairs per size to defeat the native - * 16-way product cache, verifies CUDA actually executed via the native multiply - * counter ({@code cudaOps} column), and reports wall-clock us/op for the GMP - * (CPU) path and the auto-dispatch path (which selects CUDA above its bit - * threshold). The {@code speedup} column is GMP/CUDA — values above 1.0 mean CUDA wins. + * The backend is selected through {@link RuntimeOptions}; the product cache is + * disabled so each row measures multiplication rather than result reuse. Run + * separate CPU, cuFFT, NTT, and AUTO processes to compare the same public API. *

- * Defaults to digit sizes 40k..640k. Pass explicit sizes as args. Intended to be - * launched by {@code scripts/cuda-bench.sh} against a CUDA-enabled native lib. + * Usage: {@code CudaSweep [AUTO|CPU|CUFFT|NTT] [digit sizes...]}. Defaults to + * AUTO and digit sizes 40k..640k. Intended to be launched by + * {@code scripts/cuda-bench.sh} against a CUDA-enabled native library. */ public final class CudaSweep { - static final MethodHandle MUL_GMP = BigmathFFM.getInstance() - .downcall("bigint_mul_gmp", FunctionDescriptors.BIGINT_BINARY); - static final MethodHandle FREE = BigmathFFM.getInstance() - .downcall("bigint_free", FunctionDescriptors.BIGINT_FREE); + static final int PAIRS = 24; + static final int REPS = 40; // measured multiplies per pair - static final int PAIRS = 24; // > 16-way product cache so every multiply is a miss - static final int REPS = 40; // measured multiplies per pair per path - - public static void main(String[] args) throws Throwable { - System.err.println("CUDA: " + BigmathFFM.cudaAvailable() + " / " + BigmathFFM.cudaDeviceName()); - int[] sizes = args.length > 0 - ? Arrays.stream(args).mapToInt(Integer::parseInt).toArray() + public static void main(String[] args) { + RuntimeOptions.CudaBackend backend = args.length > 0 + ? RuntimeOptions.CudaBackend.valueOf(args[0].toUpperCase(Locale.ROOT)) + : RuntimeOptions.CudaBackend.AUTO; + BigmathRuntime.configure(RuntimeOptions.builder() + .cudaBackend(backend) + .productCacheEnabled(false) + .build()); + RuntimeDiagnostics diagnostics = BigmathRuntime.initializeAsync().join(); + if (backend != RuntimeOptions.CudaBackend.CPU && + diagnostics.cuda().calibrationStatus() != RuntimeDiagnostics.CalibrationStatus.READY) { + throw new IllegalStateException(diagnostics.cuda().statusMessage()); + } + System.err.println("Backend: " + backend + " -> " + diagnostics.cuda().activeBackend() + + " / " + diagnostics.cuda().deviceName()); + int[] sizes = args.length > 1 + ? Arrays.stream(args, 1, args.length).mapToInt(Integer::parseInt).toArray() : new int[]{40000, 80000, 160000, 320000, 640000}; - System.out.printf("%-9s %12s %12s %10s %8s%n", - "digits", "GMP us/op", "CUDA us/op", "speedup", "cudaOps"); + System.out.printf("%-9s %-8s %12s %14s%n", + "digits", "backend", "us/op", "cpuFallbacks"); for (int n : sizes) { BigInt[] a = new BigInt[PAIRS], b = new BigInt[PAIRS]; SplittableRandom rnd = new SplittableRandom(0xC0FFEEL ^ n); - for (int i = 0; i < PAIRS; i++) { - a[i] = BigInt.fromString(randDigits(n, rnd), 10); - b[i] = BigInt.fromString(randDigits(n, rnd), 10); - } - - for (int w = 0; w < PAIRS; w++) { // warmup both paths - try (BigInt r = a[w].multiply(b[w])) { sink(r); } - FREE.invokeExact(mulGmp(a[w], b[w])); - } + try { + for (int i = 0; i < PAIRS; i++) { + a[i] = BigInt.fromString(randDigits(n, rnd), 10); + b[i] = BigInt.fromString(randDigits(n, rnd), 10); + } - long cudaBefore = BigmathFFM.cudaMultiplyCount(); - long tC = 0, tG = 0, ops = 0; - for (int r = 0; r < REPS; r++) { for (int i = 0; i < PAIRS; i++) { - long s = System.nanoTime(); - try (BigInt res = a[i].multiply(b[i])) { sink(res); } - tC += System.nanoTime() - s; + try (BigInt result = a[i].multiply(b[i])) { + sink(result); + } + } - s = System.nanoTime(); - MemorySegment g = mulGmp(a[i], b[i]); - tG += System.nanoTime() - s; - FREE.invokeExact(g); - ops++; + long fallbackBefore = BigmathRuntime.diagnostics().cpuFallbackCount(); + long elapsed = 0; + long operations = 0; + for (int repetition = 0; repetition < REPS; repetition++) { + for (int i = 0; i < PAIRS; i++) { + long started = System.nanoTime(); + try (BigInt result = a[i].multiply(b[i])) { + sink(result); + } + elapsed += System.nanoTime() - started; + operations++; + } + } + long fallbacks = BigmathRuntime.diagnostics().cpuFallbackCount() - fallbackBefore; + System.out.printf("%-9d %-8s %12.1f %14d%n", + n, backend, elapsed / 1000.0 / operations, fallbacks); + } finally { + for (int i = 0; i < PAIRS; i++) { + if (a[i] != null) a[i].close(); + if (b[i] != null) b[i].close(); } } - long cudaOps = BigmathFFM.cudaMultiplyCount() - cudaBefore; - double gmpUs = tG / 1000.0 / ops, cudaUs = tC / 1000.0 / ops; - System.out.printf("%-9d %12.1f %12.1f %9.2fx %8d%n", - n, gmpUs, cudaUs, gmpUs / cudaUs, cudaOps); - - for (int i = 0; i < PAIRS; i++) { a[i].close(); b[i].close(); } - } - } - - static MemorySegment mulGmp(BigInt l, BigInt r) throws Throwable { - try (Arena arena = Arena.ofConfined()) { - MemorySegment out = arena.allocate(ValueLayout.ADDRESS); - MUL_GMP.invokeExact(out, l.nativePtr(), r.nativePtr()); - return out.get(ValueLayout.ADDRESS, 0); } } diff --git a/src/jmh/java/com/modularmc/bigmath/CudaVerify.java b/src/jmh/java/com/modularmc/bigmath/CudaVerify.java index 584c6cc..7817cd7 100644 --- a/src/jmh/java/com/modularmc/bigmath/CudaVerify.java +++ b/src/jmh/java/com/modularmc/bigmath/CudaVerify.java @@ -1,201 +1,126 @@ package com.modularmc.bigmath; -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.lang.foreign.ValueLayout; -import java.lang.invoke.MethodHandle; +import java.math.BigInteger; import java.util.Arrays; +import java.util.Locale; import java.util.SplittableRandom; /** - * Correctness gate for the GPU multiply paths. + * Correctness gate for configured multiply, BigDeci multiply, and modular + * exponentiation paths through the public Bigmath API. *

- * The {@link CudaSweep} harness only measures wall-clock time; it never checks - * that the GPU result is correct. A bug in the (hand-written) integer-NTT kernel - * would therefore produce silently-wrong products. This harness multiplies via - * the auto-dispatch path — which routes to the GPU integer-NTT kernel when - * launched with {@code BIGMATH_CUDA_NTT=1} and the operands exceed the CUDA bit - * threshold — and compares the product bit-exactly against the pure-GMP - * reference {@code bigint_mul_gmp}. It covers distinct-operand multiplies and the - * squaring fast path ({@code a*a}), across digit sizes chosen to bracket the NTT - * transform-size (power-of-two) boundaries. - *

- * Exits non-zero on any mismatch so {@code scripts/cuda-bench.sh} / CI can gate - * a kernel rewrite on correctness before trusting its timings. + * Usage: {@code CudaVerify [AUTO|CPU|CUFFT|NTT] [digit sizes...]}. The selected + * backend is configured before Native initialization, and all results are + * compared with public JDK or Bigmath values rather than private Native exports. */ public final class CudaVerify { - static final MethodHandle MUL_GMP = BigmathFFM.getInstance() - .downcall("bigint_mul_gmp", FunctionDescriptors.BIGINT_BINARY); - static final MethodHandle CMP = BigmathFFM.getInstance() - .downcall("bigint_cmp", FunctionDescriptors.BIGINT_CMP); - static final MethodHandle FREE = BigmathFFM.getInstance() - .downcall("bigint_free", FunctionDescriptors.BIGINT_FREE); - // BigDeci reference handles (same FFM layout as the bigint binary/cmp/free). - static final MethodHandle DEC_MUL_MPFR = BigmathFFM.getInstance() - .downcall("bigdecimal_mul_mpfr", FunctionDescriptors.BIGINT_BINARY); - static final MethodHandle DEC_CMP = BigmathFFM.getInstance() - .downcall("bigdecimal_cmp", FunctionDescriptors.BIGINT_CMP); - static final MethodHandle DEC_FREE = BigmathFFM.getInstance() - .downcall("bigdecimal_free", FunctionDescriptors.BIGINT_FREE); - static final MethodHandle POWM_GMP = BigmathFFM.getInstance() - .downcall("bigint_powm_gmp", FunctionDescriptors.BIGINT_TERNARY); - - public static void main(String[] args) throws Throwable { - System.err.println("CUDA: " + BigmathFFM.cudaAvailable() + " / " + BigmathFFM.cudaDeviceName() - + " BIGMATH_CUDA_NTT=" + System.getenv("BIGMATH_CUDA_NTT")); - - // Sizes >= the ~79k-digit CUDA threshold so the GPU path engages, chosen to - // straddle NTT transform-size boundaries: the u16 digit count is ~0.2075x - // the decimal length, so result_size = next_pow2 lands on 2^16..2^19 across - // this range, plus a few just-over/just-under-a-boundary points. - int[] sizes = args.length > 0 - ? Arrays.stream(args).mapToInt(Integer::parseInt).toArray() - : new int[]{90000, 100000, 158000, 162000, 200000, 316000, 320000, 400000, 640000, 800000}; - - SplittableRandom rnd = new SplittableRandom(0x5EEDC0DEL); - System.out.printf("%-9s %-6s %8s %s%n", "digits", "case", "cudaOps", "result"); - int failures = 0; - for (int n : sizes) { - failures += check(n, false, rnd) ? 0 : 1; - failures += check(n, true, rnd) ? 0 : 1; - } - System.out.printf("%nRESULT: %s (%d cases checked)%n", - failures == 0 ? "ALL PASS" : (failures + " FAILED"), sizes.length * 2); - - // BigDeci high-precision multiply: bigdecimal_mul routes the significand - // product through the GPU (gpu_mpfr_mul) above ~262144-bit precision. - // Verify bit-exactly against the pure-MPFR reference bigdecimal_mul_mpfr. - int decFail = 0; - for (int precBits : new int[]{300000, 524288}) { - decFail += checkBigDeci(precBits, rnd) ? 0 : 1; + public static void main(String[] args) { + RuntimeOptions.CudaBackend backend = args.length > 0 + ? RuntimeOptions.CudaBackend.valueOf(args[0].toUpperCase(Locale.ROOT)) + : RuntimeOptions.CudaBackend.AUTO; + BigmathRuntime.configure(RuntimeOptions.builder() + .cudaBackend(backend) + .productCacheEnabled(false) + .build()); + RuntimeDiagnostics diagnostics = BigmathRuntime.initializeAsync().join(); + if (backend != RuntimeOptions.CudaBackend.CPU && + diagnostics.cuda().calibrationStatus() != RuntimeDiagnostics.CalibrationStatus.READY) { + throw new IllegalStateException(diagnostics.cuda().statusMessage()); } - System.out.printf("RESULT(bigdeci): %s%n", - decFail == 0 ? "ALL PASS" : (decFail + " FAILED")); + System.err.println("Backend: " + backend + " -> " + diagnostics.cuda().activeBackend() + + " / " + diagnostics.cuda().deviceName()); - // Modular exponentiation: modPow uses Barrett reduction with GPU multiplies - // above ~262144-bit moduli. Verify bit-exactly vs GMP's mpz_powm. - int powmFail = 0; - for (int modDigits : new int[]{200000, 250000}) { // above the ~158k-digit GPU threshold - powmFail += checkModPow(modDigits, rnd) ? 0 : 1; - } - System.out.printf("RESULT(modpow): %s%n", - powmFail == 0 ? "ALL PASS" : (powmFail + " FAILED")); + int[] sizes = args.length > 1 + ? Arrays.stream(args, 1, args.length).mapToInt(Integer::parseInt).toArray() + : new int[]{90000, 100000, 158000, 162000, 200000, 316000, 320000, 400000, 640000, 800000}; - if (failures + decFail + powmFail != 0) { - System.exit(1); + SplittableRandom random = new SplittableRandom(0x5EEDC0DEL); + System.out.printf("%-9s %-8s %14s %s%n", "size", "case", "cpuFallbacks", "result"); + int failures = 0; + for (int digits : sizes) { + failures += checkMultiply(digits, false, random) ? 0 : 1; + failures += checkMultiply(digits, true, random) ? 0 : 1; } - } - /** GPU Barrett modPow vs GMP mpz_powm reference (large modulus). */ - static boolean checkModPow(int modDigits, SplittableRandom rnd) throws Throwable { - BigInt base = BigInt.fromString(randDigits(modDigits, rnd), 10); - BigInt mod = BigInt.fromString(randDigits(modDigits, rnd), 10); - BigInt exp = BigInt.fromLong(rnd.nextLong(1L << 40, 1L << 46)); - long before = BigmathFFM.cudaMultiplyCount(); - MemorySegment ref = null; - try (BigInt r = base.modPow(exp, mod)) { - long ops = BigmathFFM.cudaMultiplyCount() - before; - ref = powmGmp(base, exp, mod); - boolean ok = (int) CMP.invokeExact(r.nativePtr(), ref) == 0; - System.out.printf("%-9d %-6s %8d %s%n", modDigits, "powm", ops, ok ? "PASS" : "*** MISMATCH ***"); - return ok; - } finally { - if (ref != null) { - FREE.invokeExact(ref); - } - exp.close(); - mod.close(); - base.close(); + for (int precisionBits : new int[]{300000, 524288}) { + failures += checkBigDeci(precisionBits, random) ? 0 : 1; } - } - static MemorySegment powmGmp(BigInt base, BigInt exp, BigInt mod) throws Throwable { - try (Arena arena = Arena.ofConfined()) { - MemorySegment out = arena.allocate(ValueLayout.ADDRESS); - POWM_GMP.invokeExact(out, base.nativePtr(), exp.nativePtr(), mod.nativePtr()); - return out.get(ValueLayout.ADDRESS, 0); + for (int modulusDigits : new int[]{200000, 250000}) { + failures += checkModPow(modulusDigits, random) ? 0 : 1; } - } - /** High-precision BigDeci multiply (GPU significand path) vs pure-MPFR reference. */ - static boolean checkBigDeci(int precBits, SplittableRandom rnd) throws Throwable { - int decDigits = (int) (precBits * 0.3011) + 8; // fill the significand - BigDeci a = BigDeci.fromString(randDecimal(decDigits, rnd), precBits); - BigDeci b = BigDeci.fromString(randDecimal(decDigits, rnd), precBits); - MemorySegment ref = null; - try (BigDeci prod = a.multiply(b)) { - ref = mulMpfr(a, b); - boolean ok = (int) DEC_CMP.invokeExact(prod.nativePtr(), ref) == 0; - System.out.printf("%-9d %-6s %8s %s%n", precBits, "decmul", "-", ok ? "PASS" : "*** MISMATCH ***"); - return ok; - } finally { - if (ref != null) { - DEC_FREE.invokeExact(ref); - } - a.close(); - b.close(); + System.out.printf("%nRESULT: %s%n", failures == 0 ? "ALL PASS" : failures + " FAILED"); + if (failures != 0) { + throw new AssertionError(failures + " public API CUDA verification cases failed"); } } - static MemorySegment mulMpfr(BigDeci l, BigDeci r) throws Throwable { - try (Arena arena = Arena.ofConfined()) { - MemorySegment out = arena.allocate(ValueLayout.ADDRESS); - DEC_MUL_MPFR.invokeExact(out, l.nativePtr(), r.nativePtr()); - return out.get(ValueLayout.ADDRESS, 0); + static boolean checkMultiply(int digits, boolean square, SplittableRandom random) { + BigInteger leftValue = new BigInteger(randDigits(digits, random)); + BigInteger rightValue = square ? leftValue : new BigInteger(randDigits(digits, random)); + BigInteger expected = leftValue.multiply(rightValue); + long fallbackBefore = BigmathRuntime.diagnostics().cpuFallbackCount(); + try (BigInt left = BigInt.fromBigInteger(leftValue); + BigInt right = BigInt.fromBigInteger(rightValue); + BigInt product = left.multiply(square ? left : right)) { + long fallbacks = BigmathRuntime.diagnostics().cpuFallbackCount() - fallbackBefore; + boolean matches = expected.equals(product.toBigInteger()); + System.out.printf("%-9d %-8s %14d %s%n", + digits, square ? "square" : "multiply", fallbacks, matches ? "PASS" : "MISMATCH"); + return matches; } } - static String randDecimal(int digits, SplittableRandom rnd) { - StringBuilder sb = new StringBuilder(digits + 2); - sb.append((char) ('1' + rnd.nextInt(9))).append('.'); - for (int i = 0; i < digits; i++) { - sb.append((char) ('0' + rnd.nextInt(10))); + static boolean checkBigDeci(int precisionBits, SplittableRandom random) { + int decimalDigits = (int) (precisionBits * 0.30103) - 8; + BigInteger leftValue = new BigInteger(randDigits(decimalDigits, random)); + BigInteger rightValue = new BigInteger(randDigits(decimalDigits, random)); + BigInteger expectedValue = leftValue.multiply(rightValue); + long fallbackBefore = BigmathRuntime.diagnostics().cpuFallbackCount(); + try (BigInt leftInteger = BigInt.fromBigInteger(leftValue); + BigInt rightInteger = BigInt.fromBigInteger(rightValue); + BigInt expectedInteger = BigInt.fromBigInteger(expectedValue); + BigDeci left = BigDeci.fromBigInt(leftInteger, precisionBits); + BigDeci right = BigDeci.fromBigInt(rightInteger, precisionBits); + BigDeci expected = BigDeci.fromBigInt(expectedInteger, precisionBits); + BigDeci product = left.multiply(right)) { + long fallbacks = BigmathRuntime.diagnostics().cpuFallbackCount() - fallbackBefore; + boolean matches = product.compareTo(expected) == 0; + System.out.printf("%-9d %-8s %14d %s%n", + precisionBits, "BigDeci", fallbacks, matches ? "PASS" : "MISMATCH"); + return matches; } - return sb.toString(); } - /** Multiply via the auto/GPU path and compare bit-exactly to the GMP reference. */ - static boolean check(int n, boolean square, SplittableRandom rnd) throws Throwable { - BigInt a = BigInt.fromString(randDigits(n, rnd), 10); - BigInt b = square ? a : BigInt.fromString(randDigits(n, rnd), 10); - long before = BigmathFFM.cudaMultiplyCount(); - MemorySegment refPtr = null; - try (BigInt prod = a.multiply(b)) { - long ops = BigmathFFM.cudaMultiplyCount() - before; - refPtr = mulGmp(a, b); - int cmp = (int) CMP.invokeExact(prod.nativePtr(), refPtr); - boolean ok = cmp == 0; - System.out.printf("%-9d %-6s %8d %s%n", - n, square ? "a*a" : "a*b", ops, ok ? "PASS" : "*** MISMATCH ***"); - return ok; - } finally { - if (refPtr != null) { - FREE.invokeExact(refPtr); - } - if (!square) { - b.close(); - } - a.close(); + static boolean checkModPow(int modulusDigits, SplittableRandom random) { + BigInteger baseValue = new BigInteger(randDigits(modulusDigits, random)); + BigInteger modulusValue = new BigInteger(randDigits(modulusDigits, random)); + BigInteger exponentValue = BigInteger.valueOf(random.nextLong(1L << 40, 1L << 46)); + BigInteger expected = baseValue.modPow(exponentValue, modulusValue); + long fallbackBefore = BigmathRuntime.diagnostics().cpuFallbackCount(); + try (BigInt base = BigInt.fromBigInteger(baseValue); + BigInt exponent = BigInt.fromBigInteger(exponentValue); + BigInt modulus = BigInt.fromBigInteger(modulusValue); + BigInt result = base.modPow(exponent, modulus)) { + long fallbacks = BigmathRuntime.diagnostics().cpuFallbackCount() - fallbackBefore; + boolean matches = expected.equals(result.toBigInteger()); + System.out.printf("%-9d %-8s %14d %s%n", + modulusDigits, "modPow", fallbacks, matches ? "PASS" : "MISMATCH"); + return matches; } } - static MemorySegment mulGmp(BigInt l, BigInt r) throws Throwable { - try (Arena arena = Arena.ofConfined()) { - MemorySegment out = arena.allocate(ValueLayout.ADDRESS); - MUL_GMP.invokeExact(out, l.nativePtr(), r.nativePtr()); - return out.get(ValueLayout.ADDRESS, 0); + static String randDigits(int digits, SplittableRandom random) { + StringBuilder result = new StringBuilder(digits); + result.append((char) ('1' + random.nextInt(9))); + for (int index = 1; index < digits; index++) { + result.append((char) ('0' + random.nextInt(10))); } + return result.toString(); } - static String randDigits(int n, SplittableRandom rnd) { - StringBuilder sb = new StringBuilder(n); - sb.append((char) ('1' + rnd.nextInt(9))); - for (int i = 1; i < n; i++) { - sb.append((char) ('0' + rnd.nextInt(10))); - } - return sb.toString(); + private CudaVerify() { } - - private CudaVerify() {} } diff --git a/src/main/cpp/CMakeLists.txt b/src/main/cpp/CMakeLists.txt index 2fc6e69..7eafd47 100644 --- a/src/main/cpp/CMakeLists.txt +++ b/src/main/cpp/CMakeLists.txt @@ -5,7 +5,7 @@ if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) endif() option(USE_GMP "Build with GMP/MPFR native bigint/bigdecimal support" ON) -set(BIGMATH_BUILD_ID "development" CACHE STRING "Native build identifier exposed through ABI v2") +set(BIGMATH_BUILD_ID "development" CACHE STRING "Native build identifier exposed through runtime metadata") set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -186,6 +186,9 @@ add_library(bigmath_ffm SHARED formatting/format_exports.cpp formatting/number_renderer.cpp handles/native_handles.cpp + runtime/cuda_calibration.cpp + runtime/cuda_calibration_cache.cpp + runtime/cuda_workspace_budget.cpp bigint.cpp bigdecimal.cpp int128.cpp diff --git a/src/main/cpp/algos.cpp b/src/main/cpp/algos.cpp index 7d8f16e..0b57f9d 100644 --- a/src/main/cpp/algos.cpp +++ b/src/main/cpp/algos.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -256,7 +257,12 @@ void modpow(mpz_ptr out, mpz_ptr base, mpz_ptr exp, mpz_ptr mod) { // so engage only at >= 2^19 bits ~= 158k decimal digits. static constexpr mp_bitcnt_t MODPOW_BIT_THRESHOLD = 524288; if (mpz_sgn(mod) <= 0 || mpz_sgn(exp) < 0 || mpz_cmp_ui(mod, 1) == 0 || - mpz_sizeinbase(mod, 2) < MODPOW_BIT_THRESHOLD) { + mpz_sizeinbase(mod, 2) < MODPOW_BIT_THRESHOLD || + !cuda_dispatch_favorable( + mpz_sizeinbase(mod, 2), + mpz_sizeinbase(mod, 2), + true + )) { mpz_powm(out, base, exp, mod); return; } @@ -328,6 +334,14 @@ struct CachedCudaU16Digits { std::vector limbs; std::vector digits; + void clear() { + source = nullptr; + limb_count = 0; + bits_per_digit = 0; + limbs.clear(); + digits.clear(); + } + const std::vector &load(mpz_ptr value, mp_bitcnt_t bits, unsigned digit_bits) { #if GMP_NUMB_BITS % 16 == 0 const int signed_limb_count = value->_mp_size; @@ -374,6 +388,13 @@ struct CudaMultiplyHostWorkspace { CachedCudaU16Digits bd; std::vector conv; std::vector packed_limbs; + + void clear() { + ad.clear(); + bd.clear(); + conv.clear(); + packed_limbs.clear(); + } }; static void export_abs_mpz_to_u16_digits(mpz_ptr value, mp_bitcnt_t bits, std::vector &out) { @@ -539,83 +560,76 @@ static void write_u64_limbs_to_mpz(mpz_ptr out, const std::vector &lim #endif } -#ifdef BIGMATH_HAS_CUDA -// Opt-in (BIGMATH_CUDA_NTT=1) switch to the integer-NTT GPU path instead of the -// default cuFFT (FP64) path. The integer path keeps 16-bit digits at every size -// because CRT reconstruction is exact, avoiding the FP64 2^50 coefficient cap -// that forces the cuFFT path onto smaller digits (and more transform points) for -// very large operands. -static bool cuda_ntt_enabled() { - static const int enabled = [] { - const char *value = std::getenv("BIGMATH_CUDA_NTT"); - if (value == nullptr) { - return 0; - } - switch (value[0]) { - case '1': case 't': case 'T': case 'y': case 'Y': case 'o': case 'O': - return 1; - default: - return 0; - } - }(); - return enabled != 0; +static int cuda_transform_size(uint64_t left_bits, uint64_t right_bits) { + const uint64_t digits = (left_bits + 15) / 16 + (right_bits + 15) / 16 - 1; + if (digits > static_cast(std::numeric_limits::max() / 2)) return 0; + int transform = 1; + while (static_cast(transform) < digits) transform <<= 1; + return transform; } -#endif -static constexpr mp_bitcnt_t CUDA_BIT_THRESHOLD = 262144; +static cuda::DispatchDecision cuda_dispatch_decision( + uint64_t left_bits, + uint64_t right_bits, + bool square +) { + return cuda::choose_dispatch({ + left_bits, + right_bits, + cuda_transform_size(left_bits, right_bits), + square, + false + }); +} -static caching::ProductBackend selected_product_backend(mpz_ptr a, mpz_ptr b) { -#ifndef BIGMATH_HAS_CUDA - (void)a; - (void)b; +static caching::ProductBackend product_backend(const cuda::DispatchDecision &decision) { + if (decision.backend == cuda::RuntimeBackend::NTT) return caching::ProductBackend::CUDA_NTT; + if (decision.backend == cuda::RuntimeBackend::CUFFT) return caching::ProductBackend::CUDA_CUFFT; return caching::ProductBackend::CPU_GMP; -#else - if (!cuda::is_available()) return caching::ProductBackend::CPU_GMP; - const mp_bitcnt_t bits_a = mpz_sizeinbase(a, 2); - const mp_bitcnt_t bits_b = mpz_sizeinbase(b, 2); - if (bits_a < CUDA_BIT_THRESHOLD && bits_b < CUDA_BIT_THRESHOLD) { - return caching::ProductBackend::CPU_GMP; - } -#if GMP_NUMB_BITS % 16 == 0 && GMP_NUMB_BITS <= 64 - if (cuda_ntt_enabled()) return caching::ProductBackend::CUDA_NTT; -#endif - return caching::ProductBackend::CUDA_CUFFT; -#endif } -static bool cuda_multiply(mpz_ptr out, mpz_ptr abs_a, mpz_ptr abs_b) { +bool cuda_dispatch_favorable(uint64_t left_bits, uint64_t right_bits, bool square) { + return cuda_dispatch_decision(left_bits, right_bits, square).backend != cuda::RuntimeBackend::CPU; +} + +static bool execute_cuda_multiply( + mpz_ptr out, + mpz_ptr abs_a, + mpz_ptr abs_b, + CudaMultiplyHostWorkspace &workspace, + DirectCudaBackend backend, + uint64_t max_queue_wait_nanos, + bool cache_spectra +) { #ifndef BIGMATH_HAS_CUDA (void)out; (void)abs_a; (void)abs_b; + (void)workspace; + (void)backend; + (void)max_queue_wait_nanos; + (void)cache_spectra; return false; #else static constexpr unsigned CUDA_DIGIT_BITS[] = {16, 12, 8}; - // Only hand off to the GPU once it actually beats CPU GMP. Measured crossover - // on an RTX 3050 (cuFFT path, pinned-D2H build) is ~80k decimal digits - // ~= 2^18 bits; below this the fixed GPU overhead makes mpz_mul faster, so a - // lower threshold (was 131072) regressed ~40-70k-digit multiplies ~2x. - if (!cuda::is_available()) { - return false; - } const mp_bitcnt_t bits_a = mpz_sizeinbase(abs_a, 2); const mp_bitcnt_t bits_b = mpz_sizeinbase(abs_b, 2); - if (bits_a < CUDA_BIT_THRESHOLD && bits_b < CUDA_BIT_THRESHOLD) { - return false; - } - - thread_local CudaMultiplyHostWorkspace workspace; - #if GMP_NUMB_BITS % 16 == 0 && GMP_NUMB_BITS <= 64 - if (cuda_ntt_enabled()) { + if (backend == DirectCudaBackend::NTT) { const std::vector &ad = workspace.ad.load(abs_a, bits_a, 16); const std::vector &bd = abs_a == abs_b ? ad : workspace.bd.load(abs_b, bits_b, 16); - if (cuda::convolve_ntt_u16_to_limbs(ad, bd, workspace.packed_limbs, 16, GMP_NUMB_BITS)) { + if (cuda::convolve_ntt_u16_to_limbs( + ad, + bd, + workspace.packed_limbs, + 16, + GMP_NUMB_BITS, + max_queue_wait_nanos + )) { write_u64_limbs_to_mpz(out, workspace.packed_limbs); - cuda::record_multiply(); return true; } - // Fall through to the cuFFT path on any failure. + return false; } #endif @@ -625,27 +639,98 @@ static bool cuda_multiply(mpz_ptr out, mpz_ptr abs_a, mpz_ptr abs_b) { #if GMP_NUMB_BITS % 16 == 0 && GMP_NUMB_BITS <= 64 if (GMP_NUMB_BITS % bits_per_digit == 0) { if (!cuda::convolve_u16_digits_to_limbs(ad, bd, workspace.packed_limbs, - bits_per_digit, GMP_NUMB_BITS)) { + bits_per_digit, GMP_NUMB_BITS, max_queue_wait_nanos, cache_spectra)) { continue; } write_u64_limbs_to_mpz(out, workspace.packed_limbs); - cuda::record_multiply(); return true; } #else (void)workspace.packed_limbs; #endif - if (!cuda::convolve_u16_digits(ad, bd, workspace.conv, bits_per_digit)) { + if (!cuda::convolve_u16_digits( + ad, + bd, + workspace.conv, + bits_per_digit, + max_queue_wait_nanos, + cache_spectra + )) { continue; } write_u16_digits_to_mpz(out, workspace.conv, bits_per_digit); - cuda::record_multiply(); return true; } return false; #endif } +bool cuda_multiply_direct( + mpz_ptr out, + mpz_ptr a, + mpz_ptr b, + DirectCudaBackend backend, + uint64_t max_queue_wait_nanos, + bool cache_spectra, + bool reset_host_cache +) { + thread_local CudaMultiplyHostWorkspace workspace; + if (reset_host_cache) workspace.clear(); + return execute_cuda_multiply( + out, + a, + b, + workspace, + backend, + max_queue_wait_nanos, + cache_spectra + ); +} + +static bool cuda_multiply( + mpz_ptr out, + mpz_ptr abs_a, + mpz_ptr abs_b, + const cuda::DispatchDecision &decision +) { +#ifndef BIGMATH_HAS_CUDA + (void)out; + (void)abs_a; + (void)abs_b; + (void)decision; + return false; +#else + if (decision.backend == cuda::RuntimeBackend::CPU) return false; + thread_local CudaMultiplyHostWorkspace workspace; + bool completed = false; + if (decision.backend == cuda::RuntimeBackend::NTT) { + completed = execute_cuda_multiply( + out, + abs_a, + abs_b, + workspace, + DirectCudaBackend::NTT, + decision.max_queue_wait_nanos, + false + ); + } + if (!completed) { + completed = execute_cuda_multiply( + out, + abs_a, + abs_b, + workspace, + DirectCudaBackend::CUFFT, + decision.max_queue_wait_nanos, + true + ); + } + if (completed) cuda::record_multiply(); + else cuda::record_cpu_fallback(); + return completed; +#endif +} + static void store_product_result( const caching::ProductCacheKey *cache_key, bool admitted, @@ -684,13 +769,16 @@ static void fft_multiply_impl( bool a_neg = (mpz_sgn(a) < 0); bool b_neg = (mpz_sgn(b) < 0); + const uint64_t bits_a = mpz_sizeinbase(a, 2); + const uint64_t bits_b = mpz_sizeinbase(b, 2); + const cuda::DispatchDecision dispatch = cuda_dispatch_decision(bits_a, bits_b, a == b); caching::ProductCacheKey resolved_cache_key{}; const caching::ProductCacheKey *resolved_cache_key_ptr = nullptr; if (cache_key != nullptr) { resolved_cache_key = *cache_key; resolved_cache_key.config = caching::with_product_backend( cache_key->config, - selected_product_backend(a, b) + product_backend(dispatch) ); resolved_cache_key_ptr = &resolved_cache_key; } @@ -725,7 +813,7 @@ static void fft_multiply_impl( clear_abs_b = true; } - if (cuda_multiply(out, abs_a, abs_b)) { + if (cuda_multiply(out, abs_a, abs_b, dispatch)) { store_product_result(resolved_cache_key_ptr, admit_product, out); if (clear_abs_a) mpz_clear(abs_a_storage); if (clear_abs_b) mpz_clear(abs_b_storage); @@ -788,6 +876,15 @@ 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 *) {} +bool cuda_multiply_direct( + mpz_ptr, + mpz_ptr, + mpz_ptr, + DirectCudaBackend, + uint64_t, + bool, + bool +) { return false; } void modpow(mpz_ptr, mpz_ptr, mpz_ptr, mpz_ptr) {} #endif // BIGMATH_NO_GMP diff --git a/src/main/cpp/algos.h b/src/main/cpp/algos.h index 776c0d7..46573db 100644 --- a/src/main/cpp/algos.h +++ b/src/main/cpp/algos.h @@ -25,6 +25,11 @@ constexpr int NTT_THRESHOLD = 4096; using limb_t = uint64_t; +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); @@ -54,6 +59,18 @@ void accelerated_mul( const caching::ProductCacheKey *cache_key = nullptr ); +bool cuda_multiply_direct( + mpz_ptr out, + mpz_ptr a, + mpz_ptr b, + DirectCudaBackend backend, + uint64_t max_queue_wait_nanos, + bool cache_spectra, + bool reset_host_cache +); + +bool cuda_dispatch_favorable(uint64_t left_bits, uint64_t right_bits, bool square); + void modpow(mpz_ptr out, mpz_ptr base, mpz_ptr exp, mpz_ptr mod); inline limb_t *limb_alloc(int n) { diff --git a/src/main/cpp/bigdecimal.cpp b/src/main/cpp/bigdecimal.cpp index 65be796..d61d577 100644 --- a/src/main/cpp/bigdecimal.cpp +++ b/src/main/cpp/bigdecimal.cpp @@ -33,10 +33,15 @@ static bool gpu_mpfr_mul( return false; #else static constexpr mpfr_prec_t GPU_MUL_PREC_THRESHOLD = 262144; // ~79k decimal digits - if (!bigmath::cuda::is_available() || + if (!bigmath::cuda::is_available() || !bigmath::cuda::calibration_ready() || !mpfr_regular_p(a) || !mpfr_regular_p(b) || mpfr_get_prec(a) < GPU_MUL_PREC_THRESHOLD || - mpfr_get_prec(b) < GPU_MUL_PREC_THRESHOLD) { + mpfr_get_prec(b) < GPU_MUL_PREC_THRESHOLD || + !bigmath::cuda_dispatch_favorable( + static_cast(mpfr_get_prec(a)), + static_cast(mpfr_get_prec(b)), + a == b + )) { return false; } mpz_t za, zb, zp; diff --git a/src/main/cpp/bigmath_ffm.h b/src/main/cpp/bigmath_ffm.h index e1e8985..a0861f4 100644 --- a/src/main/cpp/bigmath_ffm.h +++ b/src/main/cpp/bigmath_ffm.h @@ -25,6 +25,33 @@ struct BigmathFormatResult { uint64_t size; }; +struct BigmathRuntimeSnapshot { + uint64_t threshold_bits[4]; + uint64_t square_threshold_bits; + uint64_t workspace_budget_bytes; + uint64_t workspace_in_use_bytes; + uint64_t cpu_fallback_count; + uint64_t product_cache_hits; + uint64_t product_cache_misses; + uint64_t product_cache_admissions; + uint64_t product_cache_evictions; + uint64_t product_cache_bytes; + uint32_t schema_version; + uint32_t calibration_status; + uint32_t active_backend; + uint32_t configured_backend; + uint32_t cuda_available; + uint32_t device_count; + int32_t selected_device; + uint32_t ntt_enabled; + uint32_t ntt_transform_mask; + uint32_t workspace_capacity; + uint32_t workspace_in_use; + uint32_t probe_count; + char device_name[256]; + char status_message[512]; +}; + extern "C" { BIGMATH_EXPORT uint32_t bigmath_abi_version(); @@ -35,6 +62,17 @@ BIGMATH_EXPORT uint64_t bigmath_product_cache_misses(); BIGMATH_EXPORT uint64_t bigmath_product_cache_admissions(); BIGMATH_EXPORT uint64_t bigmath_product_cache_evictions(); BIGMATH_EXPORT uint64_t bigmath_product_cache_bytes(); +BIGMATH_EXPORT int32_t bigmath_runtime_configure( + int32_t product_cache_enabled, + uint64_t product_cache_bytes, + double gpu_workspace_fraction, + uint64_t gpu_workspace_max_bytes, + uint64_t calibration_millis, + int32_t cuda_device, + int32_t cuda_backend +); +BIGMATH_EXPORT int32_t bigmath_runtime_initialize(); +BIGMATH_EXPORT int32_t bigmath_runtime_snapshot(BigmathRuntimeSnapshot *snapshot); BIGMATH_EXPORT BigIntHandle *bigint_from_long(int64_t val); BIGMATH_EXPORT BigIntHandle *bigint_from_string(const char *str, int radix); diff --git a/src/main/cpp/caching/product_cache.cpp b/src/main/cpp/caching/product_cache.cpp index 571e2b5..18143d0 100644 --- a/src/main/cpp/caching/product_cache.cpp +++ b/src/main/cpp/caching/product_cache.cpp @@ -1,5 +1,6 @@ #include "product_cache.h" +#include #include #include #include @@ -34,6 +35,7 @@ class ProductCache { public: ProductCacheLookup lookup(const ProductCacheKey &key) { std::lock_guard lock(mutex_); + if (!enabled_) return ProductCacheLookup{}; const uint64_t use_tick = next_tick(); for (CachedProduct &entry : results_) { if (entry.ready && entry.key == key) { @@ -66,12 +68,16 @@ class ProductCache { std::vector packed_limbs, bool admitted ) { - if (!admitted || !product_result_fits(packed_limbs.capacity())) { + if (!admitted || !accepts(packed_limbs.capacity())) { return; } const size_t result_bytes = packed_limbs.capacity() * sizeof(uint64_t); auto shared_limbs = std::make_shared>(std::move(packed_limbs)); std::lock_guard lock(mutex_); + if (!enabled_ || max_results_ == 0 || + result_bytes > max_bytes_) { + return; + } const uint64_t use_tick = next_tick(); for (CachedProduct &entry : results_) { if (entry.ready && entry.key == key) { @@ -80,8 +86,7 @@ class ProductCache { } } - while (result_count_ >= MAX_RESULTS || - bytes_ > PRODUCT_CACHE_MAX_RESULT_BYTES - result_bytes) { + while (result_count_ >= max_results_ || bytes_ > max_bytes_ - result_bytes) { if (!evict_lru()) { return; } @@ -108,6 +113,23 @@ class ProductCache { return metrics_; } + bool accepts(size_t limb_count) const { + std::lock_guard lock(mutex_); + return enabled_ && max_results_ != 0 && limb_count <= max_bytes_ / sizeof(uint64_t); + } + + void configure(bool enabled, size_t max_entries, size_t max_bytes) { + std::lock_guard lock(mutex_); + enabled_ = enabled; + max_results_ = std::min(max_entries, MAX_RESULTS); + max_bytes_ = max_bytes; + for (CachedProduct &entry : results_) entry = CachedProduct{}; + for (AdmissionCandidate &candidate : candidates_) candidate = AdmissionCandidate{}; + result_count_ = 0; + bytes_ = 0; + metrics_.bytes = 0; + } + void record_bypass() { std::lock_guard lock(mutex_); metrics_.bypasses++; @@ -152,6 +174,9 @@ class ProductCache { std::array results_{}; std::array candidates_{}; uint64_t tick_ = 0; + bool enabled_ = true; + size_t max_results_ = MAX_RESULTS; + size_t max_bytes_ = PRODUCT_CACHE_MAX_RESULT_BYTES; size_t result_count_ = 0; size_t bytes_ = 0; ProductCacheMetrics metrics_{}; @@ -188,6 +213,14 @@ ProductCacheLookup lookup_product(const ProductCacheKey &key) { } } +bool product_result_fits(size_t limb_count) { + return cache().accepts(limb_count); +} + +void configure_product_cache(bool enabled, size_t max_entries, size_t max_bytes) { + cache().configure(enabled, max_entries, max_bytes); +} + void store_product( const ProductCacheKey &key, std::vector packed_limbs, diff --git a/src/main/cpp/caching/product_cache.h b/src/main/cpp/caching/product_cache.h index 9aabdb6..b721d90 100644 --- a/src/main/cpp/caching/product_cache.h +++ b/src/main/cpp/caching/product_cache.h @@ -23,9 +23,8 @@ constexpr uint64_t with_product_backend(uint64_t config, ProductBackend backend) return (config & ~BACKEND_MASK) | (static_cast(backend) << 8); } -constexpr bool product_result_fits(size_t limb_count) { - return limb_count <= PRODUCT_CACHE_MAX_RESULT_BYTES / sizeof(uint64_t); -} +bool product_result_fits(size_t limb_count); +void configure_product_cache(bool enabled, size_t max_entries, size_t max_bytes); struct ProductOperandKey { uint64_t id; diff --git a/src/main/cpp/cuda_convolution.cu b/src/main/cpp/cuda_convolution.cu index 3080d0f..c700d25 100644 --- a/src/main/cpp/cuda_convolution.cu +++ b/src/main/cpp/cuda_convolution.cu @@ -1,8 +1,16 @@ #include "cuda_convolution.h" +#include "runtime/cuda_workspace_budget.h" +#include +#include +#include +#include #include #include #include +#include +#include +#include #include #include @@ -48,21 +56,6 @@ static bool next_pow2(size_t value, int &out) { return true; } -static bool has_enough_device_memory(size_t element_count, bool cache_spectra) { - size_t free_bytes = 0; - size_t total_bytes = 0; - if (cudaMemGetInfo(&free_bytes, &total_bytes) != cudaSuccess) { - return false; - } - const size_t spectrum_size = element_count / 2 + 1; - const size_t spectrum_buffers = cache_spectra ? 2 + 2 * SPECTRUM_CACHE_WAYS : 2; - const size_t required = sizeof(double) * element_count * 2 + - sizeof(cufftDoubleComplex) * spectrum_size * spectrum_buffers + - sizeof(uint16_t) * element_count * 2; - // cuFFT may reserve temporary workspace in addition to both input arrays. - return required < free_bytes / 2; -} - static bool coefficients_fit_double(size_t result_size, unsigned bits_per_digit) { if (bits_per_digit == 0 || bits_per_digit >= 32) { return false; @@ -73,21 +66,13 @@ static bool coefficients_fit_double(size_t result_size, unsigned bits_per_digit) } static bool round_nonnegative_to_u64(double value, uint64_t &out) { - if (value <= -0.5) { + if (!std::isfinite(value) || value <= -0.5 || value >= std::ldexp(1.0, 64)) { return false; } out = static_cast(value + 0.5); return true; } -static bool clear_device_tail(double *values, size_t used, int n) { - const size_t count = static_cast(n); - if (used >= count) { - return true; - } - return cudaMemset(values + used, 0, sizeof(double) * (count - used)) == cudaSuccess; -} - struct CudaConvolutionWorkspace { struct CachedSpectrum { int n = 0; @@ -132,16 +117,22 @@ struct CudaConvolutionWorkspace { cufftDoubleComplex *fb = nullptr; cufftDoubleComplex *cached_fa[SPECTRUM_CACHE_WAYS] = {}; cufftDoubleComplex *cached_fb[SPECTRUM_CACHE_WAYS] = {}; + cudaStream_t stream = nullptr; cufftHandle forward_plan = 0; cufftHandle inverse_plan = 0; + void *fft_work = nullptr; + size_t fft_work_bytes = 0; int plan_size = 0; int capacity = 0; int spectrum_cache_capacity = 0; uint64_t spectrum_cache_tick = 0; - std::vector host_a; - std::vector host_b; + uint16_t *host_digits_a = nullptr; + uint16_t *host_digits_b = nullptr; + int host_digits_capacity = 0; double *host_result = nullptr; // pinned (page-locked) staging for fast D2H int host_result_capacity = 0; + size_t base_device_bytes = 0; + size_t spectrum_device_bytes = 0; CachedSpectrum cache_a[SPECTRUM_CACHE_WAYS]; CachedSpectrum cache_b[SPECTRUM_CACHE_WAYS]; @@ -158,6 +149,9 @@ struct CudaConvolutionWorkspace { cufftDestroy(inverse_plan); inverse_plan = 0; } + cudaFree(fft_work); + fft_work = nullptr; + fft_work_bytes = 0; plan_size = 0; } @@ -171,6 +165,7 @@ struct CudaConvolutionWorkspace { cache_b[i].clear(); } spectrum_cache_capacity = 0; + spectrum_device_bytes = 0; spectrum_cache_tick = 0; } @@ -190,11 +185,27 @@ struct CudaConvolutionWorkspace { fa = nullptr; fb = nullptr; capacity = 0; + base_device_bytes = 0; + cudaFreeHost(host_digits_a); + cudaFreeHost(host_digits_b); + host_digits_a = nullptr; + host_digits_b = nullptr; + host_digits_capacity = 0; cudaFreeHost(host_result); host_result = nullptr; host_result_capacity = 0; - host_a.clear(); - host_b.clear(); + if (stream != nullptr) { + cudaStreamDestroy(stream); + stream = nullptr; + } + } + + size_t device_bytes() const { + return base_device_bytes + spectrum_device_bytes + fft_work_bytes; + } + + bool ensure_stream() { + return stream != nullptr || cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess; } bool ensure_capacity(int n) { @@ -202,6 +213,7 @@ struct CudaConvolutionWorkspace { return true; } release(); + if (!ensure_stream()) return false; const int spectrum_size = n / 2 + 1; if (cudaMalloc(&da, sizeof(double) * n) != cudaSuccess) { release(); @@ -228,6 +240,9 @@ struct CudaConvolutionWorkspace { return false; } capacity = n; + base_device_bytes = sizeof(double) * static_cast(n) * 2 + + sizeof(uint16_t) * static_cast(n) * 2 + + sizeof(cufftDoubleComplex) * static_cast(spectrum_size) * 2; return true; } @@ -248,6 +263,8 @@ struct CudaConvolutionWorkspace { } } spectrum_cache_capacity = n; + spectrum_device_bytes = sizeof(cufftDoubleComplex) * + static_cast(spectrum_size) * 2 * SPECTRUM_CACHE_WAYS; return true; } @@ -256,14 +273,31 @@ struct CudaConvolutionWorkspace { return true; } release_plan(); - if (cufftPlan1d(&forward_plan, n, CUFFT_D2Z, 1) != CUFFT_SUCCESS) { - forward_plan = 0; - plan_size = 0; + if (!ensure_stream() || + cufftCreate(&forward_plan) != CUFFT_SUCCESS || + cufftCreate(&inverse_plan) != CUFFT_SUCCESS || + cufftSetAutoAllocation(forward_plan, 0) != CUFFT_SUCCESS || + cufftSetAutoAllocation(inverse_plan, 0) != CUFFT_SUCCESS) { + release_plan(); return false; } - if (cufftPlan1d(&inverse_plan, n, CUFFT_Z2D, 1) != CUFFT_SUCCESS) { + size_t forward_work = 0; + size_t inverse_work = 0; + if (cufftMakePlan1d(forward_plan, n, CUFFT_D2Z, 1, &forward_work) != CUFFT_SUCCESS || + cufftMakePlan1d(inverse_plan, n, CUFFT_Z2D, 1, &inverse_work) != CUFFT_SUCCESS) { + release_plan(); + return false; + } + fft_work_bytes = std::max(forward_work, inverse_work); + if (fft_work_bytes != 0 && cudaMalloc(&fft_work, fft_work_bytes) != cudaSuccess) { + release_plan(); + return false; + } + if (cufftSetWorkArea(forward_plan, fft_work) != CUFFT_SUCCESS || + cufftSetWorkArea(inverse_plan, fft_work) != CUFFT_SUCCESS || + cufftSetStream(forward_plan, stream) != CUFFT_SUCCESS || + cufftSetStream(inverse_plan, stream) != CUFFT_SUCCESS) { release_plan(); - plan_size = 0; return false; } plan_size = n; @@ -273,6 +307,32 @@ struct CudaConvolutionWorkspace { // Allocate the D2H result staging buffer in page-locked (pinned) host memory // so the device->host copy runs at full PCIe bandwidth instead of going // through a pageable bounce buffer. + bool ensure_host_digits(int n) { + if (host_digits_capacity >= n) return true; + cudaFreeHost(host_digits_a); + cudaFreeHost(host_digits_b); + host_digits_a = nullptr; + host_digits_b = nullptr; + host_digits_capacity = 0; + if (cudaHostAlloc( + reinterpret_cast(&host_digits_a), + sizeof(uint16_t) * static_cast(n), + cudaHostAllocDefault + ) != cudaSuccess || cudaHostAlloc( + reinterpret_cast(&host_digits_b), + sizeof(uint16_t) * static_cast(n), + cudaHostAllocDefault + ) != cudaSuccess) { + cudaFreeHost(host_digits_a); + cudaFreeHost(host_digits_b); + host_digits_a = nullptr; + host_digits_b = nullptr; + return false; + } + host_digits_capacity = n; + return true; + } + bool ensure_host_result(size_t result_size) { if (host_result_capacity >= static_cast(result_size)) { return true; @@ -289,13 +349,293 @@ struct CudaConvolutionWorkspace { return true; } - void prepare_host_inputs(size_t a_size, size_t b_size) { - host_a.resize(a_size); - host_b.resize(b_size); +}; + +class CudaWorkspacePool { +private: + struct Slot { + std::unique_ptr workspace; + int transform_size = 0; + size_t device_bytes = 0; + bool busy = false; + uint64_t last_used = 0; + std::chrono::steady_clock::time_point acquired_at{}; + }; + +public: + class Lease { + public: + Lease() = default; + Lease(CudaWorkspacePool *pool, Slot *slot) : pool_(pool), slot_(slot) {} + ~Lease() { release(); } + + Lease(const Lease &) = delete; + Lease &operator=(const Lease &) = delete; + + Lease(Lease &&other) noexcept : pool_(other.pool_), slot_(other.slot_) { + other.pool_ = nullptr; + } + + Lease &operator=(Lease &&other) noexcept { + if (this != &other) { + release(); + pool_ = other.pool_; + slot_ = other.slot_; + other.pool_ = nullptr; + } + return *this; + } + + explicit operator bool() const { return pool_ != nullptr; } + + CudaConvolutionWorkspace &workspace() { + return *slot_->workspace; + } + + private: + void release() { + if (pool_ != nullptr) { + pool_->release(slot_); + pool_ = nullptr; + } + } + + CudaWorkspacePool *pool_ = nullptr; + Slot *slot_ = nullptr; + }; + + bool configure(int device, uint64_t budget_bytes) { + std::lock_guard lock(mutex_); + if (reserved_bytes_ != 0) return false; + for (const auto &slot : slots_) { + if (slot->busy) return false; + } + for (const auto &slot : slots_) { + bigmath::runtime::release_cuda_workspace_bytes(device_, slot->device_bytes); + } + slots_.clear(); + allocated_bytes_ = 0; + reserved_bytes_ = 0; + device_ = device; + budget_bytes_ = static_cast(std::min(budget_bytes, SIZE_MAX)); + if (!bigmath::runtime::configure_cuda_workspace_budget(device_, budget_bytes_)) return false; + configured_ = true; + return true; + } + + Lease acquire(int n, bool cache_spectra, uint64_t max_wait_nanos) { + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::nanoseconds(max_wait_nanos); + for (;;) { + std::unique_lock lock(mutex_); + if (!ensure_default_configuration(lock)) return Lease{}; + for (size_t index = 0; index < slots_.size(); index++) { + Slot &slot = *slots_[index]; + if (!slot.busy && slot.transform_size == n && + (!cache_spectra || slot.workspace->spectrum_cache_capacity >= n)) { + slot.busy = true; + slot.acquired_at = std::chrono::steady_clock::now(); + slot.last_used = next_tick(); + if (cudaSetDevice(device_) != cudaSuccess) { + slot.busy = false; + return Lease{}; + } + return Lease(this, &slot); + } + } + + const size_t estimate = estimate_device_bytes(n, cache_spectra); + while (allocated_bytes_ + reserved_bytes_ > budget_bytes_ - std::min(estimate, budget_bytes_)) { + if (!evict_idle_lru()) break; + } + if (estimate <= budget_bytes_ && + allocated_bytes_ + reserved_bytes_ <= budget_bytes_ - estimate) { + if (!bigmath::runtime::reserve_cuda_workspace_bytes(device_, estimate)) { + if (evict_idle_lru()) continue; + } else { + reserved_bytes_ += estimate; + const int device = device_; + lock.unlock(); + auto workspace = std::make_unique(); + const bool initialized = cudaSetDevice(device) == cudaSuccess && + workspace->ensure_capacity(n) && + workspace->ensure_plan(n) && + workspace->ensure_host_digits(n) && + workspace->ensure_host_result(static_cast(n)) && + (!cache_spectra || workspace->ensure_spectrum_cache_capacity(n)); + const size_t actual = initialized ? workspace->device_bytes() : 0; + lock.lock(); + reserved_bytes_ -= estimate; + bool actual_reserved = initialized; + if (initialized && actual < estimate) { + bigmath::runtime::release_cuda_workspace_bytes(device_, estimate - actual); + } else if (initialized && actual > estimate) { + actual_reserved = bigmath::runtime::reserve_cuda_workspace_bytes( + device_, + actual - estimate + ); + } + if (!initialized || !actual_reserved || actual > budget_bytes_ - allocated_bytes_) { + bigmath::runtime::release_cuda_workspace_bytes( + device_, + actual_reserved ? actual : estimate + ); + lock.unlock(); + workspace.reset(); + lock.lock(); + condition_.notify_all(); + return Lease{}; + } + auto slot = std::make_unique(); + slot->workspace = std::move(workspace); + slot->transform_size = n; + slot->device_bytes = actual; + slot->busy = true; + slot->acquired_at = std::chrono::steady_clock::now(); + slot->last_used = next_tick(); + allocated_bytes_ += actual; + Slot *acquired_slot = slot.get(); + slots_.push_back(std::move(slot)); + return Lease(this, acquired_slot); + } + } + + if (max_wait_nanos == 0 || + condition_.wait_until(lock, deadline) == std::cv_status::timeout) { + return Lease{}; + } + } + } + + uint64_t budget_bytes() const { + std::lock_guard lock(mutex_); + return budget_bytes_; + } + + uint64_t in_use_bytes() const { + std::lock_guard lock(mutex_); + uint64_t bytes = 0; + for (const auto &slot : slots_) { + if (slot->busy) bytes += slot->device_bytes; + } + return bytes; + } + + int capacity() const { + std::lock_guard lock(mutex_); + return static_cast(slots_.size()); + } + + int in_use() const { + std::lock_guard lock(mutex_); + return static_cast(std::count_if(slots_.begin(), slots_.end(), [](const auto &slot) { + return slot->busy; + })); + } + + bool available(int n) const { + std::lock_guard lock(mutex_); + for (const auto &slot : slots_) { + if (!slot->busy && slot->transform_size == n) return true; + } + const size_t estimate = estimate_device_bytes(n, true); + const uint64_t shared_allocated = + bigmath::runtime::cuda_workspace_allocated_bytes(device_); + return configured_ && estimate <= budget_bytes_ && + allocated_bytes_ + reserved_bytes_ <= budget_bytes_ - estimate && + shared_allocated <= budget_bytes_ - estimate; + } + +private: + bool ensure_default_configuration(std::unique_lock &) { + if (configured_) return true; + int device = 0; + size_t free_bytes = 0; + size_t total_bytes = 0; + if (cudaGetDevice(&device) != cudaSuccess || + cudaMemGetInfo(&free_bytes, &total_bytes) != cudaSuccess) { + return false; + } + device_ = device; + budget_bytes_ = std::min(free_bytes / 4, 512 * 1024 * 1024); + if (!bigmath::runtime::configure_cuda_workspace_budget(device_, budget_bytes_)) return false; + configured_ = true; + return true; } + + static size_t estimate_device_bytes(int n, bool cache_spectra) { + const size_t count = static_cast(n); + const size_t spectrum = count / 2 + 1; + const size_t base = sizeof(double) * count * 2 + + sizeof(uint16_t) * count * 2 + + sizeof(cufftDoubleComplex) * spectrum * 2; + const size_t cached = cache_spectra + ? sizeof(cufftDoubleComplex) * spectrum * 2 * SPECTRUM_CACHE_WAYS + : 0; + const size_t conservative_fft_work = sizeof(cufftDoubleComplex) * count * 8; + return base + cached + conservative_fft_work; + } + + uint64_t next_tick() { + if (++tick_ == 0) tick_ = 1; + return tick_; + } + + bool evict_idle_lru() { + size_t target = slots_.size(); + for (size_t index = 0; index < slots_.size(); index++) { + if (slots_[index]->busy) continue; + if (target == slots_.size() || slots_[index]->last_used < slots_[target]->last_used) { + target = index; + } + } + if (target == slots_.size()) return false; + allocated_bytes_ -= slots_[target]->device_bytes; + bigmath::runtime::release_cuda_workspace_bytes(device_, slots_[target]->device_bytes); + slots_.erase(slots_.begin() + static_cast(target)); + return true; + } + + void release(Slot *slot) { + cudaError_t synchronized = cudaErrorInvalidResourceHandle; + if (slot != nullptr && cudaSetDevice(device_) == cudaSuccess) { + synchronized = cudaStreamSynchronize(slot->workspace->stream); + } + std::lock_guard lock(mutex_); + if (slot != nullptr && synchronized == cudaSuccess) { + slot->busy = false; + slot->last_used = next_tick(); + } else if (slot != nullptr) { + for (auto iterator = slots_.begin(); iterator != slots_.end(); ++iterator) { + if (iterator->get() == slot) { + allocated_bytes_ -= slot->device_bytes; + bigmath::runtime::release_cuda_workspace_bytes(device_, slot->device_bytes); + slots_.erase(iterator); + break; + } + } + } + condition_.notify_one(); + } + + mutable std::mutex mutex_; + std::condition_variable condition_; + std::vector> slots_; + bool configured_ = false; + int device_ = 0; + size_t budget_bytes_ = 0; + size_t allocated_bytes_ = 0; + size_t reserved_bytes_ = 0; + uint64_t tick_ = 0; }; +CudaWorkspacePool &workspace_pool() { + static CudaWorkspacePool pool; + return pool; +} + static bool prepare_u16_spectrum(const std::vector &digits, + uint16_t *host_digits, uint16_t *device_digits, double *device_values, cufftDoubleComplex *spectrum, @@ -303,6 +643,7 @@ static bool prepare_u16_spectrum(const std::vector &digits, CudaConvolutionWorkspace::CachedSpectrum *caches, uint64_t &cache_tick, cufftHandle forward_plan, + cudaStream_t stream, int n, unsigned bits_per_digit, int block_size) { @@ -318,15 +659,33 @@ static bool prepare_u16_spectrum(const std::vector &digits, for (int i = 0; i < SPECTRUM_CACHE_WAYS; i++) { if (cached_spectra[i] != nullptr && caches[i].matches(digits, n, bits_per_digit)) { caches[i].last_used = use_tick; - return cudaMemcpy(spectrum, cached_spectra[i], spectrum_bytes, cudaMemcpyDeviceToDevice) == cudaSuccess; + return cudaMemcpyAsync( + spectrum, + cached_spectra[i], + spectrum_bytes, + cudaMemcpyDeviceToDevice, + stream + ) == cudaSuccess; } } } - if (cudaMemcpy(device_digits, digits.data(), sizeof(uint16_t) * digits.size(), cudaMemcpyHostToDevice) != cudaSuccess) { + std::memcpy(host_digits, digits.data(), sizeof(uint16_t) * digits.size()); + if (cudaMemcpyAsync( + device_digits, + host_digits, + sizeof(uint16_t) * digits.size(), + cudaMemcpyHostToDevice, + stream + ) != cudaSuccess) { return false; } const int grid_size = (n + block_size - 1) / block_size; - load_u16_digits<<>>(device_digits, static_cast(digits.size()), device_values, n); + load_u16_digits<<>>( + device_digits, + static_cast(digits.size()), + device_values, + n + ); if (cudaGetLastError() != cudaSuccess) { return false; } @@ -346,7 +705,13 @@ static bool prepare_u16_spectrum(const std::vector &digits, target = i; } } - if (cudaMemcpy(cached_spectra[target], spectrum, spectrum_bytes, cudaMemcpyDeviceToDevice) != cudaSuccess) { + if (cudaMemcpyAsync( + cached_spectra[target], + spectrum, + spectrum_bytes, + cudaMemcpyDeviceToDevice, + stream + ) != cudaSuccess) { return false; } caches[target].store(digits, n, bits_per_digit, use_tick); @@ -438,7 +803,9 @@ static bool convolve_u16_digits_impl(const std::vector &a, std::vector *digit_out, std::vector *limb_out, unsigned bits_per_digit, - unsigned limb_bits) { + unsigned limb_bits, + uint64_t max_queue_wait_nanos, + bool cache_spectra) { if (a.empty() || b.empty()) { if (digit_out != nullptr) { digit_out->clear(); @@ -456,43 +823,50 @@ static bool convolve_u16_digits_impl(const std::vector &a, return false; } static constexpr int SPECTRUM_CACHE_MIN_SIZE = 32768; - const bool use_spectrum_cache = n >= SPECTRUM_CACHE_MIN_SIZE; - thread_local CudaConvolutionWorkspace workspace; - if (workspace.capacity < n && !has_enough_device_memory(static_cast(n), use_spectrum_cache)) { - return false; - } - if (!workspace.ensure_capacity(n) || !workspace.ensure_plan(n)) { - return false; - } - if (use_spectrum_cache && !workspace.ensure_spectrum_cache_capacity(n)) { - return false; - } + const bool use_spectrum_cache = cache_spectra && n >= SPECTRUM_CACHE_MIN_SIZE; + CudaWorkspacePool::Lease lease = workspace_pool().acquire( + n, + use_spectrum_cache, + max_queue_wait_nanos + ); + if (!lease) return false; + CudaConvolutionWorkspace &workspace = lease.workspace(); const int block_size = 256; - if (!prepare_u16_spectrum(a, workspace.digits_a, workspace.da, workspace.fa, + if (!prepare_u16_spectrum(a, workspace.host_digits_a, workspace.digits_a, workspace.da, workspace.fa, use_spectrum_cache ? workspace.cached_fa : nullptr, use_spectrum_cache ? workspace.cache_a : nullptr, workspace.spectrum_cache_tick, - workspace.forward_plan, n, bits_per_digit, block_size)) { + workspace.forward_plan, workspace.stream, n, bits_per_digit, block_size)) { return false; } const int spectrum_size = n / 2 + 1; const size_t spectrum_bytes = sizeof(cufftDoubleComplex) * static_cast(spectrum_size); if (&a == &b) { - if (cudaMemcpy(workspace.fb, workspace.fa, spectrum_bytes, cudaMemcpyDeviceToDevice) != cudaSuccess) { + if (cudaMemcpyAsync( + workspace.fb, + workspace.fa, + spectrum_bytes, + cudaMemcpyDeviceToDevice, + workspace.stream + ) != cudaSuccess) { return false; } - } else if (!prepare_u16_spectrum(b, workspace.digits_b, workspace.db, workspace.fb, + } else if (!prepare_u16_spectrum(b, workspace.host_digits_b, workspace.digits_b, workspace.db, workspace.fb, use_spectrum_cache ? workspace.cached_fb : nullptr, use_spectrum_cache ? workspace.cache_b : nullptr, workspace.spectrum_cache_tick, - workspace.forward_plan, n, bits_per_digit, block_size)) { + workspace.forward_plan, workspace.stream, n, bits_per_digit, block_size)) { return false; } const int grid_size = (spectrum_size + block_size - 1) / block_size; - pointwise_multiply<<>>(workspace.fa, workspace.fb, spectrum_size); + pointwise_multiply<<>>( + workspace.fa, + workspace.fb, + spectrum_size + ); if (cudaGetLastError() != cudaSuccess) { return false; } @@ -502,7 +876,13 @@ static bool convolve_u16_digits_impl(const std::vector &a, if (!workspace.ensure_host_result(result_size)) { return false; } - if (cudaMemcpy(workspace.host_result, workspace.da, sizeof(double) * result_size, cudaMemcpyDeviceToHost) != cudaSuccess) { + if (cudaMemcpyAsync( + workspace.host_result, + workspace.da, + sizeof(double) * result_size, + cudaMemcpyDeviceToHost, + workspace.stream + ) != cudaSuccess || cudaStreamSynchronize(workspace.stream) != cudaSuccess) { return false; } @@ -517,87 +897,63 @@ static bool convolve_u16_digits_impl(const std::vector &a, bool convolve_u16_digits(const std::vector &a, const std::vector &b, std::vector &out, - unsigned bits_per_digit) { - return convolve_u16_digits_impl(a, b, &out, nullptr, bits_per_digit, 0); + unsigned bits_per_digit, + uint64_t max_queue_wait_nanos, + bool cache_spectra) { + return convolve_u16_digits_impl( + a, + b, + &out, + nullptr, + bits_per_digit, + 0, + max_queue_wait_nanos, + cache_spectra + ); } bool convolve_u16_digits_to_limbs(const std::vector &a, const std::vector &b, std::vector &out, unsigned bits_per_digit, - unsigned limb_bits) { - return convolve_u16_digits_impl(a, b, nullptr, &out, bits_per_digit, limb_bits); + unsigned limb_bits, + uint64_t max_queue_wait_nanos, + bool cache_spectra) { + return convolve_u16_digits_impl( + a, + b, + nullptr, + &out, + bits_per_digit, + limb_bits, + max_queue_wait_nanos, + cache_spectra + ); } -bool convolve_digits(const std::vector &a, - const std::vector &b, - std::vector &out, - unsigned bits_per_digit) { - if (a.empty() || b.empty()) { - out.clear(); - return true; - } +bool configure_convolution_workspace_pool(int device, uint64_t budget_bytes) { + if (device < 0 || cudaSetDevice(device) != cudaSuccess) return false; + return workspace_pool().configure(device, budget_bytes); +} - const size_t result_size = a.size() + b.size() - 1; - int n = 0; - if (!coefficients_fit_double(result_size, bits_per_digit) || - !next_pow2(result_size, n)) { - return false; - } - thread_local CudaConvolutionWorkspace workspace; - if (workspace.capacity < n && !has_enough_device_memory(static_cast(n), false)) { - return false; - } - if (!workspace.ensure_capacity(n) || !workspace.ensure_plan(n)) { - return false; - } +uint64_t convolution_workspace_budget_bytes() { + return workspace_pool().budget_bytes(); +} - workspace.prepare_host_inputs(a.size(), b.size()); - for (size_t i = 0; i < a.size(); i++) { - workspace.host_a[i] = static_cast(a[i]); - } - for (size_t i = 0; i < b.size(); i++) { - workspace.host_b[i] = static_cast(b[i]); - } +uint64_t convolution_workspace_in_use_bytes() { + return workspace_pool().in_use_bytes(); +} - if (cudaMemcpy(workspace.da, workspace.host_a.data(), sizeof(double) * a.size(), cudaMemcpyHostToDevice) != cudaSuccess || - cudaMemcpy(workspace.db, workspace.host_b.data(), sizeof(double) * b.size(), cudaMemcpyHostToDevice) != cudaSuccess || - !clear_device_tail(workspace.da, a.size(), n) || - !clear_device_tail(workspace.db, b.size(), n)) { - return false; - } - if (cufftExecD2Z(workspace.forward_plan, workspace.da, workspace.fa) != CUFFT_SUCCESS || - cufftExecD2Z(workspace.forward_plan, workspace.db, workspace.fb) != CUFFT_SUCCESS) { - return false; - } +int convolution_workspace_capacity() { + return workspace_pool().capacity(); +} - const int block_size = 256; - const int spectrum_size = n / 2 + 1; - const int grid_size = (spectrum_size + block_size - 1) / block_size; - pointwise_multiply<<>>(workspace.fa, workspace.fb, spectrum_size); - if (cudaGetLastError() != cudaSuccess) { - return false; - } - if (cufftExecZ2D(workspace.inverse_plan, workspace.fa, workspace.da) != CUFFT_SUCCESS) { - return false; - } - if (!workspace.ensure_host_result(result_size)) { - return false; - } - if (cudaMemcpy(workspace.host_result, workspace.da, sizeof(double) * result_size, cudaMemcpyDeviceToHost) != cudaSuccess) { - return false; - } +int convolution_workspace_in_use() { + return workspace_pool().in_use(); +} - out.resize(result_size); - const double scale = 1.0 / static_cast(n); - for (size_t i = 0; i < result_size; i++) { - uint64_t rounded = 0; - if (!round_nonnegative_to_u64(workspace.host_result[i] * scale, rounded)) { - return false; - } - out[i] = rounded; - } - return true; +bool convolution_workspace_available(int transform_size) { + return workspace_pool().available(transform_size); } } diff --git a/src/main/cpp/cuda_convolution.h b/src/main/cpp/cuda_convolution.h index bf192d7..68463d3 100644 --- a/src/main/cpp/cuda_convolution.h +++ b/src/main/cpp/cuda_convolution.h @@ -9,18 +9,24 @@ namespace bigmath::cuda { bool convolve_u16_digits(const std::vector &a, const std::vector &b, std::vector &out, - unsigned bits_per_digit); + unsigned bits_per_digit, + uint64_t max_queue_wait_nanos = 0, + bool cache_spectra = true); bool convolve_u16_digits_to_limbs(const std::vector &a, const std::vector &b, std::vector &out, unsigned bits_per_digit, - unsigned limb_bits); + unsigned limb_bits, + uint64_t max_queue_wait_nanos = 0, + bool cache_spectra = true); -bool convolve_digits(const std::vector &a, - const std::vector &b, - std::vector &out, - unsigned bits_per_digit); +bool configure_convolution_workspace_pool(int device, uint64_t budget_bytes); +uint64_t convolution_workspace_budget_bytes(); +uint64_t convolution_workspace_in_use_bytes(); +int convolution_workspace_capacity(); +int convolution_workspace_in_use(); +bool convolution_workspace_available(int transform_size); } diff --git a/src/main/cpp/cuda_ntt.cu b/src/main/cpp/cuda_ntt.cu index 1888b8a..b0420d7 100644 --- a/src/main/cpp/cuda_ntt.cu +++ b/src/main/cpp/cuda_ntt.cu @@ -1,7 +1,14 @@ #include "cuda_ntt.h" +#include "runtime/cuda_workspace_budget.h" +#include +#include +#include #include #include +#include +#include +#include #include #include @@ -150,6 +157,7 @@ __global__ void k_crt(const u64 *c1, const u64 *c3, u64 *out, int count, u64 mu3 struct NttWorkspace { int capacity = 0; // allocated element count (n) + cudaStream_t stream = nullptr; u64 *fa = nullptr; // working buffer A u64 *fb = nullptr; // working buffer B u64 *c1 = nullptr; // residues from the first prime @@ -160,9 +168,14 @@ struct NttWorkspace { u64 *wf3 = nullptr; // MOD3 forward twiddles u64 *wi3 = nullptr; // MOD3 inverse twiddles int twiddle_n = 0; // transform size the cached twiddles are valid for - std::vector host_w; // staging for twiddle upload - std::vector host_in; // staging for digit upload (zero-padded) - std::vector host_out; // download buffer + u64 *host_w = nullptr; // pinned staging for twiddle upload + u64 *host_a = nullptr; // pinned H2D staging for left digits + u64 *host_b = nullptr; // pinned H2D staging for right digits + u64 *host_out = nullptr; // pinned D2H result staging + int host_w_capacity = 0; + int host_input_capacity = 0; + int host_out_capacity = 0; + size_t device_bytes = 0; ~NttWorkspace() { release(); } @@ -170,13 +183,27 @@ struct NttWorkspace { cudaFree(fa); cudaFree(fb); cudaFree(c1); cudaFree(out); cudaFree(wf1); cudaFree(wi1); cudaFree(wf3); cudaFree(wi3); fa = fb = c1 = out = wf1 = wi1 = wf3 = wi3 = nullptr; + cudaFreeHost(host_w); + cudaFreeHost(host_a); + cudaFreeHost(host_b); + cudaFreeHost(host_out); + host_w = host_a = host_b = host_out = nullptr; + host_w_capacity = 0; + host_input_capacity = 0; + host_out_capacity = 0; + if (stream != nullptr) { + cudaStreamDestroy(stream); + stream = nullptr; + } capacity = 0; twiddle_n = 0; + device_bytes = 0; } bool ensure(int n) { if (capacity >= n) return true; release(); + if (cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) != cudaSuccess) return false; const size_t full = sizeof(u64) * static_cast(n); const size_t half = sizeof(u64) * static_cast(n / 2); if (cudaMalloc(&fa, full) != cudaSuccess || @@ -191,14 +218,277 @@ struct NttWorkspace { return false; } capacity = n; + device_bytes = full * 4 + half * 4; + return true; + } + + bool ensure_host_buffers(int n) { + const int half = n / 2; + if (host_w_capacity < half) { + cudaFreeHost(host_w); + host_w = nullptr; + host_w_capacity = 0; + if (cudaHostAlloc( + reinterpret_cast(&host_w), + sizeof(u64) * static_cast(half), + cudaHostAllocDefault + ) != cudaSuccess) return false; + host_w_capacity = half; + } + if (host_input_capacity < n) { + cudaFreeHost(host_a); + cudaFreeHost(host_b); + host_a = nullptr; + host_b = nullptr; + host_input_capacity = 0; + if (cudaHostAlloc( + reinterpret_cast(&host_a), + sizeof(u64) * static_cast(n), + cudaHostAllocDefault + ) != cudaSuccess || cudaHostAlloc( + reinterpret_cast(&host_b), + sizeof(u64) * static_cast(n), + cudaHostAllocDefault + ) != cudaSuccess) { + cudaFreeHost(host_a); + cudaFreeHost(host_b); + host_a = nullptr; + host_b = nullptr; + return false; + } + host_input_capacity = n; + } + if (host_out_capacity < n) { + cudaFreeHost(host_out); + host_out = nullptr; + host_out_capacity = 0; + if (cudaHostAlloc( + reinterpret_cast(&host_out), + sizeof(u64) * static_cast(n), + cudaHostAllocDefault + ) != cudaSuccess) return false; + host_out_capacity = n; + } return true; } }; +bool ensure_twiddles(NttWorkspace &workspace, int n); + +class NttWorkspacePool { +private: + struct Slot { + std::unique_ptr workspace; + int transform_size = 0; + uint64_t device_bytes = 0; + bool busy = false; + uint64_t last_used = 0; + }; + +public: + class Lease { + public: + Lease() = default; + Lease(NttWorkspacePool *pool, Slot *slot) : pool_(pool), slot_(slot) {} + ~Lease() { release(); } + + Lease(const Lease &) = delete; + Lease &operator=(const Lease &) = delete; + Lease(Lease &&other) noexcept : pool_(other.pool_), slot_(other.slot_) { + other.pool_ = nullptr; + } + Lease &operator=(Lease &&other) noexcept { + if (this != &other) { + release(); + pool_ = other.pool_; + slot_ = other.slot_; + other.pool_ = nullptr; + } + return *this; + } + + explicit operator bool() const { return pool_ != nullptr; } + NttWorkspace &workspace() { return *slot_->workspace; } + + private: + void release() { + if (pool_ != nullptr) { + pool_->release(slot_); + pool_ = nullptr; + } + } + + NttWorkspacePool *pool_ = nullptr; + Slot *slot_ = nullptr; + }; + + bool configure(int device) { + std::lock_guard lock(mutex_); + if (reserved_bytes_ != 0) return false; + for (const auto &slot : slots_) { + if (slot->busy) return false; + } + for (const auto &slot : slots_) { + bigmath::runtime::release_cuda_workspace_bytes(device_, slot->device_bytes); + } + slots_.clear(); + allocated_bytes_ = 0; + device_ = device; + configured_ = true; + return true; + } + + Lease acquire(int n, uint64_t max_wait_nanos) { + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::nanoseconds(max_wait_nanos); + const uint64_t required = static_cast(sizeof(u64)) * + static_cast(n) * 6; + for (;;) { + std::unique_lock lock(mutex_); + if (!configured_) return Lease{}; + for (const auto &slot : slots_) { + if (!slot->busy && slot->transform_size == n) { + slot->busy = true; + slot->last_used = next_tick(); + if (cudaSetDevice(device_) != cudaSuccess) { + slot->busy = false; + return Lease{}; + } + return Lease(this, slot.get()); + } + } + + if (bigmath::runtime::reserve_cuda_workspace_bytes(device_, required)) { + reserved_bytes_ += required; + const int device = device_; + lock.unlock(); + auto workspace = std::make_unique(); + const bool initialized = cudaSetDevice(device) == cudaSuccess && + workspace->ensure(n) && workspace->ensure_host_buffers(n) && + ensure_twiddles(*workspace, n); + lock.lock(); + reserved_bytes_ -= required; + if (!initialized) { + bigmath::runtime::release_cuda_workspace_bytes(device_, required); + lock.unlock(); + workspace.reset(); + lock.lock(); + condition_.notify_all(); + return Lease{}; + } + auto slot = std::make_unique(); + slot->device_bytes = workspace->device_bytes; + slot->transform_size = n; + slot->workspace = std::move(workspace); + slot->busy = true; + slot->last_used = next_tick(); + allocated_bytes_ += required; + Slot *acquired = slot.get(); + slots_.push_back(std::move(slot)); + return Lease(this, acquired); + } + + if (evict_idle_lru()) continue; + if (max_wait_nanos == 0 || + condition_.wait_until(lock, deadline) == std::cv_status::timeout) { + return Lease{}; + } + } + } + + uint64_t in_use_bytes() const { + std::lock_guard lock(mutex_); + uint64_t bytes = 0; + for (const auto &slot : slots_) if (slot->busy) bytes += slot->device_bytes; + return bytes; + } + + int capacity() const { + std::lock_guard lock(mutex_); + return static_cast(slots_.size()); + } + + int in_use() const { + std::lock_guard lock(mutex_); + return static_cast(std::count_if(slots_.begin(), slots_.end(), [](const auto &slot) { + return slot->busy; + })); + } + + bool available(int transform_size) const { + std::lock_guard lock(mutex_); + for (const auto &slot : slots_) { + if (!slot->busy && slot->transform_size == transform_size) return true; + } + const uint64_t required = static_cast(sizeof(u64)) * + static_cast(transform_size) * 6; + const uint64_t budget = bigmath::runtime::cuda_workspace_budget_bytes(device_); + const uint64_t allocated = bigmath::runtime::cuda_workspace_allocated_bytes(device_); + return configured_ && required <= budget && allocated <= budget - required; + } + +private: + uint64_t next_tick() { + if (++tick_ == 0) tick_ = 1; + return tick_; + } + + bool evict_idle_lru() { + size_t target = slots_.size(); + for (size_t index = 0; index < slots_.size(); index++) { + if (slots_[index]->busy) continue; + if (target == slots_.size() || slots_[index]->last_used < slots_[target]->last_used) { + target = index; + } + } + if (target == slots_.size()) return false; + allocated_bytes_ -= slots_[target]->device_bytes; + bigmath::runtime::release_cuda_workspace_bytes(device_, slots_[target]->device_bytes); + slots_.erase(slots_.begin() + static_cast(target)); + return true; + } + + void release(Slot *slot) { + cudaError_t synchronized = cudaErrorInvalidResourceHandle; + if (slot != nullptr && cudaSetDevice(device_) == cudaSuccess) { + synchronized = cudaStreamSynchronize(slot->workspace->stream); + } + std::lock_guard lock(mutex_); + if (slot != nullptr && synchronized == cudaSuccess) { + slot->busy = false; + slot->last_used = next_tick(); + } else if (slot != nullptr) { + for (auto iterator = slots_.begin(); iterator != slots_.end(); ++iterator) { + if (iterator->get() == slot) { + allocated_bytes_ -= slot->device_bytes; + bigmath::runtime::release_cuda_workspace_bytes(device_, slot->device_bytes); + slots_.erase(iterator); + break; + } + } + } + condition_.notify_one(); + } + + mutable std::mutex mutex_; + std::condition_variable condition_; + std::vector> slots_; + bool configured_ = false; + int device_ = 0; + uint64_t allocated_bytes_ = 0; + uint64_t reserved_bytes_ = 0; + uint64_t tick_ = 0; +}; + +NttWorkspacePool &ntt_workspace_pool() { + static NttWorkspacePool pool; + return pool; +} + bool next_pow2(size_t value, int &out_n, int &out_logn) { + if (value > static_cast(NTT_MAX_TRANSFORM_SIZE)) return false; int p = 1, logn = 0; while (static_cast(p) < value) { - if (p > (1 << 27)) return false; // keep within configured root order p <<= 1; logn++; } @@ -213,13 +503,18 @@ bool upload_twiddles(NttWorkspace &ws, u64 *dst, int n, u64 p, bool inverse) { const u64 root = host_powmod(PRIMITIVE_ROOT, (p - 1) / static_cast(n), p); const u64 g = inverse ? host_powmod(root, p - 2, p) : root; const int half = n / 2; - ws.host_w.resize(half); u64 cur = 1; for (int i = 0; i < half; i++) { ws.host_w[i] = cur; cur = host_mulmod(cur, g, p); } - return cudaMemcpy(dst, ws.host_w.data(), sizeof(u64) * half, cudaMemcpyHostToDevice) == cudaSuccess; + return cudaMemcpyAsync( + dst, + ws.host_w, + sizeof(u64) * static_cast(half), + cudaMemcpyHostToDevice, + ws.stream + ) == cudaSuccess && cudaStreamSynchronize(ws.stream) == cudaSuccess; } // Compute and upload all four twiddle tables (forward+inverse for both primes) @@ -240,13 +535,29 @@ bool ensure_twiddles(NttWorkspace &ws, int n) { return true; } -bool load_digits(NttWorkspace &ws, u64 *dst, const std::vector &digits, int n) { - ws.host_in.assign(static_cast(n), 0); +bool load_digits( + NttWorkspace &ws, + u64 *host, + u64 *dst, + const std::vector &digits, + int n +) { for (size_t i = 0; i < digits.size(); i++) { - ws.host_in[i] = digits[i]; // 0..65535 < every modulus + host[i] = digits[i]; } - return cudaMemcpy(dst, ws.host_in.data(), sizeof(u64) * static_cast(n), - cudaMemcpyHostToDevice) == cudaSuccess; + if (cudaMemcpyAsync( + dst, + host, + sizeof(u64) * digits.size(), + cudaMemcpyHostToDevice, + ws.stream + ) != cudaSuccess) return false; + return digits.size() >= static_cast(n) || cudaMemsetAsync( + dst + digits.size(), + 0, + sizeof(u64) * (static_cast(n) - digits.size()), + ws.stream + ) == cudaSuccess; } constexpr int BLOCK = 256; @@ -256,27 +567,27 @@ constexpr int SHARED_TILE = 2048; // Run all butterfly stages for one transform: the low stages (len <= tile) // fused in shared memory, the remaining high-stride stages as global passes. -void run_stages(u64 *a, const u64 *tw, int n, u64 p, u64 mu) { +void run_stages(u64 *a, const u64 *tw, int n, u64 p, u64 mu, cudaStream_t stream) { const int tile = n < SHARED_TILE ? n : SHARED_TILE; - k_ntt_shared<<(tile)>>>( + k_ntt_shared<<(tile), stream>>>( a, tw, n, tile, p, mu); const int butter = (n / 2 + BLOCK - 1) / BLOCK; for (int len = 2 * tile; len <= n; len <<= 1) { - k_butterfly<<>>(a, tw, n, len, p, mu); + k_butterfly<<>>(a, tw, n, len, p, mu); } } -bool forward_ntt(u64 *a, const u64 *wf, int n, int logn, u64 p, u64 mu) { - k_bit_reverse<<<(n + BLOCK - 1) / BLOCK, BLOCK>>>(a, n, logn); - run_stages(a, wf, n, p, mu); +bool forward_ntt(u64 *a, const u64 *wf, int n, int logn, u64 p, u64 mu, cudaStream_t stream) { + k_bit_reverse<<<(n + BLOCK - 1) / BLOCK, BLOCK, 0, stream>>>(a, n, logn); + run_stages(a, wf, n, p, mu, stream); return cudaGetLastError() == cudaSuccess; } -bool inverse_ntt(u64 *a, const u64 *wi, int n, int logn, u64 p, u64 mu) { - k_bit_reverse<<<(n + BLOCK - 1) / BLOCK, BLOCK>>>(a, n, logn); - run_stages(a, wi, n, p, mu); +bool inverse_ntt(u64 *a, const u64 *wi, int n, int logn, u64 p, u64 mu, cudaStream_t stream) { + k_bit_reverse<<<(n + BLOCK - 1) / BLOCK, BLOCK, 0, stream>>>(a, n, logn); + run_stages(a, wi, n, p, mu, stream); const u64 inv_n = host_powmod(static_cast(n), p - 2, p); - k_scale<<<(n + BLOCK - 1) / BLOCK, BLOCK>>>(a, n, inv_n, p, mu); + k_scale<<<(n + BLOCK - 1) / BLOCK, BLOCK, 0, stream>>>(a, n, inv_n, p, mu); return cudaGetLastError() == cudaSuccess; } @@ -289,24 +600,25 @@ bool convolve_one_prime(NttWorkspace &ws, const std::vector &a, // transform of a, so skip the redundant load + forward NTT and square fa in // place. Saves one of the two forward transforms per prime. const bool squaring = (&a == &b); - if (!load_digits(ws, ws.fa, a, n)) { + if (!load_digits(ws, ws.host_a, ws.fa, a, n)) { return false; } - if (!squaring && !load_digits(ws, ws.fb, b, n)) { + if (!squaring && !load_digits(ws, ws.host_b, ws.fb, b, n)) { return false; } - if (!forward_ntt(ws.fa, wf, n, logn, p, mu)) { + if (!forward_ntt(ws.fa, wf, n, logn, p, mu, ws.stream)) { return false; } - if (!squaring && !forward_ntt(ws.fb, wf, n, logn, p, mu)) { + if (!squaring && !forward_ntt(ws.fb, wf, n, logn, p, mu, ws.stream)) { return false; } const u64 *rhs = squaring ? ws.fa : ws.fb; - k_pointwise<<<(n + BLOCK - 1) / BLOCK, BLOCK>>>(ws.fa, rhs, n, p, mu); + k_pointwise<<<(n + BLOCK - 1) / BLOCK, BLOCK, 0, ws.stream>>>(ws.fa, rhs, n, p, mu); if (cudaGetLastError() != cudaSuccess) { return false; } - return inverse_ntt(ws.fa, wi, n, logn, p, mu); + return inverse_ntt(ws.fa, wi, n, logn, p, mu, ws.stream) && + cudaStreamSynchronize(ws.stream) == cudaSuccess; } } // namespace @@ -315,7 +627,8 @@ bool convolve_ntt_u16_to_limbs(const std::vector &a, const std::vector &b, std::vector &out, unsigned bits_per_digit, - unsigned limb_bits) { + unsigned limb_bits, + uint64_t max_queue_wait_nanos) { if (bits_per_digit != 16 || limb_bits == 0 || limb_bits > 64 || limb_bits % 16 != 0) { return false; } @@ -338,31 +651,39 @@ bool convolve_ntt_u16_to_limbs(const std::vector &a, return false; } - thread_local NttWorkspace ws; - if (!ws.ensure(n) || !ensure_twiddles(ws, n)) { - return false; - } + NttWorkspacePool::Lease lease = ntt_workspace_pool().acquire(n, max_queue_wait_nanos); + if (!lease) return false; + NttWorkspace &ws = lease.workspace(); // Prime 1 -> c1, prime 3 -> fa, then CRT into out. if (!convolve_one_prime(ws, a, b, n, logn, MOD1, MU1, ws.wf1, ws.wi1)) { return false; } - if (cudaMemcpy(ws.c1, ws.fa, sizeof(u64) * static_cast(n), - cudaMemcpyDeviceToDevice) != cudaSuccess) { + if (cudaMemcpyAsync( + ws.c1, + ws.fa, + sizeof(u64) * static_cast(n), + cudaMemcpyDeviceToDevice, + ws.stream + ) != cudaSuccess) { return false; } if (!convolve_one_prime(ws, a, b, n, logn, MOD3, MU3, ws.wf3, ws.wi3)) { return false; } - k_crt<<<(static_cast(result_size) + BLOCK - 1) / BLOCK, BLOCK>>>( + k_crt<<<(static_cast(result_size) + BLOCK - 1) / BLOCK, BLOCK, 0, ws.stream>>>( ws.c1, ws.fa, ws.out, static_cast(result_size), MU3); if (cudaGetLastError() != cudaSuccess) { return false; } - ws.host_out.resize(result_size); - if (cudaMemcpy(ws.host_out.data(), ws.out, sizeof(u64) * result_size, - cudaMemcpyDeviceToHost) != cudaSuccess) { + if (cudaMemcpyAsync( + ws.host_out, + ws.out, + sizeof(u64) * result_size, + cudaMemcpyDeviceToHost, + ws.stream + ) != cudaSuccess || cudaStreamSynchronize(ws.stream) != cudaSuccess) { return false; } @@ -398,4 +719,25 @@ bool convolve_ntt_u16_to_limbs(const std::vector &a, return true; } +bool configure_ntt_workspace_pool(int device) { + if (device < 0 || cudaSetDevice(device) != cudaSuccess) return false; + return ntt_workspace_pool().configure(device); +} + +uint64_t ntt_workspace_in_use_bytes() { + return ntt_workspace_pool().in_use_bytes(); +} + +int ntt_workspace_capacity() { + return ntt_workspace_pool().capacity(); +} + +int ntt_workspace_in_use() { + return ntt_workspace_pool().in_use(); +} + +bool ntt_workspace_available(int transform_size) { + return ntt_workspace_pool().available(transform_size); +} + } diff --git a/src/main/cpp/cuda_ntt.h b/src/main/cpp/cuda_ntt.h index e1b226a..bbf77b3 100644 --- a/src/main/cpp/cuda_ntt.h +++ b/src/main/cpp/cuda_ntt.h @@ -6,6 +6,8 @@ namespace bigmath::cuda { +inline constexpr int NTT_MAX_TRANSFORM_SIZE = 1 << 23; + // GPU integer NTT convolution with dual-modulus CRT reconstruction. // // Unlike the cuFFT (FP64) path, coefficients are computed in exact modular @@ -21,7 +23,14 @@ bool convolve_ntt_u16_to_limbs(const std::vector &a, const std::vector &b, std::vector &out, unsigned bits_per_digit, - unsigned limb_bits); + unsigned limb_bits, + uint64_t max_queue_wait_nanos = 0); + +bool configure_ntt_workspace_pool(int device); +uint64_t ntt_workspace_in_use_bytes(); +int ntt_workspace_capacity(); +int ntt_workspace_in_use(); +bool ntt_workspace_available(int transform_size); } diff --git a/src/main/cpp/cuda_runtime_state.cpp b/src/main/cpp/cuda_runtime_state.cpp index cf05395..0d8694b 100644 --- a/src/main/cpp/cuda_runtime_state.cpp +++ b/src/main/cpp/cuda_runtime_state.cpp @@ -1,222 +1,463 @@ #include "cuda_runtime_state.h" -#include "bigmath_ffm.h" +#include "caching/product_cache.h" +#include "runtime/cuda_calibration.h" + +#include #include +#include +#include +#include #include - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#else -#include -#endif +#include +#include +#include +#include #ifdef BIGMATH_HAS_CUDA +#include "cuda_convolution.h" +#include "cuda_ntt.h" #include #endif +static_assert(sizeof(BigmathRuntimeSnapshot) == 920); + namespace bigmath::cuda { +namespace { + +enum class InitializationPhase : int { + NOT_STARTED = 0, + PROBING = 1, + CALIBRATING = 2, + FINISHED = 3 +}; struct RuntimeState { - bool initialized = false; bool available = false; int count = 0; int selected_device = -1; int probe_count = 0; + RuntimeBackend active_backend = RuntimeBackend::CPU; + uint64_t threshold_bits[4] = {UINT64_MAX, UINT64_MAX, UINT64_MAX, UINT64_MAX}; + uint64_t square_threshold_bits = UINT64_MAX; + uint32_t ntt_transform_mask = 0; + uint64_t workspace_budget_bytes = 0; + uint64_t workspace_in_use_bytes = 0; + uint32_t workspace_capacity = 0; + uint32_t workspace_in_use = 0; + bigmath::runtime::CudaCalibrationProfile calibration; char name[256] = ""; - char message[512] = "CUDA runtime has not been probed"; + char message[512] = "Native runtime initialization has not started"; }; -enum class ProbePhase : int { - not_started = 0, - running = 1, - finishing = 2, - finished = 3 +std::mutex state_mutex; +std::condition_variable state_changed; +RuntimeConfiguration configured_options; +RuntimeState state; +std::atomic initialization_phase{static_cast(InitializationPhase::NOT_STARTED)}; +std::atomic calibration_status{ + static_cast(CalibrationStatus::NOT_STARTED) }; +std::atomic successful_multiply_count{0}; +std::atomic cpu_fallbacks{0}; -static RuntimeState state; -static std::atomic probe_phase{static_cast(ProbePhase::not_started)}; -static std::atomic successful_multiply_count{0}; - -static void copy_text(char *target, size_t target_size, const char *value) { - if (target_size == 0) { - return; - } +void copy_text(char *target, size_t target_size, const char *value) { + if (target_size == 0) return; std::snprintf(target, target_size, "%s", value == nullptr ? "" : value); } -static void sleep_one_millisecond() { -#ifdef _WIN32 - Sleep(1); -#else - usleep(1000); -#endif -} - -static RuntimeState unavailable_state(const char *message) { +RuntimeState unavailable_state(const char *message, CalibrationStatus status) { RuntimeState result; - result.initialized = true; - result.available = false; - result.count = 0; - result.selected_device = -1; result.probe_count = 1; - copy_text(result.name, sizeof(result.name), ""); copy_text(result.message, sizeof(result.message), message); - return result; -} - -static RuntimeState unavailable_state(const char *message, int device_count) { - RuntimeState result = unavailable_state(message); - result.count = device_count; + calibration_status.store(static_cast(status), std::memory_order_release); return result; } #ifdef BIGMATH_HAS_CUDA -static RuntimeState cuda_error_state(const char *operation, cudaError_t err, int device_count = 0) { - RuntimeState result = unavailable_state("", device_count); - std::snprintf(result.message, sizeof(result.message), "%s failed: %s", operation, cudaGetErrorString(err)); +RuntimeState cuda_error_state(const char *operation, cudaError_t error, int count = 0) { + RuntimeState result = unavailable_state("", CalibrationStatus::FAILED); + result.count = count; + std::snprintf( + result.message, + sizeof(result.message), + "%s failed: %s", + operation, + cudaGetErrorString(error) + ); return result; } #endif -static RuntimeState probe_runtime() { +RuntimeState probe_runtime(const RuntimeConfiguration &configuration) { + if (configuration.backend == RuntimeBackend::CPU) { + RuntimeState result = unavailable_state( + "CPU backend was selected by RuntimeOptions", + CalibrationStatus::READY + ); + result.active_backend = RuntimeBackend::CPU; + return result; + } #ifndef BIGMATH_HAS_CUDA - return unavailable_state("CUDA support was not compiled for this platform"); + return unavailable_state( + "CUDA support was not compiled for this platform", + CalibrationStatus::UNAVAILABLE + ); #else RuntimeState result; - result.initialized = true; result.probe_count = 1; - int count = 0; - cudaError_t err = cudaGetDeviceCount(&count); - if (err != cudaSuccess) { - return cuda_error_state("cudaGetDeviceCount", err); - } - + cudaError_t error = cudaGetDeviceCount(&count); + if (error != cudaSuccess) return cuda_error_state("cudaGetDeviceCount", error); result.count = count; if (count <= 0) { - return unavailable_state("No CUDA devices were detected"); + return unavailable_state("No CUDA devices were detected", CalibrationStatus::UNAVAILABLE); } - cudaDeviceProp prop{}; - err = cudaGetDeviceProperties(&prop, 0); - if (err != cudaSuccess) { - return cuda_error_state("cudaGetDeviceProperties", err, count); - } - - err = cudaSetDevice(0); - if (err != cudaSuccess) { - return cuda_error_state("cudaSetDevice", err, count); + const int selected = configuration.selected_device < 0 ? 0 : configuration.selected_device; + if (selected >= count) { + return unavailable_state("Configured CUDA device index is unavailable", CalibrationStatus::FAILED); } + error = cudaSetDevice(selected); + if (error != cudaSuccess) return cuda_error_state("cudaSetDevice", error, count); + cudaDeviceProp properties{}; + error = cudaGetDeviceProperties(&properties, selected); + if (error != cudaSuccess) return cuda_error_state("cudaGetDeviceProperties", error, count); + + size_t free_bytes = 0; + size_t total_bytes = 0; + error = cudaMemGetInfo(&free_bytes, &total_bytes); + if (error != cudaSuccess) return cuda_error_state("cudaMemGetInfo", error, count); + const long double fraction_budget = + static_cast(free_bytes) * configuration.workspace_fraction; + const uint64_t fraction_bytes = fraction_budget >= static_cast(UINT64_MAX) + ? UINT64_MAX + : static_cast(fraction_budget); result.available = true; - result.selected_device = 0; - copy_text(result.name, sizeof(result.name), prop.name); - std::snprintf(result.message, sizeof(result.message), "CUDA device 0 is available: %s", result.name); + result.selected_device = selected; + result.workspace_budget_bytes = std::min( + configuration.workspace_max_bytes, + fraction_bytes + ); + if (!configure_convolution_workspace_pool(selected, result.workspace_budget_bytes) || + !configure_ntt_workspace_pool(selected)) { + result.available = false; + result.active_backend = RuntimeBackend::CPU; + calibration_status.store( + static_cast(CalibrationStatus::FAILED), + std::memory_order_release + ); + copy_text( + result.message, + sizeof(result.message), + "Failed to configure the CUDA workspace pool" + ); + return result; + } + copy_text(result.name, sizeof(result.name), properties.name); + if (configuration.backend == RuntimeBackend::AUTO) { + result.active_backend = RuntimeBackend::CPU; + calibration_status.store( + static_cast(CalibrationStatus::RUNNING), + std::memory_order_release + ); + std::snprintf( + result.message, + sizeof(result.message), + "CUDA device %d is available; calibration is pending: %s", + selected, + result.name + ); + } else { + result.active_backend = configuration.backend; + calibration_status.store( + static_cast(CalibrationStatus::READY), + std::memory_order_release + ); + std::snprintf( + result.message, + sizeof(result.message), + "CUDA device %d is ready with an explicit backend: %s", + selected, + result.name + ); + } return result; #endif } -static bool begin_probe() { - int expected = static_cast(ProbePhase::not_started); - return probe_phase.compare_exchange_strong(expected, static_cast(ProbePhase::running), - std::memory_order_acq_rel); +void run_initialization() { + RuntimeConfiguration configuration; + { + std::lock_guard lock(state_mutex); + configuration = configured_options; + } + RuntimeState initialized = probe_runtime(configuration); + { + std::lock_guard lock(state_mutex); + state = initialized; + } + if (initialized.available && configuration.backend == RuntimeBackend::AUTO) { + initialization_phase.store( + static_cast(InitializationPhase::CALIBRATING), + std::memory_order_release + ); + state_changed.notify_all(); + try { + bigmath::runtime::CudaCalibrationProfile profile = + bigmath::runtime::calibrate_cuda( + configuration.calibration_millis, + initialized.workspace_budget_bytes + ); + { + std::lock_guard lock(state_mutex); + state.calibration = profile; + state.active_backend = profile.completed ? RuntimeBackend::AUTO : RuntimeBackend::CPU; + for (size_t index = 0; index < 4; index++) { + state.threshold_bits[index] = profile.threshold_bits[index]; + } + state.square_threshold_bits = profile.square_threshold_bits; + state.ntt_transform_mask = profile.ntt_transform_mask; + if (profile.completed) { + calibration_status.store( + static_cast(CalibrationStatus::READY), + std::memory_order_release + ); + std::snprintf( + state.message, + sizeof(state.message), + profile.loaded_from_cache + ? "CUDA calibration loaded from cache for device %d: %s" + : "CUDA calibration completed for device %d: %s", + state.selected_device, + state.name + ); + } else { + calibration_status.store( + static_cast(CalibrationStatus::FAILED), + std::memory_order_release + ); + copy_text( + state.message, + sizeof(state.message), + "CUDA calibration failed; CPU dispatch remains active" + ); + } + } + } catch (const std::exception &exception) { + std::lock_guard lock(state_mutex); + state.active_backend = RuntimeBackend::CPU; + calibration_status.store( + static_cast(CalibrationStatus::FAILED), + std::memory_order_release + ); + std::snprintf( + state.message, + sizeof(state.message), + "CUDA calibration failed: %s", + exception.what() + ); + } + } + initialization_phase.store( + static_cast(InitializationPhase::FINISHED), + std::memory_order_release + ); + state_changed.notify_all(); } -static bool finish_probe(RuntimeState result) { - int expected = static_cast(ProbePhase::running); - if (!probe_phase.compare_exchange_strong(expected, static_cast(ProbePhase::finishing), - std::memory_order_acq_rel)) { - return false; +void wait_for_initialization() { + if (initialization_phase.load(std::memory_order_acquire) == + static_cast(InitializationPhase::FINISHED)) { + return; } - state = result; - probe_phase.store(static_cast(ProbePhase::finished), std::memory_order_release); - return true; + std::unique_lock lock(state_mutex); + state_changed.wait(lock, [] { + return initialization_phase.load(std::memory_order_acquire) == + static_cast(InitializationPhase::FINISHED); + }); } -static void run_probe_body() { - finish_probe(probe_runtime()); +void wait_for_probe() { + const int phase = initialization_phase.load(std::memory_order_acquire); + if (phase >= static_cast(InitializationPhase::CALIBRATING)) return; + std::unique_lock lock(state_mutex); + state_changed.wait(lock, [] { + return initialization_phase.load(std::memory_order_acquire) >= + static_cast(InitializationPhase::CALIBRATING); + }); } -static void wait_for_probe() { - if (probe_phase.load(std::memory_order_acquire) == static_cast(ProbePhase::finished)) { - return; +RuntimeState state_snapshot() { + wait_for_initialization(); + std::lock_guard lock(state_mutex); + return state; +} + +RuntimeState probe_state_snapshot() { + wait_for_probe(); + std::lock_guard lock(state_mutex); + return state; +} + +} + +bool configure(const RuntimeConfiguration &configuration) { + if (initialization_phase.load(std::memory_order_acquire) != + static_cast(InitializationPhase::NOT_STARTED)) { + return false; } - for (int i = 0; i < 10000; i++) { - if (probe_phase.load(std::memory_order_acquire) == static_cast(ProbePhase::finished)) { - return; - } - sleep_one_millisecond(); + std::lock_guard lock(state_mutex); + if (initialization_phase.load(std::memory_order_relaxed) != + static_cast(InitializationPhase::NOT_STARTED)) { + return false; } + configured_options = configuration; + bigmath::caching::configure_product_cache( + configuration.product_cache_enabled, + 16, + static_cast(configuration.product_cache_bytes) + ); + return true; +} - int expected = static_cast(ProbePhase::running); - if (probe_phase.compare_exchange_strong(expected, static_cast(ProbePhase::finishing), - std::memory_order_acq_rel)) { - state = unavailable_state("CUDA runtime probe timed out"); - probe_phase.store(static_cast(ProbePhase::finished), std::memory_order_release); - return; +int initialize_async() { + int expected = static_cast(InitializationPhase::NOT_STARTED); + if (!initialization_phase.compare_exchange_strong( + expected, + static_cast(InitializationPhase::PROBING), + std::memory_order_acq_rel + )) { + return 0; } - while (probe_phase.load(std::memory_order_acquire) != static_cast(ProbePhase::finished)) { - sleep_one_millisecond(); + try { + std::thread(run_initialization).detach(); + return 0; + } catch (const std::exception &exception) { + { + std::lock_guard lock(state_mutex); + state = unavailable_state("", CalibrationStatus::FAILED); + std::snprintf( + state.message, + sizeof(state.message), + "Failed to start the Native runtime initialization thread: %s", + exception.what() + ); + } + initialization_phase.store( + static_cast(InitializationPhase::FINISHED), + std::memory_order_release + ); + state_changed.notify_all(); + return -1; } } -void initialize_once() { - if (begin_probe()) { - run_probe_body(); - } else { - wait_for_probe(); - } +bool is_available() { + return probe_state_snapshot().available; } -void start_background_probe() { - if (!begin_probe()) { - return; +bool calibration_ready() { + return calibration_status.load(std::memory_order_acquire) == + static_cast(CalibrationStatus::READY); +} + +RuntimeBackend active_backend() { + if (!calibration_ready()) return RuntimeBackend::CPU; + std::lock_guard lock(state_mutex); + return state.active_backend; +} + +DispatchDecision choose_dispatch(const DispatchRequest &request) { + DispatchDecision decision; + if (!calibration_ready()) { + if (calibration_status.load(std::memory_order_acquire) == + static_cast(CalibrationStatus::RUNNING)) { + cpu_fallbacks.fetch_add(1, std::memory_order_relaxed); + } + return decision; } -#if defined(BIGMATH_HAS_CUDA) && defined(_WIN32) - HANDLE thread = CreateThread(nullptr, 0, [](LPVOID) -> DWORD { - run_probe_body(); - return 0; - }, nullptr, 0, nullptr); - if (thread != nullptr) { - CloseHandle(thread); - return; + if (request.left_bits == 0 || request.right_bits == 0 || + request.transform_size <= 0) { + return decision; } - finish_probe(unavailable_state("Failed to start CUDA runtime probe thread")); -#else - run_probe_body(); + + RuntimeState current; + { + std::lock_guard lock(state_mutex); + current = state; + } + if (!current.available || current.active_backend == RuntimeBackend::CPU) return decision; + if (current.active_backend == RuntimeBackend::CUFFT) { + decision.backend = RuntimeBackend::CUFFT; + return decision; + } + if (current.active_backend == RuntimeBackend::NTT) { +#ifdef BIGMATH_HAS_CUDA + if (request.transform_size <= bigmath::cuda::NTT_MAX_TRANSFORM_SIZE) { + decision.backend = RuntimeBackend::NTT; + } #endif -} + return decision; + } -static void ensure_initialized() { - if (probe_phase.load(std::memory_order_acquire) == static_cast(ProbePhase::not_started)) { - initialize_once(); - return; + const uint64_t maximum = std::max(request.left_bits, request.right_bits); + const uint64_t minimum = std::min(request.left_bits, request.right_bits); + size_t shape = 4; + if (!request.square) { + const uint64_t ratio = maximum / minimum + (maximum % minimum == 0 ? 0 : 1); + if (ratio <= 1) shape = 0; + else if (ratio <= 2) shape = 1; + else if (ratio <= 8) shape = 2; + else if (ratio <= 64) shape = 3; + else return decision; } - wait_for_probe(); -} -bool is_available() { - if (probe_phase.load(std::memory_order_acquire) == static_cast(ProbePhase::finished)) { - return state.available; + int transform_log = 0; + int transform = request.transform_size; + while (transform > 1 && (transform & 1) == 0) { + transform >>= 1; + transform_log++; + } + if (transform != 1 || transform_log >= static_cast(bigmath::runtime::CUDA_TRANSFORM_BUCKETS)) { + return decision; } - ensure_initialized(); - return state.available; + const bigmath::runtime::DispatchProfileCell &cell = + current.calibration.cells[shape][static_cast(transform_log)]; + if (!cell.measured || cell.backend == bigmath::runtime::CalibratedBackend::CPU) return decision; + + bool workspace_available = false; + uint64_t gpu_nanos = 0; +#ifdef BIGMATH_HAS_CUDA + if (cell.backend == bigmath::runtime::CalibratedBackend::NTT) { + if ((current.ntt_transform_mask & (UINT32_C(1) << transform_log)) == 0) return decision; + workspace_available = ntt_workspace_available(request.transform_size); + gpu_nanos = workspace_available ? cell.ntt_nanos : cell.ntt_cold_nanos; + decision.backend = RuntimeBackend::NTT; + } else { + workspace_available = convolution_workspace_available(request.transform_size); + gpu_nanos = request.spectrum_cached ? cell.cufft_nanos : cell.cufft_cold_nanos; + decision.backend = RuntimeBackend::CUFFT; + } +#else + return DispatchDecision{}; +#endif + if (gpu_nanos == 0 || gpu_nanos >= cell.cpu_nanos) return DispatchDecision{}; + if (!workspace_available) decision.max_queue_wait_nanos = cell.cpu_nanos - gpu_nanos; + return decision; } int device_count() { - ensure_initialized(); - return state.count; + return probe_state_snapshot().count; } int device_id() { - ensure_initialized(); - return state.selected_device; + return probe_state_snapshot().selected_device; } int probe_count() { - ensure_initialized(); - return state.probe_count; + return probe_state_snapshot().probe_count; } void record_multiply() { @@ -227,37 +468,112 @@ int multiply_count() { return successful_multiply_count.load(std::memory_order_relaxed); } -const char *device_name() { - ensure_initialized(); - return state.name; +void record_cpu_fallback() { + cpu_fallbacks.fetch_add(1, std::memory_order_relaxed); } -const char *status_message() { - ensure_initialized(); - return state.message; +uint64_t cpu_fallback_count() { + return cpu_fallbacks.load(std::memory_order_relaxed); +} + +const char *device_name() { + thread_local char copy[256]; + RuntimeState current = state_snapshot(); + copy_text(copy, sizeof(copy), current.name); + return copy; } +const char *status_message() { + thread_local char copy[512]; + RuntimeState current = state_snapshot(); + copy_text(copy, sizeof(copy), current.message); + return copy; } +int snapshot(BigmathRuntimeSnapshot *out) { + if (out == nullptr) return -1; + RuntimeState current = state_snapshot(); + std::memset(out, 0, sizeof(*out)); + for (size_t index = 0; index < 4; index++) out->threshold_bits[index] = current.threshold_bits[index]; + out->square_threshold_bits = current.square_threshold_bits; + out->workspace_budget_bytes = current.workspace_budget_bytes; + out->workspace_in_use_bytes = current.workspace_in_use_bytes; + out->cpu_fallback_count = cpu_fallback_count(); + const bigmath::caching::ProductCacheMetrics cache_metrics = + bigmath::caching::product_cache_metrics(); + out->product_cache_hits = cache_metrics.hits; + out->product_cache_misses = cache_metrics.misses; + out->product_cache_admissions = cache_metrics.admissions; + out->product_cache_evictions = cache_metrics.evictions; + out->product_cache_bytes = cache_metrics.bytes; + out->schema_version = 1; + out->calibration_status = calibration_status.load(std::memory_order_acquire); + out->active_backend = static_cast(current.active_backend); + out->configured_backend = static_cast(configured_options.backend); + out->cuda_available = current.available ? 1 : 0; + out->device_count = static_cast(current.count); + out->selected_device = current.selected_device; + out->ntt_enabled = current.ntt_transform_mask != 0 ? 1 : 0; + out->ntt_transform_mask = current.ntt_transform_mask; + out->workspace_capacity = current.workspace_capacity; + out->workspace_in_use = current.workspace_in_use; #ifdef BIGMATH_HAS_CUDA -#ifdef _WIN32 -BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID) { - if (reason == DLL_PROCESS_ATTACH) { - DisableThreadLibraryCalls(module); - bigmath::cuda::start_background_probe(); + if (current.available) { + out->workspace_budget_bytes = convolution_workspace_budget_bytes(); + out->workspace_in_use_bytes = + convolution_workspace_in_use_bytes() + ntt_workspace_in_use_bytes(); + out->workspace_capacity = static_cast( + convolution_workspace_capacity() + ntt_workspace_capacity() + ); + out->workspace_in_use = static_cast( + convolution_workspace_in_use() + ntt_workspace_in_use() + ); } - return TRUE; +#endif + out->probe_count = static_cast(current.probe_count); + copy_text(out->device_name, sizeof(out->device_name), current.name); + copy_text(out->status_message, sizeof(out->status_message), current.message); + return 0; } -#else -__attribute__((constructor)) -static void bigmath_cuda_constructor() { - bigmath::cuda::start_background_probe(); + } -#endif -#endif extern "C" { +int32_t bigmath_runtime_configure( + int32_t product_cache_enabled, + uint64_t product_cache_bytes, + double gpu_workspace_fraction, + uint64_t gpu_workspace_max_bytes, + uint64_t calibration_millis, + int32_t cuda_device, + int32_t cuda_backend +) { + if (!std::isfinite(gpu_workspace_fraction) || gpu_workspace_fraction <= 0.0 || + gpu_workspace_fraction > 1.0 || gpu_workspace_max_bytes == 0 || + calibration_millis == 0 || cuda_device < -1 || cuda_backend < 0 || cuda_backend > 3 || + product_cache_bytes > static_cast(SIZE_MAX)) { + return -1; + } + bigmath::cuda::RuntimeConfiguration configuration; + configuration.product_cache_enabled = product_cache_enabled != 0; + configuration.product_cache_bytes = product_cache_bytes; + configuration.workspace_fraction = gpu_workspace_fraction; + configuration.workspace_max_bytes = gpu_workspace_max_bytes; + configuration.calibration_millis = calibration_millis; + configuration.selected_device = cuda_device; + configuration.backend = static_cast(cuda_backend); + return bigmath::cuda::configure(configuration) ? 0 : -2; +} + +int32_t bigmath_runtime_initialize() { + return bigmath::cuda::initialize_async(); +} + +int32_t bigmath_runtime_snapshot(BigmathRuntimeSnapshot *snapshot) { + return bigmath::cuda::snapshot(snapshot); +} + int bigmath_cuda_available() { return bigmath::cuda::is_available() ? 1 : 0; } diff --git a/src/main/cpp/cuda_runtime_state.h b/src/main/cpp/cuda_runtime_state.h index 4318f7a..56efef7 100644 --- a/src/main/cpp/cuda_runtime_state.h +++ b/src/main/cpp/cuda_runtime_state.h @@ -1,18 +1,67 @@ #ifndef BIGMATH_CUDA_RUNTIME_STATE_H #define BIGMATH_CUDA_RUNTIME_STATE_H +#include "bigmath_ffm.h" + +#include + namespace bigmath::cuda { -void initialize_once(); +enum class RuntimeBackend : uint32_t { + AUTO = 0, + CPU = 1, + CUFFT = 2, + NTT = 3 +}; + +enum class CalibrationStatus : uint32_t { + NOT_STARTED = 0, + RUNNING = 1, + READY = 2, + FAILED = 3, + UNAVAILABLE = 4 +}; + +struct RuntimeConfiguration { + bool product_cache_enabled = true; + uint64_t product_cache_bytes = UINT64_C(64) * 1024 * 1024; + double workspace_fraction = 0.25; + uint64_t workspace_max_bytes = UINT64_C(512) * 1024 * 1024; + uint64_t calibration_millis = 10000; + int selected_device = -1; + RuntimeBackend backend = RuntimeBackend::AUTO; +}; + +struct DispatchRequest { + uint64_t left_bits; + uint64_t right_bits; + int transform_size; + bool square; + bool spectrum_cached; +}; + +struct DispatchDecision { + RuntimeBackend backend = RuntimeBackend::CPU; + uint64_t max_queue_wait_nanos = 0; +}; + +bool configure(const RuntimeConfiguration &configuration); +int initialize_async(); bool is_available(); +bool calibration_ready(); +RuntimeBackend active_backend(); +DispatchDecision choose_dispatch(const DispatchRequest &request); int device_count(); int device_id(); int probe_count(); void record_multiply(); int multiply_count(); +void record_cpu_fallback(); +uint64_t cpu_fallback_count(); const char *device_name(); const char *status_message(); +int snapshot(BigmathRuntimeSnapshot *out); } -#endif /* BIGMATH_CUDA_RUNTIME_STATE_H */ +#endif diff --git a/src/main/cpp/runtime/cuda_calibration.cpp b/src/main/cpp/runtime/cuda_calibration.cpp new file mode 100644 index 0000000..08f06c2 --- /dev/null +++ b/src/main/cpp/runtime/cuda_calibration.cpp @@ -0,0 +1,347 @@ +#include "cuda_calibration.h" +#include "cuda_calibration_cache.h" + +#include "../algos.h" +#include "../bigmath_ffm.h" +#include "../cuda_ntt.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(BIGMATH_HAS_CUDA) +#include +#endif + +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) +#include +#elif defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) +#include +#endif + +namespace bigmath::runtime { +namespace { + +using Clock = std::chrono::steady_clock; + +constexpr std::array CANDIDATE_BITS = { + UINT64_C(131072), UINT64_C(262144), UINT64_C(524288), + UINT64_C(1048576), UINT64_C(2097152), UINT64_C(4194304) +}; +constexpr std::array RATIOS = {1, 2, 8, 64}; +constexpr int WINDOWS = 3; + +#if defined(BIGMATH_HAS_CUDA) && defined(BIGMATH_HAS_GMP) + +std::string cpu_identity() { + std::array brand{}; +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) + int registers[4]{}; + __cpuid(registers, static_cast(UINT32_C(0x80000000))); + const uint32_t maximum = static_cast(registers[0]); + if (maximum >= UINT32_C(0x80000004)) { + for (uint32_t leaf = UINT32_C(0x80000002); leaf <= UINT32_C(0x80000004); leaf++) { + __cpuid(registers, static_cast(leaf)); + std::memcpy( + brand.data() + static_cast(leaf - UINT32_C(0x80000002)) * 16, + registers, + 16 + ); + } + } +#elif defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) + const unsigned maximum = __get_cpuid_max(UINT32_C(0x80000000), nullptr); + if (maximum >= UINT32_C(0x80000004)) { + for (unsigned leaf = UINT32_C(0x80000002); leaf <= UINT32_C(0x80000004); leaf++) { + unsigned eax = 0; + unsigned ebx = 0; + unsigned ecx = 0; + unsigned edx = 0; + __cpuid(leaf, eax, ebx, ecx, edx); + const std::array registers = {eax, ebx, ecx, edx}; + std::memcpy( + brand.data() + static_cast(leaf - UINT32_C(0x80000002)) * 16, + registers.data(), + 16 + ); + } + } +#endif + std::string result(brand.data()); + const size_t start = result.find_first_not_of(' '); + if (start == std::string::npos) return "unknown"; + const size_t end = result.find_last_not_of(' '); + return result.substr(start, end - start + 1); +} + +std::string calibration_cache_key(uint64_t budget_millis, uint64_t workspace_budget_bytes) { + int device = -1; + if (cudaGetDevice(&device) != cudaSuccess || device < 0) return {}; + cudaDeviceProp properties{}; + if (cudaGetDeviceProperties(&properties, device) != cudaSuccess) return {}; + int driver_version = 0; + int runtime_version = 0; + if (cudaDriverGetVersion(&driver_version) != cudaSuccess || + cudaRuntimeGetVersion(&runtime_version) != cudaSuccess) { + return {}; + } + + std::ostringstream key; + key << "schema=1" + << "\nabi=" << bigmath_abi_version() + << "\nbuild=" << bigmath_build_id() + << "\ndevice="; + key << std::hex << std::setfill('0'); + for (char byte : properties.uuid.bytes) { + key << std::setw(2) << static_cast(static_cast(byte)); + } + key << std::dec + << "\ncompute=" << properties.major << '.' << properties.minor + << "\ndriver=" << driver_version + << "\nruntime=" << runtime_version + << "\ncpu=" << cpu_identity() + << "\ngmp=" << gmp_version + << "\nmpfr=" << mpfr_get_version() + << "\nbudgetMillis=" << budget_millis + << "\nworkspaceBytes=" << workspace_budget_bytes; + return key.str(); +} + +class ScopedMpz { +public: + ScopedMpz() { mpz_init(value_); } + ~ScopedMpz() { mpz_clear(value_); } + mpz_ptr get() { return value_; } + mpz_srcptr get() const { return value_; } + + ScopedMpz(const ScopedMpz &) = delete; + ScopedMpz &operator=(const ScopedMpz &) = delete; + +private: + mpz_t value_; +}; + +void deterministic_value(mpz_ptr out, uint64_t bits, uint64_t seed) { + const size_t limbs = static_cast((bits + 63) / 64); + std::vector data(std::max(1, limbs)); + uint64_t state = seed; + for (uint64_t &limb : data) { + state ^= state >> 12; + state ^= state << 25; + state ^= state >> 27; + limb = state * UINT64_C(2685821657736338717); + } + const unsigned top_bits = static_cast((bits - 1) % 64 + 1); + if (top_bits < 64) data.back() &= (UINT64_C(1) << top_bits) - 1; + data.back() |= UINT64_C(1) << (top_bits - 1); + mpz_import(out, data.size(), -1, sizeof(uint64_t), 0, 0, data.data()); +} + +template +std::pair timed(Operation operation) { + const auto started = Clock::now(); + const bool completed = operation(); + const uint64_t nanos = static_cast( + std::chrono::duration_cast(Clock::now() - started).count() + ); + return {completed, nanos}; +} + +uint64_t average(const std::array &values) { + uint64_t total = 0; + for (uint64_t value : values) total += value / WINDOWS; + return total; +} + +uint64_t warm_average(const std::array &values) { + return (values[1] / 2) + (values[2] / 2); +} + +int transform_log2(uint64_t left_bits, uint64_t right_bits) { + const uint64_t digits = (left_bits + 15) / 16 + (right_bits + 15) / 16 - 1; + uint64_t transform = 1; + int log = 0; + while (transform < digits && log + 1 < static_cast(CUDA_TRANSFORM_BUCKETS)) { + transform <<= 1; + log++; + } + return transform < digits ? -1 : log; +} + +bool measure_case( + mpz_ptr left, + mpz_ptr right, + bool square, + int transform_log, + DispatchProfileCell &cell +) { + ScopedMpz expected; + ScopedMpz actual; + std::array cpu_times{}; + std::array cufft_times{}; + std::array ntt_times{}; + bool cufft_correct = true; + bool ntt_correct = (UINT64_C(1) << transform_log) <= + static_cast(bigmath::cuda::NTT_MAX_TRANSFORM_SIZE); + + for (int window = 0; window < WINDOWS; window++) { + const auto cpu = timed([&] { + mpz_mul(expected.get(), left, square ? left : right); + return true; + }); + cpu_times[window] = cpu.second; + + const auto cufft = timed([&] { + return bigmath::cuda_multiply_direct( + actual.get(), + left, + square ? left : right, + bigmath::DirectCudaBackend::CUFFT, + 0, + window != 0, + window == 0 + ); + }); + cufft_times[window] = cufft.second; + cufft_correct &= cufft.first && mpz_cmp(actual.get(), expected.get()) == 0; + if (window == 0 && cufft_correct) { + const bool warmed = bigmath::cuda_multiply_direct( + actual.get(), + left, + square ? left : right, + bigmath::DirectCudaBackend::CUFFT, + 0, + true, + false + ); + cufft_correct &= warmed && mpz_cmp(actual.get(), expected.get()) == 0; + } + + if (ntt_correct) { + const auto ntt = timed([&] { + return bigmath::cuda_multiply_direct( + actual.get(), + left, + square ? left : right, + bigmath::DirectCudaBackend::NTT, + 0, + false, + window == 0 + ); + }); + ntt_times[window] = ntt.second; + ntt_correct &= cufft.first && ntt.first && + mpz_cmp(actual.get(), expected.get()) == 0 && + ntt.second <= cufft.second - cufft.second / 10; + } + } + + cell.measured = true; + cell.cpu_nanos = average(cpu_times); + cell.cufft_cold_nanos = cufft_times[0]; + cell.cufft_nanos = warm_average(cufft_times); + cell.ntt_cold_nanos = ntt_correct ? ntt_times[0] : 0; + cell.ntt_nanos = ntt_correct ? warm_average(ntt_times) : 0; + if (ntt_correct && cell.ntt_nanos < cell.cpu_nanos) { + cell.backend = CalibratedBackend::NTT; + } else if (cufft_correct && cell.cufft_nanos < cell.cpu_nanos) { + cell.backend = CalibratedBackend::CUFFT; + } else { + cell.backend = CalibratedBackend::CPU; + } + return cufft_correct; +} + +#endif + +} + +CudaCalibrationProfile calibrate_cuda(uint64_t budget_millis, uint64_t workspace_budget_bytes) { + CudaCalibrationProfile profile; +#if !defined(BIGMATH_HAS_CUDA) || !defined(BIGMATH_HAS_GMP) + (void)budget_millis; + (void)workspace_budget_bytes; + return profile; +#else + std::unique_ptr cache; + try { + const std::string key = calibration_cache_key(budget_millis, workspace_budget_bytes); + if (!key.empty()) { + cache = std::make_unique(key); + if (cache->load(profile)) return profile; + } + } catch (const std::exception &exception) { + std::fprintf(stderr, "Bigmath CUDA calibration cache unavailable: %s\n", exception.what()); + cache.reset(); + } catch (...) { + std::fprintf(stderr, "Bigmath CUDA calibration cache unavailable\n"); + cache.reset(); + } + + const uint64_t bounded_millis = std::min(budget_millis, 60000); + const auto deadline = Clock::now() + std::chrono::milliseconds(bounded_millis); + bool measured = false; + for (uint64_t max_bits : CANDIDATE_BITS) { + for (size_t shape = 0; shape < RATIOS.size(); shape++) { + if (Clock::now() >= deadline) break; + const uint64_t min_bits = std::max(16, max_bits / RATIOS[shape]); + const int transform = transform_log2(max_bits, min_bits); + if (transform < 0) continue; + ScopedMpz left; + ScopedMpz right; + deterministic_value(left.get(), max_bits, UINT64_C(0x9e3779b97f4a7c15) ^ max_bits ^ shape); + deterministic_value(right.get(), min_bits, UINT64_C(0xbf58476d1ce4e5b9) ^ max_bits ^ shape); + DispatchProfileCell &cell = profile.cells[shape][static_cast(transform)]; + if (!measure_case(left.get(), right.get(), false, transform, cell)) continue; + measured = true; + if (cell.backend != CalibratedBackend::CPU && profile.threshold_bits[shape] == UINT64_MAX) { + profile.threshold_bits[shape] = max_bits; + } + if (cell.backend == CalibratedBackend::NTT) { + profile.ntt_transform_mask |= UINT32_C(1) << transform; + } + } + + if (Clock::now() >= deadline) break; + const int square_transform = transform_log2(max_bits, max_bits); + if (square_transform >= 0) { + ScopedMpz square; + deterministic_value(square.get(), max_bits, UINT64_C(0x94d049bb133111eb) ^ max_bits); + DispatchProfileCell &cell = profile.cells[4][static_cast(square_transform)]; + if (measure_case(square.get(), square.get(), true, square_transform, cell)) { + measured = true; + if (cell.backend != CalibratedBackend::CPU && profile.square_threshold_bits == UINT64_MAX) { + profile.square_threshold_bits = max_bits; + } + if (cell.backend == CalibratedBackend::NTT) { + profile.ntt_transform_mask |= UINT32_C(1) << square_transform; + } + } + } + } + profile.completed = measured; + if (profile.completed && cache != nullptr) { + try { + cache->store(profile); + } catch (const std::exception &exception) { + std::fprintf(stderr, "Bigmath CUDA calibration cache write failed: %s\n", exception.what()); + } catch (...) { + std::fprintf(stderr, "Bigmath CUDA calibration cache write failed\n"); + } + } + return profile; +#endif +} + +} diff --git a/src/main/cpp/runtime/cuda_calibration.h b/src/main/cpp/runtime/cuda_calibration.h new file mode 100644 index 0000000..17a8dce --- /dev/null +++ b/src/main/cpp/runtime/cuda_calibration.h @@ -0,0 +1,42 @@ +#ifndef BIGMATH_CUDA_CALIBRATION_H +#define BIGMATH_CUDA_CALIBRATION_H + +#include +#include +#include + +namespace bigmath::runtime { + +inline constexpr size_t CUDA_DISPATCH_SHAPES = 5; +inline constexpr size_t CUDA_TRANSFORM_BUCKETS = 24; + +enum class CalibratedBackend : uint8_t { + CPU, + CUFFT, + NTT +}; + +struct DispatchProfileCell { + bool measured = false; + CalibratedBackend backend = CalibratedBackend::CPU; + uint64_t cpu_nanos = 0; + uint64_t cufft_cold_nanos = 0; + uint64_t cufft_nanos = 0; + uint64_t ntt_cold_nanos = 0; + uint64_t ntt_nanos = 0; +}; + +struct CudaCalibrationProfile { + bool completed = false; + bool loaded_from_cache = false; + std::array, CUDA_DISPATCH_SHAPES> cells{}; + std::array threshold_bits = {UINT64_MAX, UINT64_MAX, UINT64_MAX, UINT64_MAX}; + uint64_t square_threshold_bits = UINT64_MAX; + uint32_t ntt_transform_mask = 0; +}; + +CudaCalibrationProfile calibrate_cuda(uint64_t budget_millis, uint64_t workspace_budget_bytes); + +} + +#endif diff --git a/src/main/cpp/runtime/cuda_calibration_cache.cpp b/src/main/cpp/runtime/cuda_calibration_cache.cpp new file mode 100644 index 0000000..a451a3d --- /dev/null +++ b/src/main/cpp/runtime/cuda_calibration_cache.cpp @@ -0,0 +1,369 @@ +#include "cuda_calibration_cache.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#define NOMINMAX +#include +#else +#include +#include +#include +#endif + +namespace bigmath::runtime { +namespace { + +constexpr std::array CACHE_MAGIC = {'B', 'M', 'C', 'A', 'L', '0', '0', '1'}; +constexpr uint32_t CACHE_SCHEMA_VERSION = 1; +constexpr uint64_t MAX_CACHE_BYTES = UINT64_C(65536); +constexpr uint32_t MAX_KEY_BYTES = 4096; + +std::filesystem::path cache_directory() { +#ifdef _WIN32 + const DWORD length = GetEnvironmentVariableW(L"LOCALAPPDATA", nullptr, 0); + if (length == 0) return {}; + std::vector value(length); + const DWORD written = GetEnvironmentVariableW(L"LOCALAPPDATA", value.data(), length); + if (written == 0 || written >= length) return {}; + return std::filesystem::path(value.data()) / L"Bigmath-FFM"; +#elif defined(__APPLE__) + const char *home = std::getenv("HOME"); + if (home == nullptr || home[0] == '\0') return {}; + return std::filesystem::path(home) / "Library" / "Caches" / "Bigmath-FFM"; +#else + const char *xdg_cache = std::getenv("XDG_CACHE_HOME"); + if (xdg_cache != nullptr && xdg_cache[0] != '\0') { + std::filesystem::path configured(xdg_cache); + if (configured.is_absolute()) return configured / "bigmath-ffm"; + } + const char *home = std::getenv("HOME"); + if (home == nullptr || home[0] == '\0') return {}; + return std::filesystem::path(home) / ".cache" / "bigmath-ffm"; +#endif +} + +void append_u8(std::vector &bytes, uint8_t value) { + bytes.push_back(value); +} + +void append_u32(std::vector &bytes, uint32_t value) { + for (unsigned shift = 0; shift < 32; shift += 8) { + bytes.push_back(static_cast(value >> shift)); + } +} + +void append_u64(std::vector &bytes, uint64_t value) { + for (unsigned shift = 0; shift < 64; shift += 8) { + bytes.push_back(static_cast(value >> shift)); + } +} + +class Decoder final { +public: + explicit Decoder(const std::vector &bytes) : bytes_(bytes) { + } + + bool read_u8(uint8_t &value) { + if (offset_ >= bytes_.size()) return false; + value = bytes_[offset_++]; + return true; + } + + bool read_u32(uint32_t &value) { + value = 0; + for (unsigned shift = 0; shift < 32; shift += 8) { + uint8_t byte = 0; + if (!read_u8(byte)) return false; + value |= static_cast(byte) << shift; + } + return true; + } + + bool read_u64(uint64_t &value) { + value = 0; + for (unsigned shift = 0; shift < 64; shift += 8) { + uint8_t byte = 0; + if (!read_u8(byte)) return false; + value |= static_cast(byte) << shift; + } + return true; + } + + bool read_bytes(uint8_t *target, size_t size) { + if (size > bytes_.size() - offset_) return false; + if (size > 0) std::copy_n(bytes_.data() + offset_, size, target); + offset_ += size; + return true; + } + + bool finished() const { + return offset_ == bytes_.size(); + } + +private: + const std::vector &bytes_; + size_t offset_ = 0; +}; + +std::vector encode( + const std::string &key, + const CudaCalibrationProfile &profile +) { + std::vector bytes; + bytes.reserve(8192); + bytes.insert(bytes.end(), CACHE_MAGIC.begin(), CACHE_MAGIC.end()); + append_u32(bytes, CACHE_SCHEMA_VERSION); + append_u32(bytes, static_cast(key.size())); + bytes.insert(bytes.end(), key.begin(), key.end()); + append_u8(bytes, profile.completed ? 1 : 0); + for (uint64_t threshold : profile.threshold_bits) append_u64(bytes, threshold); + append_u64(bytes, profile.square_threshold_bits); + append_u32(bytes, profile.ntt_transform_mask); + for (const auto &shape : profile.cells) { + for (const DispatchProfileCell &cell : shape) { + append_u8(bytes, cell.measured ? 1 : 0); + append_u8(bytes, static_cast(cell.backend)); + append_u64(bytes, cell.cpu_nanos); + append_u64(bytes, cell.cufft_cold_nanos); + append_u64(bytes, cell.cufft_nanos); + append_u64(bytes, cell.ntt_cold_nanos); + append_u64(bytes, cell.ntt_nanos); + } + } + return bytes; +} + +bool decode( + const std::vector &bytes, + const std::string &expected_key, + CudaCalibrationProfile &profile +) { + Decoder decoder(bytes); + std::array magic{}; + if (!decoder.read_bytes(magic.data(), magic.size()) || magic != CACHE_MAGIC) return false; + uint32_t schema = 0; + uint32_t key_size = 0; + if (!decoder.read_u32(schema) || schema != CACHE_SCHEMA_VERSION || + !decoder.read_u32(key_size) || key_size > MAX_KEY_BYTES) { + return false; + } + std::string key(key_size, '\0'); + if (!decoder.read_bytes(reinterpret_cast(key.data()), key.size()) || + key != expected_key) { + return false; + } + + CudaCalibrationProfile decoded; + uint8_t completed = 0; + if (!decoder.read_u8(completed) || completed != 1) return false; + decoded.completed = true; + for (uint64_t &threshold : decoded.threshold_bits) { + if (!decoder.read_u64(threshold)) return false; + } + if (!decoder.read_u64(decoded.square_threshold_bits) || + !decoder.read_u32(decoded.ntt_transform_mask)) { + return false; + } + for (auto &shape : decoded.cells) { + for (DispatchProfileCell &cell : shape) { + uint8_t measured = 0; + uint8_t backend = 0; + if (!decoder.read_u8(measured) || measured > 1 || + !decoder.read_u8(backend) || + backend > static_cast(CalibratedBackend::NTT) || + !decoder.read_u64(cell.cpu_nanos) || + !decoder.read_u64(cell.cufft_cold_nanos) || + !decoder.read_u64(cell.cufft_nanos) || + !decoder.read_u64(cell.ntt_cold_nanos) || + !decoder.read_u64(cell.ntt_nanos)) { + return false; + } + cell.measured = measured != 0; + cell.backend = static_cast(backend); + } + } + if (!decoder.finished()) return false; + decoded.loaded_from_cache = true; + profile = std::move(decoded); + return true; +} + +bool write_atomically( + const std::filesystem::path &data_path, + const std::vector &bytes +) { + std::filesystem::path temporary = data_path; + temporary += ".tmp"; +#ifdef _WIN32 + HANDLE file = CreateFileW( + temporary.c_str(), + GENERIC_WRITE, + 0, + nullptr, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + nullptr + ); + if (file == INVALID_HANDLE_VALUE) { + std::fprintf( + stderr, + "Bigmath CUDA calibration cache open failed with Windows error %lu\n", + static_cast(GetLastError()) + ); + return false; + } + size_t offset = 0; + bool success = true; + while (offset < bytes.size()) { + const DWORD requested = static_cast(std::min( + bytes.size() - offset, + static_cast(std::numeric_limits::max()) + )); + DWORD written = 0; + if (!WriteFile(file, bytes.data() + offset, requested, &written, nullptr) || written == 0) { + success = false; + break; + } + offset += written; + } + if (success) success = FlushFileBuffers(file) != 0; + if (!CloseHandle(file)) success = false; + if (!success) { + const DWORD error = GetLastError(); + DeleteFileW(temporary.c_str()); + std::fprintf( + stderr, + "Bigmath CUDA calibration cache write failed with Windows error %lu\n", + static_cast(error) + ); + return false; + } + if (!MoveFileExW( + temporary.c_str(), + data_path.c_str(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH | MOVEFILE_COPY_ALLOWED + )) { + const DWORD error = GetLastError(); + DeleteFileW(temporary.c_str()); + std::fprintf( + stderr, + "Bigmath CUDA calibration cache replace failed with Windows error %lu\n", + static_cast(error) + ); + return false; + } +#else + std::FILE *file = std::fopen(temporary.c_str(), "wb"); + if (file == nullptr) return false; + bool success = (bytes.empty() || + std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size()) && + std::fflush(file) == 0; + if (success) success = fsync(fileno(file)) == 0; + if (std::fclose(file) != 0) success = false; + if (!success) { + std::error_code ignored; + std::filesystem::remove(temporary, ignored); + return false; + } + if (std::rename(temporary.c_str(), data_path.c_str()) != 0) { + std::remove(temporary.c_str()); + return false; + } + int directory_fd = open(data_path.parent_path().c_str(), O_RDONLY); + if (directory_fd >= 0) { + fsync(directory_fd); + close(directory_fd); + } +#endif + return true; +} + +} + +CudaCalibrationCache::CudaCalibrationCache(std::string key) : key_(std::move(key)) { + if (key_.empty() || key_.size() > MAX_KEY_BYTES) return; + const std::filesystem::path directory = cache_directory(); + if (directory.empty()) return; + std::error_code error; + std::filesystem::create_directories(directory, error); + if (error) return; + data_path_ = directory / "cuda-calibration-v1.bin"; + std::filesystem::path lock_path = data_path_; + lock_path += ".lock"; +#ifdef _WIN32 + HANDLE handle = INVALID_HANDLE_VALUE; + while (handle == INVALID_HANDLE_VALUE) { + handle = CreateFileW( + lock_path.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + nullptr, + OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + nullptr + ); + if (handle != INVALID_HANDLE_VALUE) break; + const DWORD error = GetLastError(); + if (error != ERROR_SHARING_VIOLATION && error != ERROR_LOCK_VIOLATION) return; + Sleep(50); + } + lock_handle_ = handle; +#else + int flags = O_CREAT | O_RDWR; +#ifdef O_CLOEXEC + flags |= O_CLOEXEC; +#endif + lock_fd_ = open(lock_path.c_str(), flags, 0600); + if (lock_fd_ < 0) return; + while (flock(lock_fd_, LOCK_EX) != 0) { + if (errno == EINTR) continue; + close(lock_fd_); + lock_fd_ = -1; + return; + } +#endif + locked_ = true; +} + +CudaCalibrationCache::~CudaCalibrationCache() { + if (!locked_) return; +#ifdef _WIN32 + CloseHandle(static_cast(lock_handle_)); +#else + flock(lock_fd_, LOCK_UN); + close(lock_fd_); +#endif +} + +bool CudaCalibrationCache::load(CudaCalibrationProfile &profile) const { + if (!locked_ || data_path_.empty()) return false; + std::ifstream input(data_path_, std::ios::binary | std::ios::ate); + if (!input) return false; + const std::streamoff size = input.tellg(); + if (size <= 0 || static_cast(size) > MAX_CACHE_BYTES) return false; + std::vector bytes(static_cast(size)); + input.seekg(0, std::ios::beg); + if (!input.read( + reinterpret_cast(bytes.data()), + static_cast(size) + )) return false; + return decode(bytes, key_, profile); +} + +void CudaCalibrationCache::store(const CudaCalibrationProfile &profile) const { + if (!locked_ || data_path_.empty() || !profile.completed) return; + const std::vector bytes = encode(key_, profile); + write_atomically(data_path_, bytes); +} + +} diff --git a/src/main/cpp/runtime/cuda_calibration_cache.h b/src/main/cpp/runtime/cuda_calibration_cache.h new file mode 100644 index 0000000..027bd27 --- /dev/null +++ b/src/main/cpp/runtime/cuda_calibration_cache.h @@ -0,0 +1,35 @@ +#ifndef BIGMATH_CUDA_CALIBRATION_CACHE_H +#define BIGMATH_CUDA_CALIBRATION_CACHE_H + +#include "cuda_calibration.h" + +#include +#include + +namespace bigmath::runtime { + +class CudaCalibrationCache final { +public: + explicit CudaCalibrationCache(std::string key); + ~CudaCalibrationCache(); + + CudaCalibrationCache(const CudaCalibrationCache &) = delete; + CudaCalibrationCache &operator=(const CudaCalibrationCache &) = delete; + + bool load(CudaCalibrationProfile &profile) const; + void store(const CudaCalibrationProfile &profile) const; + +private: + std::string key_; + std::filesystem::path data_path_; +#ifdef _WIN32 + void *lock_handle_ = nullptr; +#else + int lock_fd_ = -1; +#endif + bool locked_ = false; +}; + +} + +#endif diff --git a/src/main/cpp/runtime/cuda_workspace_budget.cpp b/src/main/cpp/runtime/cuda_workspace_budget.cpp new file mode 100644 index 0000000..a35177f --- /dev/null +++ b/src/main/cpp/runtime/cuda_workspace_budget.cpp @@ -0,0 +1,58 @@ +#include "cuda_workspace_budget.h" + +#include +#include + +namespace bigmath::runtime { +namespace { + +struct DeviceBudget { + uint64_t budget = 0; + uint64_t allocated = 0; +}; + +std::mutex budget_mutex; +std::unordered_map device_budgets; + +} + +bool configure_cuda_workspace_budget(int device, uint64_t budget_bytes) { + if (device < 0) return false; + std::lock_guard lock(budget_mutex); + DeviceBudget &budget = device_budgets[device]; + if (budget.allocated != 0) return false; + budget.budget = budget_bytes; + return true; +} + +bool reserve_cuda_workspace_bytes(int device, uint64_t bytes) { + std::lock_guard lock(budget_mutex); + auto iterator = device_budgets.find(device); + if (iterator == device_budgets.end()) return false; + DeviceBudget &budget = iterator->second; + if (bytes > budget.budget || budget.allocated > budget.budget - bytes) return false; + budget.allocated += bytes; + return true; +} + +void release_cuda_workspace_bytes(int device, uint64_t bytes) { + std::lock_guard lock(budget_mutex); + auto iterator = device_budgets.find(device); + if (iterator == device_budgets.end()) return; + DeviceBudget &budget = iterator->second; + budget.allocated = bytes >= budget.allocated ? 0 : budget.allocated - bytes; +} + +uint64_t cuda_workspace_budget_bytes(int device) { + std::lock_guard lock(budget_mutex); + auto iterator = device_budgets.find(device); + return iterator == device_budgets.end() ? 0 : iterator->second.budget; +} + +uint64_t cuda_workspace_allocated_bytes(int device) { + std::lock_guard lock(budget_mutex); + auto iterator = device_budgets.find(device); + return iterator == device_budgets.end() ? 0 : iterator->second.allocated; +} + +} diff --git a/src/main/cpp/runtime/cuda_workspace_budget.h b/src/main/cpp/runtime/cuda_workspace_budget.h new file mode 100644 index 0000000..3179848 --- /dev/null +++ b/src/main/cpp/runtime/cuda_workspace_budget.h @@ -0,0 +1,16 @@ +#ifndef BIGMATH_CUDA_WORKSPACE_BUDGET_H +#define BIGMATH_CUDA_WORKSPACE_BUDGET_H + +#include + +namespace bigmath::runtime { + +bool configure_cuda_workspace_budget(int device, uint64_t budget_bytes); +bool reserve_cuda_workspace_bytes(int device, uint64_t bytes); +void release_cuda_workspace_bytes(int device, uint64_t bytes); +uint64_t cuda_workspace_budget_bytes(int device); +uint64_t cuda_workspace_allocated_bytes(int device); + +} + +#endif diff --git a/src/main/java/com/modularmc/bigmath/BigmathFFM.java b/src/main/java/com/modularmc/bigmath/BigmathFFM.java index f211d49..827b29b 100644 --- a/src/main/java/com/modularmc/bigmath/BigmathFFM.java +++ b/src/main/java/com/modularmc/bigmath/BigmathFFM.java @@ -6,6 +6,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.FileSystemAlreadyExistsException; import java.nio.file.FileSystems; @@ -86,8 +87,35 @@ public final class BigmathFFM { final MethodHandle cudaDeviceNameHandle; final MethodHandle cudaStatusMessageHandle; static final String NATIVE_RESOURCE_ROOT = "native"; + static final MemoryLayout RUNTIME_SNAPSHOT_LAYOUT = MemoryLayout.structLayout( + MemoryLayout.sequenceLayout(4, ValueLayout.JAVA_LONG).withName("threshold_bits"), + ValueLayout.JAVA_LONG.withName("square_threshold_bits"), + ValueLayout.JAVA_LONG.withName("workspace_budget_bytes"), + ValueLayout.JAVA_LONG.withName("workspace_in_use_bytes"), + ValueLayout.JAVA_LONG.withName("cpu_fallback_count"), + ValueLayout.JAVA_LONG.withName("product_cache_hits"), + ValueLayout.JAVA_LONG.withName("product_cache_misses"), + ValueLayout.JAVA_LONG.withName("product_cache_admissions"), + ValueLayout.JAVA_LONG.withName("product_cache_evictions"), + ValueLayout.JAVA_LONG.withName("product_cache_bytes"), + ValueLayout.JAVA_INT.withName("schema_version"), + ValueLayout.JAVA_INT.withName("calibration_status"), + ValueLayout.JAVA_INT.withName("active_backend"), + ValueLayout.JAVA_INT.withName("configured_backend"), + ValueLayout.JAVA_INT.withName("cuda_available"), + ValueLayout.JAVA_INT.withName("device_count"), + ValueLayout.JAVA_INT.withName("selected_device"), + ValueLayout.JAVA_INT.withName("ntt_enabled"), + ValueLayout.JAVA_INT.withName("ntt_transform_mask"), + ValueLayout.JAVA_INT.withName("workspace_capacity"), + ValueLayout.JAVA_INT.withName("workspace_in_use"), + ValueLayout.JAVA_INT.withName("probe_count"), + MemoryLayout.sequenceLayout(256, ValueLayout.JAVA_BYTE).withName("device_name"), + MemoryLayout.sequenceLayout(512, ValueLayout.JAVA_BYTE).withName("status_message") + ); BigmathFFM() { + RuntimeOptions runtimeOptions = BigmathRuntime.beginNativeInitialization(); this.lookup = loadLibrary(); MethodHandle abiVersionHandle = requiredMetadataDowncall( "bigmath_abi_version", @@ -110,6 +138,7 @@ public final class BigmathFFM { } this.nativeBuildId = invokeMetadataString(buildIdHandle); this.nativeCapabilities = invokeMetadataLong(capabilitiesHandle); + configureRuntime(runtimeOptions); this.productCacheHitsHandle = optionalDowncall( "bigmath_product_cache_hits", FunctionDescriptors.PRODUCT_CACHE_LONG @@ -136,6 +165,7 @@ public final class BigmathFFM { this.cudaMultiplyCountHandle = optionalDowncall("bigmath_cuda_multiply_count", FunctionDescriptors.CUDA_INT); this.cudaDeviceNameHandle = optionalDowncall("bigmath_cuda_device_name", FunctionDescriptors.CUDA_STRING); this.cudaStatusMessageHandle = optionalDowncall("bigmath_cuda_status_message", FunctionDescriptors.CUDA_STRING); + initializeRuntime(); } record DowncallKey(String name, FunctionDescriptor descriptor) {} @@ -182,6 +212,43 @@ String invokeMetadataString(MethodHandle handle) { } } + void configureRuntime(RuntimeOptions options) { + MethodHandle handle = downcall("bigmath_runtime_configure", FunctionDescriptors.RUNTIME_CONFIGURE); + long calibrationMillis = options.calibrationDuration().toMillis(); + try { + int status = (int) handle.invokeExact( + options.productCacheEnabled() ? 1 : 0, + options.cpuProductCacheBytes(), + options.gpuWorkspaceFraction(), + options.gpuWorkspaceMaxBytes(), + calibrationMillis, + options.cudaDevice(), + options.cudaBackend().ordinal() + ); + if (status != 0) { + throw new IllegalStateException("Native runtime configuration was rejected with status " + status); + } + } catch (RuntimeException | Error e) { + throw e; + } catch (Throwable t) { + throw new LinkageError("Failed to configure the Bigmath Native runtime", t); + } + } + + void initializeRuntime() { + MethodHandle handle = downcall("bigmath_runtime_initialize", FunctionDescriptors.RUNTIME_INT); + try { + int status = (int) handle.invokeExact(); + if (status != 0) { + throw new IllegalStateException("Native runtime initialization failed with status " + status); + } + } catch (RuntimeException | Error e) { + throw e; + } catch (Throwable t) { + throw new LinkageError("Failed to initialize the Bigmath Native runtime", t); + } + } + static boolean hasCapability(long capability) { return (getInstance().nativeCapabilities & capability) != 0; } @@ -505,6 +572,91 @@ public MethodHandle downcall(String name, FunctionDescriptor descriptor) { ); } + RuntimeDiagnostics runtimeDiagnostics() { + try (Arena snapshotArena = Arena.ofConfined()) { + MemorySegment snapshot = snapshotArena.allocate(RUNTIME_SNAPSHOT_LAYOUT); + invokeRuntimeSnapshot(snapshot); + int schemaVersion = snapshotInt(snapshot, "schema_version"); + if (schemaVersion != 1) { + throw new IllegalStateException("Unsupported Native runtime snapshot schema " + schemaVersion); + } + long thresholdOffset = RUNTIME_SNAPSHOT_LAYOUT.byteOffset( + MemoryLayout.PathElement.groupElement("threshold_bits") + ); + RuntimeDiagnostics.DispatchThresholds thresholds = + new RuntimeDiagnostics.DispatchThresholds( + snapshot.get(ValueLayout.JAVA_LONG, thresholdOffset), + snapshot.get(ValueLayout.JAVA_LONG, thresholdOffset + Long.BYTES), + snapshot.get(ValueLayout.JAVA_LONG, thresholdOffset + 2L * Long.BYTES), + snapshot.get(ValueLayout.JAVA_LONG, thresholdOffset + 3L * Long.BYTES), + snapshotLong(snapshot, "square_threshold_bits") + ); + RuntimeDiagnostics.CudaDiagnostics cuda = new RuntimeDiagnostics.CudaDiagnostics( + snapshotInt(snapshot, "device_count"), + snapshotInt(snapshot, "selected_device"), + snapshotText(snapshot, "device_name", 256), + snapshotText(snapshot, "status_message", 512), + RuntimeDiagnostics.CalibrationStatus.fromNative( + snapshotInt(snapshot, "calibration_status") + ), + RuntimeOptions.CudaBackend.fromNative(snapshotInt(snapshot, "active_backend")), + snapshotInt(snapshot, "ntt_enabled") != 0, + snapshotInt(snapshot, "ntt_transform_mask"), + thresholds, + snapshotLong(snapshot, "workspace_budget_bytes"), + snapshotLong(snapshot, "workspace_in_use_bytes"), + snapshotInt(snapshot, "workspace_capacity"), + snapshotInt(snapshot, "workspace_in_use") + ); + RuntimeDiagnostics.ProductCacheDiagnostics productCache = + new RuntimeDiagnostics.ProductCacheDiagnostics( + snapshotLong(snapshot, "product_cache_hits"), + snapshotLong(snapshot, "product_cache_misses"), + snapshotLong(snapshot, "product_cache_admissions"), + snapshotLong(snapshot, "product_cache_evictions"), + snapshotLong(snapshot, "product_cache_bytes") + ); + return new RuntimeDiagnostics( + nativeAbiVersion, + nativeBuildId, + nativeCapabilities, + cuda, + productCache, + snapshotLong(snapshot, "cpu_fallback_count") + ); + } + } + + void invokeRuntimeSnapshot(MemorySegment snapshot) { + MethodHandle handle = downcall("bigmath_runtime_snapshot", FunctionDescriptors.RUNTIME_SNAPSHOT); + try { + int status = (int) handle.invokeExact(snapshot); + if (status != 0) throw new IllegalStateException("Native runtime snapshot failed with status " + status); + } catch (RuntimeException | Error e) { + throw e; + } catch (Throwable t) { + throw new IllegalStateException("Failed to query the Native runtime snapshot", t); + } + } + + static int snapshotInt(MemorySegment snapshot, String name) { + long offset = RUNTIME_SNAPSHOT_LAYOUT.byteOffset(MemoryLayout.PathElement.groupElement(name)); + return snapshot.get(ValueLayout.JAVA_INT, offset); + } + + static long snapshotLong(MemorySegment snapshot, String name) { + long offset = RUNTIME_SNAPSHOT_LAYOUT.byteOffset(MemoryLayout.PathElement.groupElement(name)); + return snapshot.get(ValueLayout.JAVA_LONG, offset); + } + + static String snapshotText(MemorySegment snapshot, String name, int capacity) { + long offset = RUNTIME_SNAPSHOT_LAYOUT.byteOffset(MemoryLayout.PathElement.groupElement(name)); + byte[] bytes = snapshot.asSlice(offset, capacity).toArray(ValueLayout.JAVA_BYTE); + int length = 0; + while (length < bytes.length && bytes[length] != 0) length++; + return new String(bytes, 0, length, StandardCharsets.UTF_8); + } + static long productCacheHits() { return getInstance().invokeOptionalLong(getInstance().productCacheHitsHandle); } diff --git a/src/main/java/com/modularmc/bigmath/BigmathRuntime.java b/src/main/java/com/modularmc/bigmath/BigmathRuntime.java new file mode 100644 index 0000000..ba34bd8 --- /dev/null +++ b/src/main/java/com/modularmc/bigmath/BigmathRuntime.java @@ -0,0 +1,61 @@ +package com.modularmc.bigmath; + +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +/** Process-wide configuration and diagnostics entry point for the Bigmath Native runtime. */ +@NullMarked +public final class BigmathRuntime { + + private static final Object LOCK = new Object(); + private static RuntimeOptions options = RuntimeOptions.builder().build(); + private static boolean initializationStarted; + private static @Nullable CompletableFuture initialization; + + private BigmathRuntime() { + } + + /** + * Replaces the runtime options used by the first Native initialization. + * + * @throws IllegalStateException if Native initialization has already started + */ + public static void configure(RuntimeOptions configuredOptions) { + Objects.requireNonNull(configuredOptions, "configuredOptions"); + synchronized (LOCK) { + if (initializationStarted) { + throw new IllegalStateException("Bigmath Native runtime initialization has already started"); + } + options = configuredOptions; + } + } + + /** Starts Native initialization on the common asynchronous executor. Calls are idempotent. */ + public static CompletableFuture initializeAsync() { + synchronized (LOCK) { + if (initialization == null) { + initializationStarted = true; + initialization = CompletableFuture.supplyAsync(() -> { + BigmathFFM.getInstance(); + return diagnostics(); + }); + } + return initialization; + } + } + + /** Returns a current read-only snapshot, initializing the Native runtime if necessary. */ + public static RuntimeDiagnostics diagnostics() { + return BigmathFFM.getInstance().runtimeDiagnostics(); + } + + static RuntimeOptions beginNativeInitialization() { + synchronized (LOCK) { + initializationStarted = true; + return options; + } + } +} diff --git a/src/main/java/com/modularmc/bigmath/FunctionDescriptors.java b/src/main/java/com/modularmc/bigmath/FunctionDescriptors.java index 825274f..152c53e 100644 --- a/src/main/java/com/modularmc/bigmath/FunctionDescriptors.java +++ b/src/main/java/com/modularmc/bigmath/FunctionDescriptors.java @@ -206,6 +206,24 @@ final class FunctionDescriptors { ValueLayout.JAVA_LONG ); + /** Runtime configuration scalar entry point. */ + static final FunctionDescriptor RUNTIME_CONFIGURE = FunctionDescriptor.of( + ValueLayout.JAVA_INT, + ValueLayout.JAVA_INT, + ValueLayout.JAVA_LONG, + ValueLayout.JAVA_DOUBLE, + ValueLayout.JAVA_LONG, + ValueLayout.JAVA_LONG, + ValueLayout.JAVA_INT, + ValueLayout.JAVA_INT + ); + + static final FunctionDescriptor RUNTIME_INT = FunctionDescriptor.of(ValueLayout.JAVA_INT); + static final FunctionDescriptor RUNTIME_SNAPSHOT = FunctionDescriptor.of( + ValueLayout.JAVA_INT, + ValueLayout.ADDRESS + ); + // --- BigDeci --- /** {@code void bigdecimal_from_double(void** out, double value, int precision)} */ diff --git a/src/main/java/com/modularmc/bigmath/RuntimeDiagnostics.java b/src/main/java/com/modularmc/bigmath/RuntimeDiagnostics.java new file mode 100644 index 0000000..97f2ab1 --- /dev/null +++ b/src/main/java/com/modularmc/bigmath/RuntimeDiagnostics.java @@ -0,0 +1,77 @@ +package com.modularmc.bigmath; + +import org.jspecify.annotations.NullMarked; + +import java.util.Objects; + +/** Immutable snapshot of Native runtime state. No user numeric values are recorded. */ +@NullMarked +public record RuntimeDiagnostics( + int nativeAbiVersion, + String nativeBuildId, + long nativeCapabilities, + CudaDiagnostics cuda, + ProductCacheDiagnostics productCache, + long cpuFallbackCount +) { + + public RuntimeDiagnostics { + Objects.requireNonNull(nativeBuildId, "nativeBuildId"); + Objects.requireNonNull(cuda, "cuda"); + Objects.requireNonNull(productCache, "productCache"); + } + + public enum CalibrationStatus { + NOT_STARTED, + RUNNING, + READY, + FAILED, + UNAVAILABLE; + + static CalibrationStatus fromNative(int value) { + return value >= 0 && value < values().length ? values()[value] : FAILED; + } + } + + public record CudaDiagnostics( + int deviceCount, + int selectedDevice, + String deviceName, + String statusMessage, + CalibrationStatus calibrationStatus, + RuntimeOptions.CudaBackend activeBackend, + boolean nttEnabled, + int nttTransformMask, + DispatchThresholds thresholds, + long workspaceBudgetBytes, + long workspaceInUseBytes, + int workspaceCapacity, + int workspaceInUse + ) { + public CudaDiagnostics { + Objects.requireNonNull(deviceName, "deviceName"); + Objects.requireNonNull(statusMessage, "statusMessage"); + Objects.requireNonNull(calibrationStatus, "calibrationStatus"); + Objects.requireNonNull(activeBackend, "activeBackend"); + Objects.requireNonNull(thresholds, "thresholds"); + } + } + + public record DispatchThresholds( + long balancedBits, + long ratio2Bits, + long ratio8Bits, + long ratio64Bits, + long squareBits + ) { + } + + public record ProductCacheDiagnostics( + long hits, + long misses, + long admissions, + long evictions, + long bytes + ) { + } +} diff --git a/src/main/java/com/modularmc/bigmath/RuntimeOptions.java b/src/main/java/com/modularmc/bigmath/RuntimeOptions.java new file mode 100644 index 0000000..dda5238 --- /dev/null +++ b/src/main/java/com/modularmc/bigmath/RuntimeOptions.java @@ -0,0 +1,163 @@ +package com.modularmc.bigmath; + +import org.jspecify.annotations.NullMarked; + +import java.time.Duration; +import java.util.Objects; + +/** Immutable options captured when the Bigmath Native runtime is initialized. */ +@NullMarked +public final class RuntimeOptions { + + static final int AUTO_DEVICE = -1; + private static final long MEBIBYTE = 1024L * 1024L; + + private final boolean productCacheEnabled; + private final long cpuProductCacheBytes; + private final double gpuWorkspaceFraction; + private final long gpuWorkspaceMaxBytes; + private final Duration calibrationDuration; + private final int cudaDevice; + private final CudaBackend cudaBackend; + + private RuntimeOptions(Builder builder) { + this.productCacheEnabled = builder.productCacheEnabled; + this.cpuProductCacheBytes = builder.cpuProductCacheBytes; + this.gpuWorkspaceFraction = builder.gpuWorkspaceFraction; + this.gpuWorkspaceMaxBytes = builder.gpuWorkspaceMaxBytes; + this.calibrationDuration = builder.calibrationDuration; + this.cudaDevice = builder.cudaDevice; + this.cudaBackend = builder.cudaBackend; + } + + /** @return a builder initialized with the library defaults */ + public static Builder builder() { + return new Builder(); + } + + /** @return whether the host product result cache is enabled */ + public boolean productCacheEnabled() { + return productCacheEnabled; + } + + /** @return maximum retained host product bytes */ + public long cpuProductCacheBytes() { + return cpuProductCacheBytes; + } + + /** @return fraction of free device memory available to the workspace pool */ + public double gpuWorkspaceFraction() { + return gpuWorkspaceFraction; + } + + /** @return absolute upper bound for the device workspace pool */ + public long gpuWorkspaceMaxBytes() { + return gpuWorkspaceMaxBytes; + } + + /** @return background calibration time budget */ + public Duration calibrationDuration() { + return calibrationDuration; + } + + /** @return {@code -1} for automatic selection, otherwise the configured CUDA device */ + public int cudaDevice() { + return cudaDevice; + } + + /** @return the requested CUDA backend policy */ + public CudaBackend cudaBackend() { + return cudaBackend; + } + + /** Runtime backend policy. Explicit CUDA modes are intended for diagnostics and benchmarks. */ + public enum CudaBackend { + AUTO, + CPU, + CUFFT, + NTT; + + static CudaBackend fromNative(int value) { + return value >= 0 && value < values().length ? values()[value] : CPU; + } + } + + /** Builds validated runtime options. The builder is not thread-safe. */ + public static final class Builder { + + private boolean productCacheEnabled = true; + private long cpuProductCacheBytes = 64L * MEBIBYTE; + private double gpuWorkspaceFraction = 0.25; + private long gpuWorkspaceMaxBytes = 512L * MEBIBYTE; + private Duration calibrationDuration = Duration.ofSeconds(10); + private int cudaDevice = AUTO_DEVICE; + private CudaBackend cudaBackend = CudaBackend.AUTO; + + private Builder() { + } + + /** Enables or disables host product result caching. */ + public Builder productCacheEnabled(boolean enabled) { + this.productCacheEnabled = enabled; + return this; + } + + /** Sets the maximum host product result bytes retained by the cache. */ + public Builder cpuProductCacheBytes(long bytes) { + if (bytes < 0) throw new IllegalArgumentException("CPU product cache bytes must be non-negative"); + this.cpuProductCacheBytes = bytes; + return this; + } + + /** Sets the fraction of free device memory available to pooled workspaces. */ + public Builder gpuWorkspaceFraction(double fraction) { + if (!Double.isFinite(fraction) || fraction <= 0.0 || fraction > 1.0) { + throw new IllegalArgumentException("GPU workspace fraction must be in (0, 1]"); + } + this.gpuWorkspaceFraction = fraction; + return this; + } + + /** Sets the absolute device workspace pool limit. */ + public Builder gpuWorkspaceMaxBytes(long bytes) { + if (bytes <= 0) throw new IllegalArgumentException("GPU workspace limit must be positive"); + this.gpuWorkspaceMaxBytes = bytes; + return this; + } + + /** Sets the background calibration time budget. */ + public Builder calibrationDuration(Duration duration) { + Objects.requireNonNull(duration, "duration"); + if (duration.isZero() || duration.isNegative()) { + throw new IllegalArgumentException("Calibration duration must be positive"); + } + duration.toMillis(); + this.calibrationDuration = duration; + return this; + } + + /** Selects the automatically chosen CUDA device. */ + public Builder automaticCudaDevice() { + this.cudaDevice = AUTO_DEVICE; + return this; + } + + /** Selects a concrete zero-based CUDA device. */ + public Builder cudaDevice(int device) { + if (device < 0) throw new IllegalArgumentException("CUDA device index must be non-negative"); + this.cudaDevice = device; + return this; + } + + /** Selects automatic, CPU-only, cuFFT, or NTT dispatch. */ + public Builder cudaBackend(CudaBackend backend) { + this.cudaBackend = Objects.requireNonNull(backend, "backend"); + return this; + } + + /** @return validated immutable runtime options */ + public RuntimeOptions build() { + return new RuntimeOptions(this); + } + } +} diff --git a/src/test/java/com/modularmc/bigmath/BigIntTest.java b/src/test/java/com/modularmc/bigmath/BigIntTest.java index 4f26f9e..481acd0 100644 --- a/src/test/java/com/modularmc/bigmath/BigIntTest.java +++ b/src/test/java/com/modularmc/bigmath/BigIntTest.java @@ -5,6 +5,7 @@ import java.math.BigInteger; import java.util.Random; +import java.util.concurrent.CompletableFuture; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -492,86 +493,96 @@ void randomMultiplicationAliasesMatchBigInteger() { } @Test - void cudaStatusIsCachedAndQueryable() { - int firstProbeCount = BigmathFFM.cudaProbeCount(); - String firstStatus = BigmathFFM.cudaStatusMessage(); - String secondStatus = BigmathFFM.cudaStatusMessage(); - int secondProbeCount = BigmathFFM.cudaProbeCount(); - assertNotNull(firstStatus); - assertEquals(firstStatus, secondStatus); - assertEquals(1, firstProbeCount); - assertEquals(firstProbeCount, secondProbeCount); - assertEquals(BigmathFFM.cudaDeviceCount(), BigmathFFM.cudaDeviceCount()); - if (BigmathFFM.cudaAvailable()) { - assertTrue(BigmathFFM.cudaDeviceCount() > 0); - assertFalse(BigmathFFM.cudaDeviceName().isBlank()); - } else { - assertFalse(firstStatus.isBlank()); - } + void runtimeDiagnosticsAndInitializationArePubliclyQueryable() { + CompletableFuture initialization = BigmathRuntime.initializeAsync(); + assertSame(initialization, BigmathRuntime.initializeAsync()); + RuntimeDiagnostics diagnostics = initialization.join(); + assertTrue(diagnostics.nativeAbiVersion() > 0); + assertFalse(diagnostics.nativeBuildId().isBlank()); + assertTrue(diagnostics.cuda().deviceCount() >= 0); + assertFalse(diagnostics.cuda().statusMessage().isBlank()); + assertTrue(diagnostics.cuda().workspaceBudgetBytes() >= 0); + assertTrue(diagnostics.cuda().workspaceInUseBytes() >= 0); + assertTrue(diagnostics.productCache().bytes() >= 0); + assertThrows( + IllegalStateException.class, + () -> BigmathRuntime.configure(RuntimeOptions.builder().build()) + ); } @Test void cudaUnavailableFallsBackToCpuMultiplication() { - assumeTrue(!BigmathFFM.cudaAvailable(), BigmathFFM.cudaStatusMessage()); + RuntimeDiagnostics before = BigmathRuntime.diagnostics(); + assumeTrue( + before.cuda().calibrationStatus() == RuntimeDiagnostics.CalibrationStatus.UNAVAILABLE, + before.cuda().statusMessage() + ); String left = repeatDigits("3141592653", 40000); String right = repeatDigits("2718281828", 40000); BigInteger expected = new BigInteger(left).multiply(new BigInteger(right)); - int before = BigmathFFM.cudaMultiplyCount(); try (BigInt a = BigInt.fromString(left, 10); BigInt b = BigInt.fromString(right, 10); BigInt c = a.multiply(b)) { assertEquals(expected.toString(), c.toString()); } - assertEquals(before, BigmathFFM.cudaMultiplyCount()); + assertEquals(RuntimeOptions.CudaBackend.CPU, BigmathRuntime.diagnostics().cuda().activeBackend()); } @Test @EnabledIfSystemProperty(named = "bigmath.cuda.tests", matches = "true") void cudaLargeMultiplicationMatchesBigIntegerWhenEnabled() { - assumeTrue(BigmathFFM.cudaAvailable(), BigmathFFM.cudaStatusMessage()); + RuntimeDiagnostics diagnostics = BigmathRuntime.initializeAsync().join(); + assumeTrue( + diagnostics.cuda().calibrationStatus() == RuntimeDiagnostics.CalibrationStatus.READY, + diagnostics.cuda().statusMessage() + ); String left = repeatDigits("1234567890", 80000); String right = repeatDigits("9876543210", 80000); BigInteger expected = new BigInteger(left).multiply(new BigInteger(right)); - int before = BigmathFFM.cudaMultiplyCount(); try (BigInt a = BigInt.fromString(left, 10); BigInt b = BigInt.fromString(right, 10); BigInt c = a.multiply(b)) { assertEquals(expected.toString(), c.toString()); } - assertTrue(BigmathFFM.cudaMultiplyCount() > before, BigmathFFM.cudaStatusMessage()); } @Test @EnabledIfSystemProperty(named = "bigmath.cuda.tests", matches = "true") void cudaProductCacheDoesNotReuseMutatedOperands() { - assumeTrue(BigmathFFM.cudaAvailable(), BigmathFFM.cudaStatusMessage()); + RuntimeDiagnostics diagnostics = BigmathRuntime.initializeAsync().join(); + assumeTrue( + diagnostics.cuda().calibrationStatus() == RuntimeDiagnostics.CalibrationStatus.READY, + diagnostics.cuda().statusMessage() + ); String left = repeatDigits("1234567890", 80000); String changedLeft = repeatDigits("2234567890", 80000); String right = repeatDigits("9876543210", 80000); BigInteger expected = new BigInteger(left).multiply(new BigInteger(right)); BigInteger changedExpected = new BigInteger(changedLeft).multiply(new BigInteger(right)); - int before = BigmathFFM.cudaMultiplyCount(); + RuntimeDiagnostics.ProductCacheDiagnostics before = diagnostics.productCache(); try (BigInt a = BigInt.fromString(left, 10); BigInt b = BigInt.fromString(right, 10)) { try (BigInt first = a.multiply(b)) { assertEquals(expected.toString(), first.toString()); } - int afterFirst = BigmathFFM.cudaMultiplyCount(); - assertTrue(afterFirst > before, BigmathFFM.cudaStatusMessage()); + RuntimeDiagnostics.ProductCacheDiagnostics afterFirst = BigmathRuntime.diagnostics().productCache(); + assertTrue(afterFirst.misses() > before.misses()); try (BigInt admitted = a.multiply(b)) { assertEquals(expected.toString(), admitted.toString()); } - int afterAdmission = BigmathFFM.cudaMultiplyCount(); - assertTrue(afterAdmission > afterFirst, BigmathFFM.cudaStatusMessage()); + RuntimeDiagnostics.ProductCacheDiagnostics afterAdmission = + BigmathRuntime.diagnostics().productCache(); + assertTrue(afterAdmission.admissions() > afterFirst.admissions()); try (BigInt cached = a.multiply(b)) { assertEquals(expected.toString(), cached.toString()); } - assertEquals(afterAdmission, BigmathFFM.cudaMultiplyCount()); + RuntimeDiagnostics.ProductCacheDiagnostics afterHit = BigmathRuntime.diagnostics().productCache(); + assertTrue(afterHit.hits() > afterAdmission.hits()); a.set(changedLeft, 10); try (BigInt changed = a.multiply(b)) { assertEquals(changedExpected.toString(), changed.toString()); } - assertTrue(BigmathFFM.cudaMultiplyCount() > afterAdmission, BigmathFFM.cudaStatusMessage()); + assertTrue(BigmathRuntime.diagnostics().productCache().misses() > afterHit.misses()); } }