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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions .github/workflows/native-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions gradle/scripts/resources.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
55 changes: 25 additions & 30 deletions scripts/cuda-bench.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 <run-id> # 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/<classifier>/ 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).
Expand All @@ -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"
Expand All @@ -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
48 changes: 28 additions & 20 deletions src/jmh/java/com/modularmc/bigmath/CudaCheck.java
Original file line number Diff line number Diff line change
@@ -1,51 +1,59 @@
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.
* <p>
* 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.
* <p>
* Run via {@code scripts/cuda-bench.sh} (which stages a CUDA-enabled native lib),
* or manually:
* <pre>
* 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]
* </pre>
*/
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;
}
Loading
Loading