diff --git a/.github/workflows/native-build.yml b/.github/workflows/native-build.yml index 5686c45..f03336e 100644 --- a/.github/workflows/native-build.yml +++ b/.github/workflows/native-build.yml @@ -95,10 +95,53 @@ jobs: "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 + - name: Restore Windows CUDA toolkit cache + if: matrix.platform == 'windows' + id: cuda-cache + uses: actions/cache/restore@v4 + with: + path: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.2 + key: cuda-toolkit-${{ matrix.classifier }}-13.2.0-jimver-v0.2.35-v1 + + - name: Check Windows CUDA toolkit cache + if: matrix.platform == 'windows' + id: cuda-cache-check + shell: pwsh + run: | + $nvcc = 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.2\bin\nvcc.exe' + $available = Test-Path -LiteralPath $nvcc -PathType Leaf + "available=$($available.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT + + - name: Install Linux CUDA toolkit + if: matrix.platform == 'linux' uses: Jimver/cuda-toolkit@v0.2.35 with: cuda: '13.2.0' + method: network + sub-packages: '["compiler", "cudart", "cudart-dev"]' + non-cuda-sub-packages: '["libcufft", "libcufft-dev"]' + + - name: Install Windows CUDA toolkit + if: matrix.platform == 'windows' && steps.cuda-cache-check.outputs.available != 'true' + uses: Jimver/cuda-toolkit@v0.2.35 + with: + cuda: '13.2.0' + + - name: Configure CUDA toolkit environment + shell: pwsh + run: | + if ('${{ matrix.platform }}' -eq 'windows') { + $cudaPath = 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.2' + "CUDA_PATH=$cudaPath" >> $env:GITHUB_ENV + "CUDA_PATH_V13_2=$cudaPath" >> $env:GITHUB_ENV + "$cudaPath\bin" >> $env:GITHUB_PATH + } else { + $cudaPath = '/usr/local/cuda-13.2' + "CUDA_PATH=$cudaPath" >> $env:GITHUB_ENV + "CUDA_PATH_V13_2=$cudaPath" >> $env:GITHUB_ENV + "LD_LIBRARY_PATH=$cudaPath/lib64:${env:LD_LIBRARY_PATH}" >> $env:GITHUB_ENV + "$cudaPath/bin" >> $env:GITHUB_PATH + } - uses: actions/setup-java@v4 with: @@ -134,6 +177,13 @@ jobs: path: .vcpkg-cache key: ${{ steps.vcpkg-cache.outputs.cache-primary-key }} + - name: Save Windows CUDA toolkit cache + if: matrix.platform == 'windows' && steps.cuda-cache-check.outputs.available != 'true' && !cancelled() + uses: actions/cache/save@v4 + with: + path: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.2 + key: ${{ steps.cuda-cache.outputs.cache-primary-key }} + - name: Upload CUDA Native artifact uses: actions/upload-artifact@v4 with: diff --git a/src/jmh/java/com/modularmc/bigmath/BigDeciBenchmark.java b/src/jmh/java/com/modularmc/bigmath/BigDeciBenchmark.java index 55a3ea7..117d5fe 100644 --- a/src/jmh/java/com/modularmc/bigmath/BigDeciBenchmark.java +++ b/src/jmh/java/com/modularmc/bigmath/BigDeciBenchmark.java @@ -24,6 +24,7 @@ @Fork(1) public class BigDeciBenchmark { private static final BigNumberFormat GROUPED_FORMAT = BigNumberFormat.ofPattern("#,##0.################"); + private static final int MULTIPLY_PAIRS = 32; @State(Scope.Thread) public static class PrecisionState { @@ -94,6 +95,58 @@ public void tearDown() { } } + @State(Scope.Thread) + public static class HighPrecisionMultiplyState { + @Param({"131072", "196608", "262144", "393216", "524288", "1048576"}) + public int precision; + + BigDeci[] left; + BigDeci[] alternateLeft; + BigDeci[] right; + BigDeci result; + int pair; + int selectedPair; + + @Setup(Level.Trial) + public void setup() { + int digits = (int) (precision * 0.30103) - 8; + left = new BigDeci[MULTIPLY_PAIRS]; + alternateLeft = new BigDeci[MULTIPLY_PAIRS]; + right = new BigDeci[MULTIPLY_PAIRS]; + for (int index = 0; index < MULTIPLY_PAIRS; index++) { + String suffix = Integer.toString(10 + index); + String leftDigits = repeatDigits("1234567890", digits - suffix.length()) + suffix; + String alternateDigits = repeatDigits("2234567890", digits - suffix.length()) + suffix; + String rightDigits = repeatDigits("9876543210", digits - suffix.length()) + suffix; + try (BigInt leftInteger = BigInt.fromString(leftDigits, 10); + BigInt alternateInteger = BigInt.fromString(alternateDigits, 10); + BigInt rightInteger = BigInt.fromString(rightDigits, 10)) { + left[index] = BigDeci.fromBigInt(leftInteger, precision); + alternateLeft[index] = BigDeci.fromBigInt(alternateInteger, precision); + right[index] = BigDeci.fromBigInt(rightInteger, precision); + } + } + result = BigDeci.fromDouble(0.0, precision); + } + + @Setup(Level.Invocation) + public void prepareInvocation() { + selectedPair = pair; + pair = (pair + 1) % MULTIPLY_PAIRS; + left[selectedPair].set(alternateLeft[selectedPair]); + } + + @TearDown(Level.Trial) + public void tearDown() { + for (int index = 0; index < MULTIPLY_PAIRS; index++) { + left[index].close(); + alternateLeft[index].close(); + right[index].close(); + } + result.close(); + } + } + @Benchmark public void add(PrecisionState state, Blackhole blackhole) { try (BigDeci result = state.left.add(state.right)) { @@ -123,6 +176,20 @@ public void divideInto(PrecisionState state, Blackhole blackhole) { blackhole.consume(state.result.divideInto(state.left, state.right)); } + @Benchmark + public void highPrecisionMultiply(HighPrecisionMultiplyState state, Blackhole blackhole) { + int pair = state.selectedPair; + try (BigDeci result = state.left[pair].multiply(state.right[pair])) { + blackhole.consume(result); + } + } + + @Benchmark + public void highPrecisionMultiplyInto(HighPrecisionMultiplyState state, Blackhole blackhole) { + int pair = state.selectedPair; + blackhole.consume(state.result.multiplyInto(state.left[pair], state.right[pair])); + } + @Benchmark public void sqrt(PrecisionState state, Blackhole blackhole) { try (BigDeci result = state.left.sqrt()) { diff --git a/src/jmh/java/com/modularmc/bigmath/CudaVerify.java b/src/jmh/java/com/modularmc/bigmath/CudaVerify.java index 7817cd7..f9db768 100644 --- a/src/jmh/java/com/modularmc/bigmath/CudaVerify.java +++ b/src/jmh/java/com/modularmc/bigmath/CudaVerify.java @@ -14,6 +14,7 @@ * compared with public JDK or Bigmath values rather than private Native exports. */ public final class CudaVerify { + private static boolean requireResidentModPow; public static void main(String[] args) { RuntimeOptions.CudaBackend backend = args.length > 0 @@ -24,6 +25,7 @@ public static void main(String[] args) { .productCacheEnabled(false) .build()); RuntimeDiagnostics diagnostics = BigmathRuntime.initializeAsync().join(); + requireResidentModPow = backend == RuntimeOptions.CudaBackend.NTT; if (backend != RuntimeOptions.CudaBackend.CPU && diagnostics.cuda().calibrationStatus() != RuntimeDiagnostics.CalibrationStatus.READY) { throw new IllegalStateException(diagnostics.cuda().statusMessage()); @@ -47,9 +49,9 @@ public static void main(String[] args) { failures += checkBigDeci(precisionBits, random) ? 0 : 1; } - for (int modulusDigits : new int[]{200000, 250000}) { - failures += checkModPow(modulusDigits, random) ? 0 : 1; - } + failures += checkModPow(200000, true, ExponentDensity.LOW, random) ? 0 : 1; + failures += checkModPow(200000, false, ExponentDensity.HIGH, random) ? 0 : 1; + failures += checkModPow(250000, true, ExponentDensity.MEDIUM, random) ? 0 : 1; System.out.printf("%nRESULT: %s%n", failures == 0 ? "ALL PASS" : failures + " FAILED"); if (failures != 0) { @@ -94,10 +96,20 @@ static boolean checkBigDeci(int precisionBits, SplittableRandom random) { } } - static boolean checkModPow(int modulusDigits, SplittableRandom random) { + static boolean checkModPow( + int modulusDigits, + boolean oddModulus, + ExponentDensity density, + 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)); + modulusValue = oddModulus ? modulusValue.setBit(0) : modulusValue.clearBit(0); + BigInteger exponentValue = switch (density) { + case LOW -> BigInteger.ONE.setBit(45).setBit(7); + case MEDIUM -> BigInteger.valueOf(random.nextLong(1L << 45, 1L << 46)); + case HIGH -> BigInteger.ONE.shiftLeft(46).subtract(BigInteger.ONE); + }; BigInteger expected = baseValue.modPow(exponentValue, modulusValue); long fallbackBefore = BigmathRuntime.diagnostics().cpuFallbackCount(); try (BigInt base = BigInt.fromBigInteger(baseValue); @@ -105,13 +117,27 @@ static boolean checkModPow(int modulusDigits, SplittableRandom random) { BigInt modulus = BigInt.fromBigInteger(modulusValue); BigInt result = base.modPow(exponent, modulus)) { long fallbacks = BigmathRuntime.diagnostics().cpuFallbackCount() - fallbackBefore; - boolean matches = expected.equals(result.toBigInteger()); + boolean matches = expected.equals(result.toBigInteger()) && + (!requireResidentModPow || fallbacks == 0); + String caseName = (oddModulus ? "odd" : "even") + density.displayName; System.out.printf("%-9d %-8s %14d %s%n", - modulusDigits, "modPow", fallbacks, matches ? "PASS" : "MISMATCH"); + modulusDigits, caseName, fallbacks, matches ? "PASS" : "MISMATCH"); return matches; } } + enum ExponentDensity { + LOW("Low"), + MEDIUM("Medium"), + HIGH("High"); + + final String displayName; + + ExponentDensity(String displayName) { + this.displayName = displayName; + } + } + static String randDigits(int digits, SplittableRandom random) { StringBuilder result = new StringBuilder(digits); result.append((char) ('1' + random.nextInt(9))); diff --git a/src/main/cpp/CMakeLists.txt b/src/main/cpp/CMakeLists.txt index 7eafd47..5695264 100644 --- a/src/main/cpp/CMakeLists.txt +++ b/src/main/cpp/CMakeLists.txt @@ -203,10 +203,10 @@ target_include_directories(bigmath_ffm PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_compile_definitions(bigmath_ffm PRIVATE BIGMATH_BUILD_ID="${BIGMATH_BUILD_ID}") if(BIGMATH_ENABLE_CUDA AND BIGMATH_CUDA_SUPPORTED_PLATFORM) - target_sources(bigmath_ffm PRIVATE cuda_convolution.cu cuda_ntt.cu) + target_sources(bigmath_ffm PRIVATE cuda_convolution.cu cuda_modular.cu cuda_ntt.cu) target_compile_definitions(bigmath_ffm PRIVATE BIGMATH_HAS_CUDA) target_link_libraries(bigmath_ffm PRIVATE CUDA::cudart CUDA::cufft) - set_source_files_properties(cuda_convolution.cu cuda_ntt.cu PROPERTIES LANGUAGE CUDA) + set_source_files_properties(cuda_convolution.cu cuda_modular.cu cuda_ntt.cu PROPERTIES LANGUAGE CUDA) endif() if(WIN32) diff --git a/src/main/cpp/algos.cpp b/src/main/cpp/algos.cpp index 0b57f9d..b38963a 100644 --- a/src/main/cpp/algos.cpp +++ b/src/main/cpp/algos.cpp @@ -10,6 +10,7 @@ #include #ifdef BIGMATH_HAS_CUDA +#include "cuda_modular.h" #include "cuda_ntt.h" #endif @@ -208,89 +209,134 @@ void fast_pow(mpz_ptr out, mpz_ptr base, uint64_t exp) { mpz_clear(b); } -// ---- Modular Exponentiation (Barrett reduction, GPU multiplies) ---- -// Barrett reducer for a fixed modulus m: maps x in [0, m^2) to x mod m without -// division, using two big multiplies (x*mu and q*m) that route through -// accelerated_mul (GPU above the CUDA threshold). mu = floor(2^(2k)/m) with -// k = bit length of m, precomputed once per modpow call. -namespace { -struct Barrett { - mpz_t m, mu, q, qm; - mp_bitcnt_t k2 = 0; - - void init(mpz_ptr mod) { - mpz_init_set(m, mod); - const mp_bitcnt_t k = mpz_sizeinbase(m, 2); - k2 = 2 * k; - mpz_init2(mu, k2 + 2); - mpz_init(q); - mpz_init(qm); - mpz_setbit(mu, k2); // mu = 2^(2k) - mpz_tdiv_q(mu, mu, m); // mu = floor(2^(2k) / m) - } +static void export_abs_mpz_to_u16_digits( + mpz_ptr value, + mp_bitcnt_t bits, + std::vector &out +); +static void write_u16_digits_to_mpz( + mpz_ptr out, + const std::vector &digits, + unsigned bits_per_digit +); +static cuda::DispatchDecision cuda_dispatch_decision( + uint64_t left_bits, + uint64_t right_bits, + bool square +); - void clear() { - mpz_clear(m); - mpz_clear(mu); - mpz_clear(q); - mpz_clear(qm); - } - - // r = x mod m for 0 <= x < m^2. q = floor(x*mu / 2^(2k)) underestimates the - // quotient by a small bounded amount, so a few conditional subtractions fix r. - void reduce(mpz_ptr r, mpz_ptr x) { - accelerated_mul(q, x, mu); - mpz_tdiv_q_2exp(q, q, k2); // q = (x*mu) >> 2k - accelerated_mul(qm, q, m); - mpz_sub(r, x, qm); // r = x - q*m (>= 0 since q <= x/m) - while (mpz_cmp(r, m) >= 0) { - mpz_sub(r, r, m); +#ifdef BIGMATH_HAS_CUDA +static bool try_resident_modpow(mpz_ptr out, mpz_ptr base, mpz_ptr exp, mpz_ptr modulus) { + const mp_bitcnt_t modulus_bits = mpz_sizeinbase(modulus, 2); + const cuda::DispatchDecision dispatch = cuda_dispatch_decision( + modulus_bits, + modulus_bits, + true + ); + if (dispatch.backend != cuda::RuntimeBackend::NTT) return false; + const size_t modulus_digits = static_cast((modulus_bits + 15) / 16); + if (modulus_digits == 0 || + modulus_digits > static_cast((cuda::NTT_MAX_TRANSFORM_SIZE - 4) / 2)) { + return false; + } + int transform_size = 1; + const size_t required_transform = modulus_digits * 2 + 3; + while (static_cast(transform_size) < required_transform) transform_size <<= 1; + const cuda::ModularOperationCosts costs = + cuda::modular_operation_costs(transform_size); + + mpz_t reduced_base; + mpz_t radix; + mpz_t reduction_constant; + mpz_t identity; + mpz_init(reduced_base); + mpz_init(radix); + mpz_init(reduction_constant); + mpz_init(identity); + mpz_mod(reduced_base, base, modulus); + mpz_setbit(radix, static_cast(modulus_digits * 16)); + + cuda::ResidentReduction reduction = cuda::ResidentReduction::BARRETT; + bool prepared = true; + if (mpz_odd_p(modulus)) { + reduction = cuda::ResidentReduction::MONTGOMERY; + prepared = mpz_invert(reduction_constant, modulus, radix) != 0; + if (prepared) { + mpz_neg(reduction_constant, reduction_constant); + mpz_mod(reduction_constant, reduction_constant, radix); + mpz_mul(reduced_base, reduced_base, radix); + mpz_mod(reduced_base, reduced_base, modulus); + mpz_mod(identity, radix, modulus); } + } else { + mpz_set_ui(reduction_constant, 0); + mpz_setbit( + reduction_constant, + static_cast(modulus_digits * 32) + ); + mpz_tdiv_q(reduction_constant, reduction_constant, modulus); + mpz_set_ui(identity, 1); } -}; + + std::vector base_digits; + std::vector exponent_digits; + std::vector modulus_value; + std::vector constant_digits; + std::vector identity_digits; + std::vector result_digits; + bool completed = false; + if (prepared) { + export_abs_mpz_to_u16_digits( + reduced_base, + mpz_sizeinbase(reduced_base, 2), + base_digits + ); + export_abs_mpz_to_u16_digits(exp, mpz_sizeinbase(exp, 2), exponent_digits); + export_abs_mpz_to_u16_digits(modulus, modulus_bits, modulus_value); + export_abs_mpz_to_u16_digits( + reduction_constant, + mpz_sizeinbase(reduction_constant, 2), + constant_digits + ); + export_abs_mpz_to_u16_digits( + identity, + mpz_sizeinbase(identity, 2), + identity_digits + ); + completed = cuda::resident_modpow_u16( + base_digits, + exponent_digits, + modulus_value, + constant_digits, + identity_digits, + reduction, + costs.multiply_nanos, + costs.square_nanos, + dispatch.max_queue_wait_nanos, + result_digits + ); + } + if (completed) write_u16_digits_to_mpz(out, result_digits, 16); + mpz_clear(reduced_base); + mpz_clear(radix); + mpz_clear(reduction_constant); + mpz_clear(identity); + return completed; } +#endif void modpow(mpz_ptr out, mpz_ptr base, mpz_ptr exp, mpz_ptr mod) { - // GMP handles small/edge cases (and is faster below the GPU threshold). - // Measured crossover on an RTX 3050: GPU Barrett modpow loses at 80k-digit - // moduli (0.77x) but wins from ~150k digits (1.45x at 200k, 1.65x at 400k), - // 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 || - !cuda_dispatch_favorable( - mpz_sizeinbase(mod, 2), - mpz_sizeinbase(mod, 2), - true - )) { + mpz_sizeinbase(mod, 2) < MODPOW_BIT_THRESHOLD) { mpz_powm(out, base, exp, mod); return; } - - Barrett br; - br.init(mod); - mpz_t b, acc, t; - mpz_init(b); - mpz_init(acc); - mpz_init(t); - mpz_mod(b, base, mod); // b = base mod m - mpz_set_ui(acc, 1); - const mp_bitcnt_t bits = mpz_sizeinbase(exp, 2); - for (mp_bitcnt_t i = 0; i < bits; i++) { - if (mpz_tstbit(exp, i)) { - accelerated_mul(t, acc, b); // acc *= b (mod m) - br.reduce(acc, t); - } - if (i + 1 < bits) { - accelerated_mul(t, b, b); // b = b^2 (mod m) - br.reduce(b, t); - } - } - mpz_set(out, acc); - mpz_clear(b); - mpz_clear(acc); - mpz_clear(t); - br.clear(); +#ifdef BIGMATH_HAS_CUDA + if (try_resident_modpow(out, base, exp, mod)) return; + cuda::record_cpu_fallback(); +#endif + mpz_powm(out, base, exp, mod); } // ---- Product Tree Factorial ---- @@ -757,21 +803,26 @@ static void store_product_result( #endif } -static void fft_multiply_impl( +static bool fft_multiply_impl( mpz_ptr out, mpz_ptr a, mpz_ptr b, - const caching::ProductCacheKey *cache_key + const caching::ProductCacheKey *cache_key, + bool cuda_only ) { int alen = mpz_size(a); int blen = mpz_size(b); - if (alen == 0 || blen == 0) { mpz_set_ui(out, 0); return; } + if (alen == 0 || blen == 0) { + mpz_set_ui(out, 0); + return true; + } 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); + if (cuda_only && dispatch.backend == cuda::RuntimeBackend::CPU) return false; caching::ProductCacheKey resolved_cache_key{}; const caching::ProductCacheKey *resolved_cache_key_ptr = nullptr; if (cache_key != nullptr) { @@ -790,7 +841,7 @@ static void fft_multiply_impl( if (lookup.hit) { write_u64_limbs_to_mpz(out, *lookup.packed_limbs); if (a_neg != b_neg) mpz_neg(out, out); - return; + return true; } } #endif @@ -818,13 +869,19 @@ static void fft_multiply_impl( if (clear_abs_a) mpz_clear(abs_a_storage); if (clear_abs_b) mpz_clear(abs_b_storage); if (a_neg != b_neg) mpz_neg(out, out); - return; + return true; } + if (cuda_only) { + if (clear_abs_a) mpz_clear(abs_a_storage); + if (clear_abs_b) mpz_clear(abs_b_storage); + return false; + } mpz_mul(out, a, b); 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); + return true; } void fft_multiply( @@ -833,7 +890,7 @@ void fft_multiply( mpz_ptr b, const caching::ProductCacheKey *cache_key ) { - fft_multiply_impl(out, a, b, cache_key); + fft_multiply_impl(out, a, b, cache_key, false); } void fft_multiply_into( @@ -845,12 +902,29 @@ void fft_multiply_into( if (out == a || out == b) { mpz_t tmp; mpz_init(tmp); - fft_multiply_impl(tmp, a, b, cache_key); + fft_multiply_impl(tmp, a, b, cache_key, false); mpz_set(out, tmp); mpz_clear(tmp); return; } - fft_multiply_impl(out, a, b, cache_key); + fft_multiply_impl(out, a, b, cache_key, false); +} + +bool try_cuda_multiply( + mpz_ptr out, + mpz_ptr a, + mpz_ptr b, + const caching::ProductCacheKey *cache_key +) { + if (out == a || out == b) { + mpz_t temporary; + mpz_init(temporary); + const bool completed = fft_multiply_impl(temporary, a, b, cache_key, true); + if (completed) mpz_set(out, temporary); + mpz_clear(temporary); + return completed; + } + return fft_multiply_impl(out, a, b, cache_key, true); } void accelerated_mul( @@ -876,6 +950,7 @@ 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 try_cuda_multiply(mpz_ptr, mpz_ptr, mpz_ptr, const caching::ProductCacheKey *) { return false; } bool cuda_multiply_direct( mpz_ptr, mpz_ptr, diff --git a/src/main/cpp/algos.h b/src/main/cpp/algos.h index 46573db..7b580cd 100644 --- a/src/main/cpp/algos.h +++ b/src/main/cpp/algos.h @@ -69,6 +69,13 @@ bool cuda_multiply_direct( bool reset_host_cache ); +bool try_cuda_multiply( + mpz_ptr out, + mpz_ptr a, + mpz_ptr b, + const caching::ProductCacheKey *cache_key = nullptr +); + 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); diff --git a/src/main/cpp/bigdecimal.cpp b/src/main/cpp/bigdecimal.cpp index d61d577..fe37d2f 100644 --- a/src/main/cpp/bigdecimal.cpp +++ b/src/main/cpp/bigdecimal.cpp @@ -11,6 +11,38 @@ #ifndef BIGMATH_NO_GMP +#ifdef BIGMATH_HAS_CUDA +namespace { + +struct GpuMpfrMultiplyScratch { + mpz_t left; + mpz_t right; + mpz_t product; + + GpuMpfrMultiplyScratch() { + mpz_init(left); + mpz_init(right); + mpz_init(product); + } + + ~GpuMpfrMultiplyScratch() { + mpz_clear(left); + mpz_clear(right); + mpz_clear(product); + } + + GpuMpfrMultiplyScratch(const GpuMpfrMultiplyScratch &) = delete; + GpuMpfrMultiplyScratch &operator=(const GpuMpfrMultiplyScratch &) = delete; +}; + +GpuMpfrMultiplyScratch &gpu_mpfr_multiply_scratch() { + static thread_local GpuMpfrMultiplyScratch scratch; + return scratch; +} + +} +#endif + // GPU-accelerated MPFR multiply for very high precision. The expensive part of // mpfr_mul is the integer significand product; route that through the GPU bigint // multiply (accelerated_mul) and let MPFR round exactly once via mpfr_set_z_2exp. @@ -44,17 +76,28 @@ static bool gpu_mpfr_mul( )) { return false; } - mpz_t za, zb, zp; - mpz_init(za); - mpz_init(zb); - mpz_init(zp); - const mpfr_exp_t ea = mpfr_get_z_2exp(za, a); // a = za * 2^ea - const mpfr_exp_t eb = mpfr_get_z_2exp(zb, b); // b = zb * 2^eb - bigmath::accelerated_mul(zp, za, zb, cache_key); // exact significand product (GPU) - mpfr_set_z_2exp(out, zp, ea + eb, MPFR_RNDN); // single correct rounding to out's prec - mpz_clear(za); - mpz_clear(zb); - mpz_clear(zp); + GpuMpfrMultiplyScratch &scratch = gpu_mpfr_multiply_scratch(); + const mpfr_exp_t left_exponent = mpfr_get_z_2exp(scratch.left, a); + mpz_ptr right_significand = scratch.left; + mpfr_exp_t right_exponent = left_exponent; + if (a != b) { + right_exponent = mpfr_get_z_2exp(scratch.right, b); + right_significand = scratch.right; + } + if (!bigmath::try_cuda_multiply( + scratch.product, + scratch.left, + right_significand, + cache_key + )) { + return false; + } + mpfr_set_z_2exp( + out, + scratch.product, + left_exponent + right_exponent, + MPFR_RNDN + ); return true; #endif } diff --git a/src/main/cpp/cuda_modular.cu b/src/main/cpp/cuda_modular.cu new file mode 100644 index 0000000..786320c --- /dev/null +++ b/src/main/cpp/cuda_modular.cu @@ -0,0 +1,1279 @@ +#include "cuda_modular.h" + +#include "cuda_ntt_device.cuh" +#include "runtime/cuda_workspace_budget.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace bigmath::cuda { +namespace { + +using namespace ntt_device; + +inline constexpr u64 DIGIT_MASK = UINT64_C(0xffff); +inline constexpr u64 CRT_MODULUS = MOD1 * MOD3; +inline constexpr u64 STATUS_OK = 0; +inline constexpr u64 STATUS_CARRY_OVERFLOW = 1; +inline constexpr u64 STATUS_MONTGOMERY_INVARIANT = 2; +inline constexpr u64 STATUS_REDUCTION_RANGE = 3; +inline constexpr u64 STATUS_WINDOW_RANGE = 4; + +std::atomic resident_buffer_bytes{0}; + +__device__ bool greater_or_equal(const u64 *left, const u64 *right, int digits) { + for (int index = digits - 1; index >= 0; index--) { + if (left[index] != right[index]) return left[index] > right[index]; + } + return true; +} + +__device__ void subtract_digits(u64 *left, const u64 *right, int digits) { + u64 borrow = 0; + for (int index = 0; index < digits; index++) { + const u64 subtrahend = right[index] + borrow; + const u64 value = left[index]; + left[index] = (value - subtrahend) & DIGIT_MASK; + borrow = value < subtrahend ? 1 : 0; + } +} + +static __global__ void normalize_coefficients( + const u64 *coefficients, + u64 *digits, + int coefficient_count, + int digit_capacity, + u64 *status +) { + if (blockIdx.x != 0 || threadIdx.x != 0 || *status != STATUS_OK) return; + for (int index = 0; index < digit_capacity; index++) digits[index] = 0; + u64 carry = 0; + int output = 0; + for (; output < coefficient_count && output < digit_capacity; output++) { + if (~static_cast(0) - coefficients[output] < carry) { + *status = STATUS_CARRY_OVERFLOW; + return; + } + const u64 value = coefficients[output] + carry; + digits[output] = value & DIGIT_MASK; + carry = value >> 16; + } + while (carry != 0 && output < digit_capacity) { + digits[output++] = carry & DIGIT_MASK; + carry >>= 16; + } + if (carry != 0 || coefficient_count > digit_capacity) { + *status = STATUS_CARRY_OVERFLOW; + } +} + +static __global__ void finish_montgomery_reduction( + const u64 *product, + const u64 *multiple, + u64 *result, + const u64 *modulus, + int modulus_digits, + u64 *status +) { + if (blockIdx.x != 0 || threadIdx.x != 0 || *status != STATUS_OK) return; + u64 carry = 0; + for (int index = 0; index <= 2 * modulus_digits; index++) { + const u64 sum = product[index] + multiple[index] + carry; + const u64 digit = sum & DIGIT_MASK; + carry = sum >> 16; + if (index < modulus_digits) { + if (digit != 0) { + *status = STATUS_MONTGOMERY_INVARIANT; + return; + } + } else { + result[index - modulus_digits] = digit; + } + } + if (carry != 0) { + *status = STATUS_CARRY_OVERFLOW; + return; + } + const int result_digits = modulus_digits + 1; + if (greater_or_equal(result, modulus, result_digits)) { + subtract_digits(result, modulus, result_digits); + } + if (greater_or_equal(result, modulus, result_digits)) { + subtract_digits(result, modulus, result_digits); + } + if (result[modulus_digits] != 0 || greater_or_equal(result, modulus, result_digits)) { + *status = STATUS_REDUCTION_RANGE; + } +} + +static __global__ void finish_barrett_reduction( + const u64 *product, + const u64 *reduction_product, + u64 *result, + const u64 *modulus, + int modulus_digits, + u64 *status +) { + if (blockIdx.x != 0 || threadIdx.x != 0 || *status != STATUS_OK) return; + const int result_digits = modulus_digits + 1; + u64 borrow = 0; + for (int index = 0; index < result_digits; index++) { + const u64 subtrahend = reduction_product[index] + borrow; + const u64 value = product[index]; + result[index] = (value - subtrahend) & DIGIT_MASK; + borrow = value < subtrahend ? 1 : 0; + } + for (int correction = 0; correction < 3; correction++) { + if (!greater_or_equal(result, modulus, result_digits)) break; + subtract_digits(result, modulus, result_digits); + } + if (result[modulus_digits] != 0 || greater_or_equal(result, modulus, result_digits)) { + *status = STATUS_REDUCTION_RANGE; + } +} + +static __global__ void set_one(u64 *value, int digits, u64 *status) { + if (blockIdx.x != 0 || threadIdx.x != 0 || *status != STATUS_OK) return; + for (int index = 0; index < digits; index++) value[index] = 0; + value[0] = 1; +} + +static __global__ void select_window_power( + const u64 *exponent, + int exponent_digits, + int lower_bit, + int bit_count, + const u64 *window_table, + int table_entries, + int stride, + u64 *selected, + u64 *status +) { + if (*status != STATUS_OK) return; + u64 window = 0; + for (int offset = 0; offset < bit_count; offset++) { + const int bit = lower_bit + offset; + const int digit = bit / 16; + if (digit < exponent_digits) { + window |= ((exponent[digit] >> (bit % 16)) & 1) << offset; + } + } + const int table_index = static_cast(window >> 1); + if (window == 0 || (window & 1) == 0 || table_index >= table_entries) { + if (blockIdx.x == 0 && threadIdx.x == 0) *status = STATUS_WINDOW_RANGE; + return; + } + const int index = blockIdx.x * blockDim.x + threadIdx.x; + if (index < stride) { + selected[index] = window_table[static_cast(table_index) * stride + index]; + } +} + +struct ModularNttWorkspace { + int capacity = 0; + int twiddle_count = 0; + cudaStream_t stream = nullptr; + u64 *left = nullptr; + u64 *right = nullptr; + u64 *first_residues = nullptr; + u64 *coefficients = nullptr; + u64 *forward_first = nullptr; + u64 *inverse_first = nullptr; + u64 *forward_third = nullptr; + u64 *inverse_third = nullptr; + u64 *host_twiddles = nullptr; + u64 *host_result = nullptr; + u64 *host_status = nullptr; + int host_twiddle_capacity = 0; + int host_result_capacity = 0; + uint64_t device_bytes = 0; + + ~ModularNttWorkspace() { + release(); + } + + void release() { + cudaFree(left); + cudaFree(right); + cudaFree(first_residues); + cudaFree(coefficients); + cudaFree(forward_first); + cudaFree(inverse_first); + cudaFree(forward_third); + cudaFree(inverse_third); + left = right = first_residues = coefficients = nullptr; + forward_first = inverse_first = forward_third = inverse_third = nullptr; + cudaFreeHost(host_twiddles); + cudaFreeHost(host_result); + cudaFreeHost(host_status); + host_twiddles = host_result = host_status = nullptr; + host_twiddle_capacity = 0; + host_result_capacity = 0; + if (stream != nullptr) { + cudaStreamDestroy(stream); + stream = nullptr; + } + capacity = 0; + twiddle_count = 0; + device_bytes = 0; + } + + bool ensure(int transform_size) { + if (capacity == transform_size && stream != nullptr) return true; + release(); + if (cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) != cudaSuccess) return false; + const size_t full_bytes = sizeof(u64) * static_cast(transform_size); + const size_t half_bytes = sizeof(u64) * static_cast(transform_size / 2); + if (cudaMalloc(&left, full_bytes) != cudaSuccess || + cudaMalloc(&right, full_bytes) != cudaSuccess || + cudaMalloc(&first_residues, full_bytes) != cudaSuccess || + cudaMalloc(&coefficients, full_bytes) != cudaSuccess || + cudaMalloc(&forward_first, half_bytes) != cudaSuccess || + cudaMalloc(&inverse_first, half_bytes) != cudaSuccess || + cudaMalloc(&forward_third, half_bytes) != cudaSuccess || + cudaMalloc(&inverse_third, half_bytes) != cudaSuccess) { + release(); + return false; + } + if (cudaHostAlloc( + reinterpret_cast(&host_twiddles), + half_bytes, + cudaHostAllocDefault + ) != cudaSuccess || cudaHostAlloc( + reinterpret_cast(&host_status), + sizeof(u64), + cudaHostAllocDefault + ) != cudaSuccess) { + release(); + return false; + } + capacity = transform_size; + host_twiddle_capacity = transform_size / 2; + device_bytes = static_cast(full_bytes) * 4 + + static_cast(half_bytes) * 4; + return true; + } + + bool ensure_host_result(int digits) { + if (host_result_capacity >= digits) return true; + cudaFreeHost(host_result); + host_result = nullptr; + host_result_capacity = 0; + if (cudaHostAlloc( + reinterpret_cast(&host_result), + sizeof(u64) * static_cast(digits), + cudaHostAllocDefault + ) != cudaSuccess) { + return false; + } + host_result_capacity = digits; + return true; + } +}; + +bool upload_twiddles( + ModularNttWorkspace &workspace, + u64 *destination, + int transform_size, + u64 modulus, + bool inverse_transform +) { + const u64 root = host_powmod( + PRIMITIVE_ROOT, + (modulus - 1) / static_cast(transform_size), + modulus + ); + const u64 step = inverse_transform ? host_powmod(root, modulus - 2, modulus) : root; + u64 current = 1; + for (int index = 0; index < transform_size / 2; index++) { + workspace.host_twiddles[index] = current; + current = host_mulmod(current, step, modulus); + } + return cudaMemcpyAsync( + destination, + workspace.host_twiddles, + sizeof(u64) * static_cast(transform_size / 2), + cudaMemcpyHostToDevice, + workspace.stream + ) == cudaSuccess && cudaStreamSynchronize(workspace.stream) == cudaSuccess; +} + +bool ensure_twiddles(ModularNttWorkspace &workspace, int transform_size) { + if (workspace.twiddle_count == transform_size) return true; + if (!upload_twiddles(workspace, workspace.forward_first, transform_size, MOD1, false) || + !upload_twiddles(workspace, workspace.inverse_first, transform_size, MOD1, true) || + !upload_twiddles(workspace, workspace.forward_third, transform_size, MOD3, false) || + !upload_twiddles(workspace, workspace.inverse_third, transform_size, MOD3, true) || + cudaStreamSynchronize(workspace.stream) != cudaSuccess) { + workspace.twiddle_count = 0; + return false; + } + workspace.twiddle_count = transform_size; + return true; +} + +class ModularWorkspacePool { +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(ModularWorkspacePool *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_), discard_(other.discard_) { + other.pool_ = nullptr; + } + + Lease &operator=(Lease &&other) noexcept { + if (this != &other) { + release(); + pool_ = other.pool_; + slot_ = other.slot_; + discard_ = other.discard_; + other.pool_ = nullptr; + } + return *this; + } + + explicit operator bool() const { + return pool_ != nullptr; + } + + ModularNttWorkspace &workspace() { + return *slot_->workspace; + } + + void discard() { + discard_ = true; + } + + private: + void release() { + if (pool_ == nullptr) return; + pool_->release(slot_, discard_); + pool_ = nullptr; + } + + ModularWorkspacePool *pool_ = nullptr; + Slot *slot_ = nullptr; + bool discard_ = false; + }; + + 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 transform_size, 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(transform_size) * 6; + for (;;) { + std::unique_lock lock(mutex_); + if (!configured_) return Lease{}; + for (const auto &slot : slots_) { + if (!slot->busy && slot->transform_size == transform_size) { + 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(transform_size) && ensure_twiddles(*workspace, transform_size); + 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 = transform_size; + 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; + })); + } + +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, bool discard) { + cudaError_t synchronized = cudaErrorInvalidResourceHandle; + if (slot != nullptr && cudaSetDevice(device_) == cudaSuccess) { + synchronized = cudaStreamSynchronize(slot->workspace->stream); + } + std::lock_guard lock(mutex_); + if (slot != nullptr && !discard && 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; +}; + +ModularWorkspacePool &workspace_pool() { + static ModularWorkspacePool pool; + return pool; +} + +struct ResidentBuffers { + int device = 0; + int modulus_digits = 0; + int stride = 0; + int full_digits = 0; + int exponent_digits = 0; + int window_entries = 0; + u64 *block = nullptr; + u64 *host_initial = nullptr; + u64 *modulus = nullptr; + u64 *constant = nullptr; + u64 *accumulator = nullptr; + u64 *power = nullptr; + u64 *spare = nullptr; + u64 *exponent = nullptr; + u64 *full_first = nullptr; + u64 *full_second = nullptr; + u64 *quotient = nullptr; + u64 *status = nullptr; + u64 *window_table = nullptr; + uint64_t bytes = 0; + + ~ResidentBuffers() { + release(); + } + + void release() { + cudaFreeHost(host_initial); + host_initial = nullptr; + cudaFree(block); + block = nullptr; + if (bytes != 0) { + resident_buffer_bytes.fetch_sub(bytes, std::memory_order_relaxed); + bigmath::runtime::release_cuda_workspace_bytes(device, bytes); + bytes = 0; + } + } + + bool allocate( + int selected_device, + int digits, + int selected_exponent_digits, + int selected_window_entries + ) { + device = selected_device; + modulus_digits = digits; + stride = digits + 1; + full_digits = 2 * digits + 4; + exponent_digits = selected_exponent_digits; + window_entries = selected_window_entries; + const size_t total_digits = static_cast(stride) * 5 + + static_cast(exponent_digits) + + static_cast(full_digits) * 2 + static_cast(digits + 2) + 1 + + static_cast(window_entries) * stride; + if (total_digits > std::numeric_limits::max() / sizeof(u64)) return false; + bytes = static_cast(total_digits * sizeof(u64)); + if (!bigmath::runtime::reserve_cuda_workspace_bytes(device, bytes)) { + bytes = 0; + return false; + } + resident_buffer_bytes.fetch_add(bytes, std::memory_order_relaxed); + if (cudaMalloc(&block, static_cast(bytes)) != cudaSuccess || + cudaHostAlloc( + reinterpret_cast(&host_initial), + (static_cast(stride) * 5 + exponent_digits) * sizeof(u64), + cudaHostAllocDefault + ) != cudaSuccess) { + release(); + return false; + } + u64 *cursor = block; + modulus = cursor; cursor += stride; + constant = cursor; cursor += stride; + accumulator = cursor; cursor += stride; + power = cursor; cursor += stride; + spare = cursor; cursor += stride; + exponent = cursor; cursor += exponent_digits; + full_first = cursor; cursor += full_digits; + full_second = cursor; cursor += full_digits; + quotient = cursor; cursor += digits + 2; + status = cursor; cursor++; + window_table = cursor; + return true; + } + + static void copy_to_padded( + u64 *destination, + int capacity, + const std::vector &source + ) { + for (int index = 0; index < capacity; index++) destination[index] = 0; + const size_t count = std::min(source.size(), static_cast(capacity)); + for (size_t index = 0; index < count; index++) destination[index] = source[index]; + } + + bool initialize( + const std::vector &base, + const std::vector &exponent_value, + const std::vector &modulus_value, + const std::vector &reduction_constant, + const std::vector &identity, + cudaStream_t stream + ) { + copy_to_padded(host_initial, stride, modulus_value); + copy_to_padded(host_initial + stride, stride, reduction_constant); + copy_to_padded(host_initial + stride * 2, stride, identity); + copy_to_padded(host_initial + stride * 3, stride, base); + for (int index = 0; index < stride; index++) host_initial[stride * 4 + index] = 0; + copy_to_padded( + host_initial + static_cast(stride) * 5, + exponent_digits, + exponent_value + ); + const size_t initial_bytes = + (static_cast(stride) * 5 + exponent_digits) * sizeof(u64); + return cudaMemcpyAsync( + block, + host_initial, + initial_bytes, + cudaMemcpyHostToDevice, + stream + ) == cudaSuccess && cudaMemsetAsync( + block + static_cast(stride) * 5 + exponent_digits, + 0, + static_cast(bytes) - initial_bytes, + stream + ) == cudaSuccess; + } +}; + +bool load_device_digits( + ModularNttWorkspace &workspace, + u64 *destination, + const u64 *source, + int source_digits, + int transform_size +) { + if (cudaMemcpyAsync( + destination, + source, + sizeof(u64) * static_cast(source_digits), + cudaMemcpyDeviceToDevice, + workspace.stream + ) != cudaSuccess) { + return false; + } + return source_digits >= transform_size || cudaMemsetAsync( + destination + source_digits, + 0, + sizeof(u64) * static_cast(transform_size - source_digits), + workspace.stream + ) == cudaSuccess; +} + +bool convolve_prime( + ModularNttWorkspace &workspace, + const u64 *left_digits, + int left_count, + const u64 *right_digits, + int right_count, + int transform_size, + int logarithm, + u64 modulus, + u64 mu, + const u64 *forward_twiddles, + const u64 *inverse_twiddles +) { + const bool square = left_digits == right_digits && left_count == right_count; + if (!load_device_digits(workspace, workspace.left, left_digits, left_count, transform_size) || + (!square && !load_device_digits( + workspace, + workspace.right, + right_digits, + right_count, + transform_size + ))) { + return false; + } + if (!forward( + workspace.left, + forward_twiddles, + transform_size, + logarithm, + modulus, + mu, + workspace.stream + ) || (!square && !forward( + workspace.right, + forward_twiddles, + transform_size, + logarithm, + modulus, + mu, + workspace.stream + ))) { + return false; + } + const u64 *right_transform = square ? workspace.left : workspace.right; + pointwise_multiply<<< + (transform_size + BLOCK_SIZE - 1) / BLOCK_SIZE, + BLOCK_SIZE, + 0, + workspace.stream + >>>(workspace.left, right_transform, transform_size, modulus, mu); + return cudaGetLastError() == cudaSuccess && inverse( + workspace.left, + inverse_twiddles, + transform_size, + logarithm, + modulus, + mu, + workspace.stream + ); +} + +bool convolve_device( + ModularNttWorkspace &workspace, + const u64 *left, + int left_digits, + const u64 *right, + int right_digits, + u64 *output, + int output_capacity, + int transform_size, + int logarithm, + u64 *status +) { + if (left_digits <= 0 || right_digits <= 0) return false; + const int coefficient_count = left_digits + right_digits - 1; + if (coefficient_count > transform_size || coefficient_count > output_capacity) return false; + const u64 minimum = static_cast(std::min(left_digits, right_digits)); + if (UINT64_C(65535) * UINT64_C(65535) > CRT_MODULUS / minimum) return false; + if (!convolve_prime( + workspace, + left, + left_digits, + right, + right_digits, + transform_size, + logarithm, + MOD1, + MU1, + workspace.forward_first, + workspace.inverse_first + )) { + return false; + } + if (cudaMemcpyAsync( + workspace.first_residues, + workspace.left, + sizeof(u64) * static_cast(transform_size), + cudaMemcpyDeviceToDevice, + workspace.stream + ) != cudaSuccess || !convolve_prime( + workspace, + left, + left_digits, + right, + right_digits, + transform_size, + logarithm, + MOD3, + MU3, + workspace.forward_third, + workspace.inverse_third + )) { + return false; + } + reconstruct_crt<<< + (coefficient_count + BLOCK_SIZE - 1) / BLOCK_SIZE, + BLOCK_SIZE, + 0, + workspace.stream + >>>( + workspace.first_residues, + workspace.left, + workspace.coefficients, + coefficient_count + ); + normalize_coefficients<<<1, 1, 0, workspace.stream>>>( + workspace.coefficients, + output, + coefficient_count, + output_capacity, + status + ); + return cudaGetLastError() == cudaSuccess; +} + +bool montgomery_multiply( + ModularNttWorkspace &workspace, + ResidentBuffers &buffers, + const u64 *left, + const u64 *right, + u64 *output, + int transform_size, + int logarithm +) { + const int digits = buffers.modulus_digits; + if (!convolve_device( + workspace, + left, + digits, + right, + digits, + buffers.full_first, + buffers.full_digits, + transform_size, + logarithm, + buffers.status + ) || !convolve_device( + workspace, + buffers.full_first, + digits, + buffers.constant, + digits, + buffers.full_second, + buffers.full_digits, + transform_size, + logarithm, + buffers.status + ) || cudaMemcpyAsync( + buffers.quotient, + buffers.full_second, + sizeof(u64) * static_cast(digits), + cudaMemcpyDeviceToDevice, + workspace.stream + ) != cudaSuccess || !convolve_device( + workspace, + buffers.quotient, + digits, + buffers.modulus, + digits, + buffers.full_second, + buffers.full_digits, + transform_size, + logarithm, + buffers.status + )) { + return false; + } + finish_montgomery_reduction<<<1, 1, 0, workspace.stream>>>( + buffers.full_first, + buffers.full_second, + output, + buffers.modulus, + digits, + buffers.status + ); + return cudaGetLastError() == cudaSuccess; +} + +bool barrett_multiply( + ModularNttWorkspace &workspace, + ResidentBuffers &buffers, + const u64 *left, + const u64 *right, + u64 *output, + int transform_size, + int logarithm +) { + const int digits = buffers.modulus_digits; + if (!convolve_device( + workspace, + left, + digits, + right, + digits, + buffers.full_first, + buffers.full_digits, + transform_size, + logarithm, + buffers.status + ) || !convolve_device( + workspace, + buffers.full_first + digits - 1, + digits + 1, + buffers.constant, + digits + 1, + buffers.full_second, + buffers.full_digits, + transform_size, + logarithm, + buffers.status + ) || !convolve_device( + workspace, + buffers.full_second + digits + 1, + digits + 1, + buffers.modulus, + digits, + buffers.full_second, + buffers.full_digits, + transform_size, + logarithm, + buffers.status + )) { + return false; + } + finish_barrett_reduction<<<1, 1, 0, workspace.stream>>>( + buffers.full_first, + buffers.full_second, + output, + buffers.modulus, + digits, + buffers.status + ); + return cudaGetLastError() == cudaSuccess; +} + +size_t exponent_bit_length(const std::vector &exponent) { + size_t digits = exponent.size(); + while (digits > 0 && exponent[digits - 1] == 0) digits--; + if (digits == 0) return 0; + uint16_t top = exponent[digits - 1]; + unsigned high_bits = 0; + while (top != 0) { + high_bits++; + top >>= 1; + } + return (digits - 1) * 16 + high_bits; +} + +bool exponent_bit(const std::vector &exponent, size_t bit) { + const size_t digit = bit / 16; + return digit < exponent.size() && ((exponent[digit] >> (bit % 16)) & 1) != 0; +} + +size_t window_start( + const std::vector &exponent, + size_t position, + unsigned width +) { + const size_t minimum = position > width ? position - width : 0; + size_t start = minimum; + while (!exponent_bit(exponent, start)) start++; + return start; +} + +long double window_operation_cost( + const std::vector &exponent, + size_t bits, + unsigned width, + uint64_t multiply_nanos, + uint64_t square_nanos +) { + const uint64_t entries = UINT64_C(1) << (width - 1); + long double cost = width == 1 + ? 0.0L + : static_cast(square_nanos) + + static_cast(entries - 1) * multiply_nanos; + size_t position = bits; + while (position > 0) { + if (!exponent_bit(exponent, position - 1)) { + position--; + continue; + } + position = window_start(exponent, position, width); + cost += multiply_nanos; + } + return cost; +} + +unsigned select_window_width( + const std::vector &exponent, + size_t bits, + uint64_t multiply_nanos, + uint64_t square_nanos +) { + unsigned selected = 1; + long double selected_cost = window_operation_cost( + exponent, + bits, + selected, + multiply_nanos, + square_nanos + ); + for (unsigned width = 2; width <= 6; width++) { + const long double cost = window_operation_cost( + exponent, + bits, + width, + multiply_nanos, + square_nanos + ); + if (cost < selected_cost) { + selected = width; + selected_cost = cost; + } + } + return selected; +} + +bool less_than_modulus( + const std::vector &value, + const std::vector &modulus +) { + for (size_t index = modulus.size(); index > 0; index--) { + const uint16_t left = index <= value.size() ? value[index - 1] : 0; + const uint16_t right = modulus[index - 1]; + if (left != right) return left < right; + } + return false; +} + +} + +bool configure_modular_workspace_pool(int device) { + return workspace_pool().configure(device); +} + +uint64_t modular_workspace_in_use_bytes() { + return workspace_pool().in_use_bytes() + + resident_buffer_bytes.load(std::memory_order_relaxed); +} + +int modular_workspace_capacity() { + return workspace_pool().capacity(); +} + +int modular_workspace_in_use() { + return workspace_pool().in_use(); +} + +bool resident_modpow_u16( + const std::vector &base, + const std::vector &exponent, + const std::vector &modulus, + const std::vector &reduction_constant, + const std::vector &identity, + ResidentReduction reduction, + uint64_t multiply_nanos, + uint64_t square_nanos, + uint64_t max_queue_wait_nanos, + std::vector &result +) { + if (base.empty() || modulus.empty() || reduction_constant.empty() || identity.empty()) { + return false; + } + if (exponent.empty() || + exponent.size() > static_cast(std::numeric_limits::max() / 16)) { + return false; + } + if (modulus.size() > static_cast((NTT_MAX_TRANSFORM_SIZE - 4) / 2)) { + return false; + } + const int digits = static_cast(modulus.size()); + int transform_size = 0; + int logarithm = 0; + if (!next_power_of_two(static_cast(2 * digits + 3), transform_size, logarithm)) { + return false; + } + const size_t bits = exponent_bit_length(exponent); + const unsigned window_width = select_window_width( + exponent, + bits, + std::max(1, multiply_nanos), + std::max(1, square_nanos) + ); + const int window_entries = 1 << (window_width - 1); + + ModularWorkspacePool::Lease lease = workspace_pool().acquire( + transform_size, + max_queue_wait_nanos + ); + if (!lease) return false; + ModularNttWorkspace &workspace = lease.workspace(); + if (!workspace.ensure_host_result(digits)) { + lease.discard(); + return false; + } + int device = 0; + if (cudaGetDevice(&device) != cudaSuccess) { + lease.discard(); + return false; + } + ResidentBuffers buffers; + if (!buffers.allocate( + device, + digits, + static_cast(exponent.size()), + window_entries + ) || !buffers.initialize( + base, + exponent, + modulus, + reduction_constant, + identity, + workspace.stream + )) { + lease.discard(); + return false; + } + + auto modular_multiply = [&](const u64 *left, const u64 *right, u64 *output) { + return reduction == ResidentReduction::MONTGOMERY + ? montgomery_multiply( + workspace, + buffers, + left, + right, + output, + transform_size, + logarithm + ) + : barrett_multiply( + workspace, + buffers, + left, + right, + output, + transform_size, + logarithm + ); + }; + + if (cudaMemcpyAsync( + buffers.window_table, + buffers.power, + sizeof(u64) * static_cast(buffers.stride), + cudaMemcpyDeviceToDevice, + workspace.stream + ) != cudaSuccess) { + lease.discard(); + return false; + } + if (window_entries > 1) { + if (!modular_multiply(buffers.power, buffers.power, buffers.spare)) { + lease.discard(); + return false; + } + for (int entry = 1; entry < window_entries; entry++) { + if (!modular_multiply( + buffers.window_table + static_cast(entry - 1) * buffers.stride, + buffers.spare, + buffers.window_table + static_cast(entry) * buffers.stride + )) { + lease.discard(); + return false; + } + } + } + + size_t position = bits; + while (position > 0) { + if (!exponent_bit(exponent, position - 1)) { + if (!modular_multiply(buffers.accumulator, buffers.accumulator, buffers.spare)) { + lease.discard(); + return false; + } + std::swap(buffers.accumulator, buffers.spare); + position--; + continue; + } + + const size_t lower = window_start(exponent, position, window_width); + const int window_bits = static_cast(position - lower); + for (int square = 0; square < window_bits; square++) { + if (!modular_multiply(buffers.accumulator, buffers.accumulator, buffers.spare)) { + lease.discard(); + return false; + } + std::swap(buffers.accumulator, buffers.spare); + } + select_window_power<<< + (buffers.stride + BLOCK_SIZE - 1) / BLOCK_SIZE, + BLOCK_SIZE, + 0, + workspace.stream + >>>( + buffers.exponent, + buffers.exponent_digits, + static_cast(lower), + window_bits, + buffers.window_table, + window_entries, + buffers.stride, + buffers.power, + buffers.status + ); + if (cudaGetLastError() != cudaSuccess || + !modular_multiply(buffers.accumulator, buffers.power, buffers.spare)) { + lease.discard(); + return false; + } + std::swap(buffers.accumulator, buffers.spare); + position = lower; + } + + u64 *final_value = buffers.accumulator; + if (reduction == ResidentReduction::MONTGOMERY) { + set_one<<<1, 1, 0, workspace.stream>>>( + buffers.quotient, + digits, + buffers.status + ); + if (cudaGetLastError() != cudaSuccess || + !modular_multiply(buffers.accumulator, buffers.quotient, buffers.spare)) { + lease.discard(); + return false; + } + final_value = buffers.spare; + } + + if (cudaMemcpyAsync( + workspace.host_result, + final_value, + sizeof(u64) * static_cast(digits), + cudaMemcpyDeviceToHost, + workspace.stream + ) != cudaSuccess || cudaMemcpyAsync( + workspace.host_status, + buffers.status, + sizeof(u64), + cudaMemcpyDeviceToHost, + workspace.stream + ) != cudaSuccess || cudaStreamSynchronize(workspace.stream) != cudaSuccess || + *workspace.host_status != STATUS_OK) { + lease.discard(); + return false; + } + + std::vector completed_result(static_cast(digits)); + for (int index = 0; index < digits; index++) { + if (workspace.host_result[index] > DIGIT_MASK) { + lease.discard(); + return false; + } + completed_result[static_cast(index)] = + static_cast(workspace.host_result[index]); + } + while (completed_result.size() > 1 && completed_result.back() == 0) { + completed_result.pop_back(); + } + if (!less_than_modulus(completed_result, modulus)) { + lease.discard(); + return false; + } + result = std::move(completed_result); + return true; +} + +} diff --git a/src/main/cpp/cuda_modular.h b/src/main/cpp/cuda_modular.h new file mode 100644 index 0000000..8af4777 --- /dev/null +++ b/src/main/cpp/cuda_modular.h @@ -0,0 +1,45 @@ +#ifndef BIGMATH_CUDA_MODULAR_H +#define BIGMATH_CUDA_MODULAR_H + +#include +#include + +namespace bigmath::cuda { + +// Selects the device-resident reduction for one fixed modulus. Montgomery is +// valid only for odd moduli; Barrett accepts any positive modulus. +enum class ResidentReduction { + MONTGOMERY, + BARRETT +}; + +// Configures the process-wide pool for the selected CUDA device. Leases are +// exclusive, share the global CUDA workspace budget, and may be used by any +// caller thread after runtime initialization. +bool configure_modular_workspace_pool(int device); +uint64_t modular_workspace_in_use_bytes(); +int modular_workspace_capacity(); +int modular_workspace_in_use(); + +// Computes base^exponent mod modulus while all intermediate values remain on +// one device and stream. Inputs are little-endian base-2^16 digits. The caller +// must provide the matching precomputed reduction constant and identity. On +// any allocation, launch, synchronization, normalization, or range failure the +// function returns false and leaves result unchanged so the caller can safely +// fall back to mpz_powm. +bool resident_modpow_u16( + const std::vector &base, + const std::vector &exponent, + const std::vector &modulus, + const std::vector &reduction_constant, + const std::vector &identity, + ResidentReduction reduction, + uint64_t multiply_nanos, + uint64_t square_nanos, + uint64_t max_queue_wait_nanos, + std::vector &result +); + +} + +#endif diff --git a/src/main/cpp/cuda_ntt.cu b/src/main/cpp/cuda_ntt.cu index b0420d7..2bc53db 100644 --- a/src/main/cpp/cuda_ntt.cu +++ b/src/main/cpp/cuda_ntt.cu @@ -1,4 +1,5 @@ #include "cuda_ntt.h" +#include "cuda_ntt_device.cuh" #include "runtime/cuda_workspace_budget.h" #include @@ -15,145 +16,9 @@ namespace bigmath::cuda { -// NTT-friendly primes = k*2^b + 1 with primitive root 3. CRT reconstructs -// exact coefficients over MOD1*MOD3 (~2^58.8). -// Every modulus is < 2^30, so a product of two reduced residues is < 2^60 and -// fits in u64 without 128-bit arithmetic. namespace { -using u64 = uint64_t; - -constexpr u64 MOD1 = 998244353; // 119 * 2^23 + 1 -constexpr u64 MOD3 = 469762049; // 7 * 2^26 + 1 -constexpr u64 PRIMITIVE_ROOT = 3; - -constexpr u64 host_mulmod(u64 a, u64 b, u64 mod) { - return (a % mod) * (b % mod) % mod; -} - -constexpr u64 host_powmod(u64 a, u64 e, u64 mod) { - u64 r = 1; - while (e) { - if (e & 1) r = host_mulmod(r, a, mod); - a = host_mulmod(a, a, mod); - e >>= 1; - } - return r; -} - -constexpr u64 MOD1_INV_MOD3 = host_powmod(MOD1, MOD3 - 2, MOD3); - -// Barrett constant mu = floor(2^64 / p). For an odd prime p, (~0ULL)/p equals -// floor(2^64 / p) exactly (p never divides 2^64). -constexpr u64 barrett_mu(u64 p) { return (~static_cast(0)) / p; } -constexpr u64 MU1 = barrett_mu(MOD1); -constexpr u64 MU3 = barrett_mu(MOD3); - -// Barrett reduction of a*b mod p for a,b < p < 2^30 (so a*b < 2^60 < 2^64). -// Replaces the slow 64-bit hardware modulo on the hottest NTT path. q is -// floor(x*mu / 2^64) and underestimates floor(x/p) by at most 1, so at most two -// conditional subtractions restore the canonical residue. -__device__ __forceinline__ u64 dmul(u64 a, u64 b, u64 p, u64 mu) { - const u64 x = a * b; // < 2^60 - const u64 q = __umul64hi(x, mu); // ~ x / p - u64 r = x - q * p; - if (r >= p) r -= p; - if (r >= p) r -= p; - return r; -} - -__global__ void k_bit_reverse(u64 *a, int n, int logn) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - // reverse the low logn bits of i - unsigned x = static_cast(i); - x = (x >> 16) | (x << 16); - x = ((x & 0x00ff00ffu) << 8) | ((x & 0xff00ff00u) >> 8); - x = ((x & 0x0f0f0f0fu) << 4) | ((x & 0xf0f0f0f0u) >> 4); - x = ((x & 0x33333333u) << 2) | ((x & 0xccccccccu) >> 2); - x = ((x & 0x55555555u) << 1) | ((x & 0xaaaaaaaau) >> 1); - const int j = static_cast(x >> (32 - logn)); - if (i < j) { - const u64 t = a[i]; - a[i] = a[j]; - a[j] = t; - } -} - -// One Cooley-Tukey stage. `twiddles` holds powers of the primitive n-th root -// (forward or inverse); stage `len` reads index j*(n/len). -__global__ void k_butterfly(u64 *a, const u64 *twiddles, int n, int len, u64 p, u64 mu) { - const int t = blockIdx.x * blockDim.x + threadIdx.x; - const int half = len >> 1; - if (t >= (n >> 1)) return; - const int block = t / half; - const int j = t - block * half; - const int i = block * len + j; - const int step = n / len; - const u64 u = a[i]; - const u64 v = dmul(a[i + half], twiddles[j * step], p, mu); - u64 s = u + v; - if (s >= p) s -= p; - u64 d = u >= v ? u - v : u + p - v; - a[i] = s; - a[i + half] = d; -} - -// Fused shared-memory stages. Each block owns one `tile`-element span of the -// (already bit-reversed) array and runs every Cooley-Tukey stage with len <= -// tile entirely in shared memory, so those ~log2(tile) stages cost a single -// global read + write instead of one full global pass each. Twiddle indices -// (j * n/len) are identical to the global k_butterfly because the span is -// tile-aligned and tile is a multiple of len, so the same global twiddle table -// is reused. Launch with blockDim = tile/2 threads and tile*sizeof(u64) smem. -__global__ void k_ntt_shared(u64 *a, const u64 *twiddles, int n, int tile, u64 p, u64 mu) { - extern __shared__ u64 s[]; - const int base = blockIdx.x * tile; - const int tid = threadIdx.x; // 0 .. tile/2 - 1 - const int halfTile = tile >> 1; - s[tid] = a[base + tid]; - s[tid + halfTile] = a[base + tid + halfTile]; - __syncthreads(); - for (int len = 2; len <= tile; len <<= 1) { - const int half = len >> 1; - const int step = n / len; - const int block = tid / half; - const int j = tid - block * half; - const int i = block * len + j; - const u64 u = s[i]; - const u64 v = dmul(s[i + half], twiddles[j * step], p, mu); - u64 sp = u + v; - if (sp >= p) sp -= p; - s[i] = sp; - s[i + half] = u >= v ? u - v : u + p - v; - __syncthreads(); - } - a[base + tid] = s[tid]; - a[base + tid + halfTile] = s[tid + halfTile]; -} - -__global__ void k_pointwise(u64 *fa, const u64 *fb, int n, u64 p, u64 mu) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - fa[i] = dmul(fa[i], fb[i], p, mu); -} - -__global__ void k_scale(u64 *a, int n, u64 inv_n, u64 p, u64 mu) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= n) return; - a[i] = dmul(a[i], inv_n, p, mu); -} - -// out[i] = CRT(c1[i] mod MOD1, c3[i] mod MOD3) in [0, MOD1*MOD3) -__global__ void k_crt(const u64 *c1, const u64 *c3, u64 *out, int count, u64 mu3) { - const int i = blockIdx.x * blockDim.x + threadIdx.x; - if (i >= count) return; - const u64 r1 = c1[i]; - const u64 r3 = c3[i]; - const u64 r1m = r1 % MOD3; - const u64 delta = r3 >= r1m ? r3 - r1m : r3 + MOD3 - r1m; - out[i] = r1 + dmul(delta, MOD1_INV_MOD3, MOD3, mu3) * MOD1; -} +using namespace ntt_device; struct NttWorkspace { int capacity = 0; // allocated element count (n) @@ -485,18 +350,6 @@ NttWorkspacePool &ntt_workspace_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) { - p <<= 1; - logn++; - } - out_n = p; - out_logn = logn; - return true; -} - // Fill `host_w` with powers of the primitive n-th root of unity mod p and // upload to `dst` (n/2 entries). `inverse` uses the inverse root. bool upload_twiddles(NttWorkspace &ws, u64 *dst, int n, u64 p, bool inverse) { @@ -560,37 +413,6 @@ bool load_digits( ) == cudaSuccess; } -constexpr int BLOCK = 256; -// Largest fused shared-memory tile. tile/2 threads/block (<= 1024) and -// tile*8 bytes of shared memory (16 KiB at 2048); fuses log2(tile)=11 stages. -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, cudaStream_t stream) { - const int tile = n < SHARED_TILE ? n : 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); - } -} - -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, 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, 0, stream>>>(a, n, inv_n, p, mu); - return cudaGetLastError() == cudaSuccess; -} - // fa <- IDFT( DFT(a) .* DFT(b) ) mod p, results left in workspace.fa. // Twiddles must already be uploaded for this n (see ensure_twiddles). bool convolve_one_prime(NttWorkspace &ws, const std::vector &a, @@ -606,18 +428,24 @@ bool convolve_one_prime(NttWorkspace &ws, const std::vector &a, if (!squaring && !load_digits(ws, ws.host_b, ws.fb, b, n)) { return false; } - if (!forward_ntt(ws.fa, wf, n, logn, p, mu, ws.stream)) { + if (!forward(ws.fa, wf, n, logn, p, mu, ws.stream)) { return false; } - if (!squaring && !forward_ntt(ws.fb, wf, n, logn, p, mu, ws.stream)) { + if (!squaring && !forward(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, 0, ws.stream>>>(ws.fa, rhs, n, p, mu); + pointwise_multiply<<<(n + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE, 0, ws.stream>>>( + ws.fa, + rhs, + n, + p, + mu + ); if (cudaGetLastError() != cudaSuccess) { return false; } - return inverse_ntt(ws.fa, wi, n, logn, p, mu, ws.stream) && + return inverse(ws.fa, wi, n, logn, p, mu, ws.stream) && cudaStreamSynchronize(ws.stream) == cudaSuccess; } @@ -639,7 +467,7 @@ bool convolve_ntt_u16_to_limbs(const std::vector &a, const size_t result_size = a.size() + b.size() - 1; int n = 0, logn = 0; - if (!next_pow2(result_size, n, logn)) { + if (!next_power_of_two(result_size, n, logn)) { return false; } @@ -671,8 +499,12 @@ bool convolve_ntt_u16_to_limbs(const std::vector &a, 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, 0, ws.stream>>>( - ws.c1, ws.fa, ws.out, static_cast(result_size), MU3); + reconstruct_crt<<< + (static_cast(result_size) + BLOCK_SIZE - 1) / BLOCK_SIZE, + BLOCK_SIZE, + 0, + ws.stream + >>>(ws.c1, ws.fa, ws.out, static_cast(result_size)); if (cudaGetLastError() != cudaSuccess) { return false; } diff --git a/src/main/cpp/cuda_ntt_device.cuh b/src/main/cpp/cuda_ntt_device.cuh new file mode 100644 index 0000000..9089f17 --- /dev/null +++ b/src/main/cpp/cuda_ntt_device.cuh @@ -0,0 +1,261 @@ +#ifndef BIGMATH_CUDA_NTT_DEVICE_CUH +#define BIGMATH_CUDA_NTT_DEVICE_CUH + +#include "cuda_ntt.h" + +#include +#include + +#include + +namespace bigmath::cuda::ntt_device { + +using u64 = uint64_t; + +inline constexpr u64 MOD1 = 998244353; +inline constexpr u64 MOD3 = 469762049; +inline constexpr u64 PRIMITIVE_ROOT = 3; +inline constexpr int BLOCK_SIZE = 256; +inline constexpr int SHARED_TILE_SIZE = 2048; + +constexpr u64 host_mulmod(u64 a, u64 b, u64 modulus) { + return (a % modulus) * (b % modulus) % modulus; +} + +constexpr u64 host_powmod(u64 a, u64 exponent, u64 modulus) { + u64 result = 1; + while (exponent != 0) { + if ((exponent & 1) != 0) result = host_mulmod(result, a, modulus); + a = host_mulmod(a, a, modulus); + exponent >>= 1; + } + return result; +} + +inline constexpr u64 MOD1_INV_MOD3 = host_powmod(MOD1, MOD3 - 2, MOD3); + +constexpr u64 barrett_mu(u64 modulus) { + return (~static_cast(0)) / modulus; +} + +inline constexpr u64 MU1 = barrett_mu(MOD1); +inline constexpr u64 MU3 = barrett_mu(MOD3); + +__device__ __forceinline__ u64 multiply_mod(u64 left, u64 right, u64 modulus, u64 mu) { + const u64 product = left * right; + const u64 quotient = __umul64hi(product, mu); + u64 result = product - quotient * modulus; + if (result >= modulus) result -= modulus; + if (result >= modulus) result -= modulus; + return result; +} + +static __global__ void bit_reverse(u64 *values, int count, int logarithm) { + const int index = blockIdx.x * blockDim.x + threadIdx.x; + if (index >= count) return; + unsigned reversed = static_cast(index); + reversed = (reversed >> 16) | (reversed << 16); + reversed = ((reversed & 0x00ff00ffu) << 8) | ((reversed & 0xff00ff00u) >> 8); + reversed = ((reversed & 0x0f0f0f0fu) << 4) | ((reversed & 0xf0f0f0f0u) >> 4); + reversed = ((reversed & 0x33333333u) << 2) | ((reversed & 0xccccccccu) >> 2); + reversed = ((reversed & 0x55555555u) << 1) | ((reversed & 0xaaaaaaaau) >> 1); + const int target = static_cast(reversed >> (32 - logarithm)); + if (index < target) { + const u64 temporary = values[index]; + values[index] = values[target]; + values[target] = temporary; + } +} + +static __global__ void butterfly( + u64 *values, + const u64 *twiddles, + int count, + int length, + u64 modulus, + u64 mu +) { + const int thread = blockIdx.x * blockDim.x + threadIdx.x; + const int half = length >> 1; + if (thread >= (count >> 1)) return; + const int block = thread / half; + const int offset = thread - block * half; + const int index = block * length + offset; + const int step = count / length; + const u64 left = values[index]; + const u64 right = multiply_mod(values[index + half], twiddles[offset * step], modulus, mu); + u64 sum = left + right; + if (sum >= modulus) sum -= modulus; + values[index] = sum; + values[index + half] = left >= right ? left - right : left + modulus - right; +} + +static __global__ void fused_stages( + u64 *values, + const u64 *twiddles, + int count, + int tile, + u64 modulus, + u64 mu +) { + extern __shared__ u64 shared[]; + const int base = blockIdx.x * tile; + const int thread = threadIdx.x; + const int half_tile = tile >> 1; + shared[thread] = values[base + thread]; + shared[thread + half_tile] = values[base + thread + half_tile]; + __syncthreads(); + for (int length = 2; length <= tile; length <<= 1) { + const int half = length >> 1; + const int step = count / length; + const int block = thread / half; + const int offset = thread - block * half; + const int index = block * length + offset; + const u64 left = shared[index]; + const u64 right = multiply_mod( + shared[index + half], + twiddles[offset * step], + modulus, + mu + ); + u64 sum = left + right; + if (sum >= modulus) sum -= modulus; + shared[index] = sum; + shared[index + half] = left >= right ? left - right : left + modulus - right; + __syncthreads(); + } + values[base + thread] = shared[thread]; + values[base + thread + half_tile] = shared[thread + half_tile]; +} + +static __global__ void pointwise_multiply( + u64 *left, + const u64 *right, + int count, + u64 modulus, + u64 mu +) { + const int index = blockIdx.x * blockDim.x + threadIdx.x; + if (index >= count) return; + left[index] = multiply_mod(left[index], right[index], modulus, mu); +} + +static __global__ void scale( + u64 *values, + int count, + u64 inverse_count, + u64 modulus, + u64 mu +) { + const int index = blockIdx.x * blockDim.x + threadIdx.x; + if (index >= count) return; + values[index] = multiply_mod(values[index], inverse_count, modulus, mu); +} + +static __global__ void reconstruct_crt( + const u64 *first, + const u64 *third, + u64 *output, + int count +) { + const int index = blockIdx.x * blockDim.x + threadIdx.x; + if (index >= count) return; + const u64 first_residue = first[index]; + const u64 third_residue = third[index]; + const u64 first_mod_third = first_residue % MOD3; + const u64 delta = third_residue >= first_mod_third + ? third_residue - first_mod_third + : third_residue + MOD3 - first_mod_third; + output[index] = first_residue + multiply_mod(delta, MOD1_INV_MOD3, MOD3, MU3) * MOD1; +} + +inline bool next_power_of_two(size_t value, int &count, int &logarithm) { + if (value > static_cast(NTT_MAX_TRANSFORM_SIZE)) return false; + int candidate = 1; + int candidate_logarithm = 0; + while (static_cast(candidate) < value) { + candidate <<= 1; + candidate_logarithm++; + } + count = candidate; + logarithm = candidate_logarithm; + return true; +} + +inline void run_stages( + u64 *values, + const u64 *twiddles, + int count, + u64 modulus, + u64 mu, + cudaStream_t stream +) { + const int tile = count < SHARED_TILE_SIZE ? count : SHARED_TILE_SIZE; + fused_stages<<(tile), stream>>>( + values, + twiddles, + count, + tile, + modulus, + mu + ); + const int butterflies = (count / 2 + BLOCK_SIZE - 1) / BLOCK_SIZE; + for (int length = 2 * tile; length <= count; length <<= 1) { + butterfly<<>>( + values, + twiddles, + count, + length, + modulus, + mu + ); + } +} + +inline bool forward( + u64 *values, + const u64 *twiddles, + int count, + int logarithm, + u64 modulus, + u64 mu, + cudaStream_t stream +) { + bit_reverse<<<(count + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE, 0, stream>>>( + values, + count, + logarithm + ); + run_stages(values, twiddles, count, modulus, mu, stream); + return cudaGetLastError() == cudaSuccess; +} + +inline bool inverse( + u64 *values, + const u64 *twiddles, + int count, + int logarithm, + u64 modulus, + u64 mu, + cudaStream_t stream +) { + bit_reverse<<<(count + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE, 0, stream>>>( + values, + count, + logarithm + ); + run_stages(values, twiddles, count, modulus, mu, stream); + const u64 inverse_count = host_powmod(static_cast(count), modulus - 2, modulus); + scale<<<(count + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE, 0, stream>>>( + values, + count, + inverse_count, + modulus, + mu + ); + return cudaGetLastError() == cudaSuccess; +} + +} + +#endif diff --git a/src/main/cpp/cuda_runtime_state.cpp b/src/main/cpp/cuda_runtime_state.cpp index 0d8694b..7a0d1ef 100644 --- a/src/main/cpp/cuda_runtime_state.cpp +++ b/src/main/cpp/cuda_runtime_state.cpp @@ -16,6 +16,7 @@ #ifdef BIGMATH_HAS_CUDA #include "cuda_convolution.h" +#include "cuda_modular.h" #include "cuda_ntt.h" #include #endif @@ -141,7 +142,8 @@ RuntimeState probe_runtime(const RuntimeConfiguration &configuration) { fraction_bytes ); if (!configure_convolution_workspace_pool(selected, result.workspace_budget_bytes) || - !configure_ntt_workspace_pool(selected)) { + !configure_ntt_workspace_pool(selected) || + !configure_modular_workspace_pool(selected)) { result.available = false; result.active_backend = RuntimeBackend::CPU; calibration_status.store( @@ -448,6 +450,29 @@ DispatchDecision choose_dispatch(const DispatchRequest &request) { return decision; } +ModularOperationCosts modular_operation_costs(int transform_size) { + ModularOperationCosts costs; + if (!calibration_ready() || transform_size <= 0) return costs; + int logarithm = 0; + int candidate = transform_size; + while (candidate > 1 && (candidate & 1) == 0) { + candidate >>= 1; + logarithm++; + } + if (candidate != 1 || + logarithm >= static_cast(bigmath::runtime::CUDA_TRANSFORM_BUCKETS)) { + return costs; + } + std::lock_guard lock(state_mutex); + const bigmath::runtime::DispatchProfileCell &multiply = + state.calibration.cells[0][static_cast(logarithm)]; + const bigmath::runtime::DispatchProfileCell &square = + state.calibration.cells[4][static_cast(logarithm)]; + if (multiply.ntt_nanos != 0) costs.multiply_nanos = multiply.ntt_nanos; + if (square.ntt_nanos != 0) costs.square_nanos = square.ntt_nanos; + return costs; +} + int device_count() { return probe_state_snapshot().count; } @@ -521,12 +546,15 @@ int snapshot(BigmathRuntimeSnapshot *out) { 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(); + convolution_workspace_in_use_bytes() + ntt_workspace_in_use_bytes() + + modular_workspace_in_use_bytes(); out->workspace_capacity = static_cast( - convolution_workspace_capacity() + ntt_workspace_capacity() + convolution_workspace_capacity() + ntt_workspace_capacity() + + modular_workspace_capacity() ); out->workspace_in_use = static_cast( - convolution_workspace_in_use() + ntt_workspace_in_use() + convolution_workspace_in_use() + ntt_workspace_in_use() + + modular_workspace_in_use() ); } #endif diff --git a/src/main/cpp/cuda_runtime_state.h b/src/main/cpp/cuda_runtime_state.h index 56efef7..9d8ccd9 100644 --- a/src/main/cpp/cuda_runtime_state.h +++ b/src/main/cpp/cuda_runtime_state.h @@ -45,12 +45,18 @@ struct DispatchDecision { uint64_t max_queue_wait_nanos = 0; }; +struct ModularOperationCosts { + uint64_t multiply_nanos = 1; + uint64_t square_nanos = 1; +}; + bool configure(const RuntimeConfiguration &configuration); int initialize_async(); bool is_available(); bool calibration_ready(); RuntimeBackend active_backend(); DispatchDecision choose_dispatch(const DispatchRequest &request); +ModularOperationCosts modular_operation_costs(int transform_size); int device_count(); int device_id(); int probe_count();