IsPrime with cancellation token removed.

This commit is contained in:
mlemanczyk committed 2025-10-29 22:31:28 +01:00
1 parent f9504a6a19
commit fc5700f82c
11 files changed
+287 -314

No files matched your search

@@ -29,8 +29,7 @@ public class PrimeTesterBenchmarks
return; return;
} }
CancellationToken cancellationToken = CancellationToken.None; _ = _heuristicTester.IsPrimeCpu(_candidates[0]);
_ = _heuristicTester.IsPrimeCpu(_candidates[0], cancellationToken);
_ = _heuristicTester.IsPrimeGpu(_candidates[0]); _ = _heuristicTester.IsPrimeGpu(_candidates[0]);
_ = Prime.Numbers.IsPrime(_candidates[0]); _ = Prime.Numbers.IsPrime(_candidates[0]);
} }
@@ -40,12 +39,11 @@ public class PrimeTesterBenchmarks
{ {
HeuristicPrimeTester tester = _heuristicTester; HeuristicPrimeTester tester = _heuristicTester;
ulong[] values = _candidates; ulong[] values = _candidates;
CancellationToken cancellationToken = CancellationToken.None;
int primeCount = 0; int primeCount = 0;
for (int i = 0; i < values.Length; i++) for (int i = 0; i < values.Length; i++)
{ {
if (tester.IsPrimeCpu(values[i], cancellationToken)) if (tester.IsPrimeCpu(values[i]))
{ {
primeCount++; primeCount++;
} }
@@ -75,7 +73,6 @@ public class PrimeTesterBenchmarks
[Benchmark] [Benchmark]
public int HeuristicCombinedGpu() public int HeuristicCombinedGpu()
{ {
HeuristicCombinedPrimeTester tester = _heuristicCombinedTester;
ulong[] values = _candidates; ulong[] values = _candidates;
int primeCount = 0; int primeCount = 0;
@@ -93,7 +90,6 @@ public class PrimeTesterBenchmarks
[Benchmark] [Benchmark]
public int HeuristicCombinedCpu() public int HeuristicCombinedCpu()
{ {
HeuristicCombinedPrimeTester tester = _heuristicCombinedTester;
ulong[] values = _candidates; ulong[] values = _candidates;
int primeCount = 0; int primeCount = 0;
@@ -115,12 +111,11 @@ public class PrimeTesterBenchmarks
{ {
PrimeTester tester = _nonHeuristicTester; PrimeTester tester = _nonHeuristicTester;
ulong[] values = _candidates; ulong[] values = _candidates;
CancellationToken cancellationToken = CancellationToken.None;
int primeCount = 0; int primeCount = 0;
for (int i = 0; i < values.Length; i++) for (int i = 0; i < values.Length; i++)
{ {
if (tester.IsPrimeGpu(values[i], cancellationToken)) if (tester.IsPrimeGpu(values[i]))
{ {
primeCount++; primeCount++;
} }
@@ -133,12 +128,11 @@ public class PrimeTesterBenchmarks
public int NonHeuristicCpu() public int NonHeuristicCpu()
{ {
ulong[] values = _candidates; ulong[] values = _candidates;
CancellationToken cancellationToken = CancellationToken.None;
int primeCount = 0; int primeCount = 0;
for (int i = 0; i < values.Length; i++) for (int i = 0; i < values.Length; i++)
{ {
if (PrimeTester.IsPrimeCpu(values[i], cancellationToken)) if (PrimeTester.IsPrime(values[i]))
{ {
primeCount++; primeCount++;
} }
+1 -1
View File
@@ -55,7 +55,7 @@ public class ProgramTests
[InlineData(81UL, false)] [InlineData(81UL, false)]
public void IsPrime_identifies_primes_correctly(ulong n, bool expected) public void IsPrime_identifies_primes_correctly(ulong n, bool expected)
{ {
PrimeTester.IsPrime(n, CancellationToken.None).Should().Be(expected); PrimeTester.IsPrime(n).Should().Be(expected);
} }
[Fact] [Fact]
+2 -2
View File
@@ -622,8 +622,8 @@ internal static class Program
if (!_cliArguments.UseByDivisor) if (!_cliArguments.UseByDivisor)
{ {
if (!(GpuContextPool.ForceCpu if (!(GpuContextPool.ForceCpu
? PrimeTester.IsPrime(p, CancellationToken.None) ? PrimeTester.IsPrime(p)
: PrimeTesters.Value!.IsPrimeGpu(p, CancellationToken.None))) : PrimeTesters.Value!.IsPrimeGpu(p)))
{ {
_lastCompositeP = true; _lastCompositeP = true;
return false; return false;
@@ -17,7 +17,7 @@ public class PrimeTesterGpuTests
ulong[] primes = [31UL, 61UL, 89UL, 107UL, 127UL, 521UL]; ulong[] primes = [31UL, 61UL, 89UL, 107UL, 127UL, 521UL];
foreach (ulong prime in primes) foreach (ulong prime in primes)
{ {
tester.IsPrimeGpu(prime, CancellationToken.None).Should().BeTrue(); tester.IsPrimeGpu(prime).Should().BeTrue();
} }
} }
finally finally
@@ -37,7 +37,7 @@ public class PrimeTesterGpuTests
ulong[] composites = [33UL, 39UL, 51UL, 77UL, 91UL]; ulong[] composites = [33UL, 39UL, 51UL, 77UL, 91UL];
foreach (ulong composite in composites) foreach (ulong composite in composites)
{ {
tester.IsPrimeGpu(composite, CancellationToken.None).Should().BeFalse(); tester.IsPrimeGpu(composite).Should().BeFalse();
} }
} }
finally finally
@@ -26,7 +26,7 @@ public class PrimeTesterIsPrimeTests
{ {
var tester = new PrimeTester(); var tester = new PrimeTester();
PrimeTester.IsPrime(n, CancellationToken.None).Should().Be(expected); PrimeTester.IsPrime(n).Should().Be(expected);
} }
[Theory] [Theory]
@@ -40,7 +40,7 @@ public class PrimeTesterIsPrimeTests
GpuContextPool.ForceCpu = false; GpuContextPool.ForceCpu = false;
var tester = new PrimeTester(); var tester = new PrimeTester();
tester.IsPrimeGpu(n, CancellationToken.None).Should().Be(expected); tester.IsPrimeGpu(n).Should().Be(expected);
} }
[Fact] [Fact]
@@ -50,9 +50,9 @@ public class PrimeTesterIsPrimeTests
var tester = new PrimeTester(); var tester = new PrimeTester();
GpuContextPool.ForceCpu = true; GpuContextPool.ForceCpu = true;
tester.IsPrimeGpu(137UL, CancellationToken.None).Should().BeTrue(); tester.IsPrimeGpu(137UL).Should().BeTrue();
tester.IsPrimeGpu(341UL, CancellationToken.None).Should().BeFalse(); tester.IsPrimeGpu(341UL).Should().BeFalse();
GpuContextPool.ForceCpu = false; GpuContextPool.ForceCpu = false;
} }
@@ -71,7 +71,7 @@ public class PrimeTesterIsPrimeTests
var testers = new ThreadLocal<PrimeTester>(() => new PrimeTester(), trackAllValues: true); var testers = new ThreadLocal<PrimeTester>(() => new PrimeTester(), trackAllValues: true);
Parallel.For(0, primes.Length, i => Parallel.For(0, primes.Length, i =>
{ {
results[i] = testers.Value!.IsPrimeGpu(primes[i], CancellationToken.None); results[i] = testers.Value!.IsPrimeGpu(primes[i]);
}); });
results.Should().AllBeEquivalentTo(true); results.Should().AllBeEquivalentTo(true);
@@ -80,7 +80,7 @@ public class PrimeTesterIsPrimeTests
{ {
foreach (ulong prime in primes) foreach (ulong prime in primes)
{ {
testers.Value!.IsPrimeGpu(prime, CancellationToken.None).Should().BeTrue(); testers.Value!.IsPrimeGpu(prime).Should().BeTrue();
} }
}); });
} }
+1 -8
View File
@@ -77,10 +77,8 @@ public sealed class HeuristicPrimeTester
public static HeuristicPrimeTester Exclusive => _tester ??= new(); public static HeuristicPrimeTester Exclusive => _tester ??= new();
public bool IsPrimeCpu(ulong n, CancellationToken ct) public bool IsPrimeCpu(ulong n)
{ {
ct.ThrowIfCancellationRequested();
byte nMod10 = (byte)n.Mod10(); byte nMod10 = (byte)n.Mod10();
ulong maxDivisorSquare = ComputeHeuristicDivisorSquareLimit(n); ulong maxDivisorSquare = ComputeHeuristicDivisorSquareLimit(n);
@@ -93,11 +91,6 @@ public sealed class HeuristicPrimeTester
return HeuristicTrialDivisionCpu(n, maxDivisorSquare, nMod10, includeGroupB); return HeuristicTrialDivisionCpu(n, maxDivisorSquare, nMod10, includeGroupB);
} }
public bool IsPrimeCpu(ulong n)
{
return IsPrimeCpu(n, CancellationToken.None);
}
public bool IsPrimeGpu(ulong n) public bool IsPrimeGpu(ulong n)
{ {
byte nMod10 = (byte)n.Mod10(); byte nMod10 = (byte)n.Mod10();
+7 -7
View File
@@ -411,8 +411,8 @@ public class MersenneDivisorCycles
// Atomic.Add(ref _tryFactorIntoCountsInternalHits, 1UL); // Atomic.Add(ref _tryFactorIntoCountsInternalHits, 1UL);
// Console.WriteLine($"MersenneDivisorCycles.TryFactorIntoCountsInternal hits {Volatile.Read(ref _tryFactorIntoCountsInternalHits)}"); // Console.WriteLine($"MersenneDivisorCycles.TryFactorIntoCountsInternal hits {Volatile.Read(ref _tryFactorIntoCountsInternalHits)}");
HeuristicPrimeTester primeTester = _primeTester ??= new(); // HeuristicPrimeTester primeTester = _primeTester ??= new();
if (primeTester.IsPrimeGpu(remaining)) if (PrimeTester.IsPrime(remaining))
// if (PrimeTester.IsPrimeCpu(remaining, CancellationToken.None)) // if (PrimeTester.IsPrimeCpu(remaining, CancellationToken.None))
{ {
AddFactor(counts, remaining); AddFactor(counts, remaining);
@@ -917,8 +917,8 @@ public class MersenneDivisorCycles
return CalculateCycleLengthFallback(divisor); return CalculateCycleLengthFallback(divisor);
} }
[ThreadStatic] // [ThreadStatic]
private static HeuristicPrimeTester? _primeTester; // private static HeuristicPrimeTester? _primeTester;
internal static bool TryCalculateCycleLengthHeuristic(ulong divisor, in MontgomeryDivisorData divisorData, out ulong cycleLength, bool skipPrimeOrderHeuristic = false) internal static bool TryCalculateCycleLengthHeuristic(ulong divisor, in MontgomeryDivisorData divisorData, out ulong cycleLength, bool skipPrimeOrderHeuristic = false)
{ {
@@ -940,10 +940,10 @@ public class MersenneDivisorCycles
// Console.WriteLine($"MersenneDivisorCycles.CalculateCycleLengthFallback hits {Volatile.Read(ref _tryCalculateCycleLengthHeuristicHits)}"); // Console.WriteLine($"MersenneDivisorCycles.CalculateCycleLengthFallback hits {Volatile.Read(ref _tryCalculateCycleLengthHeuristicHits)}");
// } // }
HeuristicPrimeTester primeTester = _primeTester ??= new(); // HeuristicPrimeTester primeTester = _primeTester ??= new();
// if (!skipPrimeOrderHeuristic && HeuristicPrimeTester.Exclusive.IsPrimeCpu(divisor, CancellationToken.None)) // if (!skipPrimeOrderHeuristic && HeuristicPrimeTester.Exclusive.IsPrimeCpu(divisor, CancellationToken.None))
if (!skipPrimeOrderHeuristic && primeTester.IsPrimeGpu(divisor)) // if (!skipPrimeOrderHeuristic && primeTester.IsPrimeGpu(divisor))
// if (!skipPrimeOrderHeuristic && PrimeTester.IsPrimeCpu(divisor, CancellationToken.None)) if (!skipPrimeOrderHeuristic && PrimeTester.IsPrime(divisor))
{ {
ulong computedOrder = PrimeOrderCalculator.Calculate( ulong computedOrder = PrimeOrderCalculator.Calculate(
divisor, divisor,
@@ -34,7 +34,7 @@ public static class MersennePrimeFactorTester
// Atomic.Add(ref _isPrimeFactorHits, 1UL); // Atomic.Add(ref _isPrimeFactorHits, 1UL);
// Console.WriteLine($"MersennePrimeFactorTester.IsPrimeFactor hits {Volatile.Read(ref _isPrimeFactorHits)}"); // Console.WriteLine($"MersennePrimeFactorTester.IsPrimeFactor hits {Volatile.Read(ref _isPrimeFactorHits)}");
if (!PrimeTester.IsPrimeCpu(q, ct)) if (!PrimeTester.IsPrime(q))
{ {
return false; return false;
} }
@@ -247,7 +247,7 @@ public static class MersennePrimeFactorTester
// Console.WriteLine($"MersennePrimeFactorTester.Factor64 hits {Volatile.Read(ref _factor64Hits)}"); // Console.WriteLine($"MersennePrimeFactorTester.Factor64 hits {Volatile.Read(ref _factor64Hits)}");
// if (HeuristicPrimeTester.Exclusive.IsPrime(m, ct)) // if (HeuristicPrimeTester.Exclusive.IsPrime(m, ct))
if (PrimeTester.IsPrimeCpu(m, ct)) if (PrimeTester.IsPrime(m))
{ {
dict[m] = 1; dict[m] = 1;
continue; continue;
+10 -10
View File
@@ -1079,7 +1079,7 @@ internal static partial class PrimeOrderCalculator
PartialFactorResult result; PartialFactorResult result;
PrimeTester primeTester = PrimeTester.Exclusive; PrimeTester primeTester = PrimeTester.Exclusive;
CancellationToken ct = CancellationToken.None; CancellationToken ct = CancellationToken.None;
HeuristicPrimeTester? tester = _tester ??= new(); // HeuristicPrimeTester? tester = _tester ??= new();
if (!gpuFactored) if (!gpuFactored)
{ {
@@ -1152,7 +1152,7 @@ internal static partial class PrimeOrderCalculator
// Console.WriteLine($"Partial factor hits {Volatile.Read(ref _partialFactorHits)}"); // Console.WriteLine($"Partial factor hits {Volatile.Read(ref _partialFactorHits)}");
// bool isPrime = PrimeTester.IsPrimeCpu(composite, CancellationToken.None); // bool isPrime = PrimeTester.IsPrimeCpu(composite, CancellationToken.None);
bool isPrime = tester.IsPrimeGpu(composite); bool isPrime = PrimeTester.IsPrime(composite);
// bool isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(composite); // bool isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(composite);
if (isPrime) if (isPrime)
@@ -1220,7 +1220,7 @@ internal static partial class PrimeOrderCalculator
// Console.WriteLine($"Partial factor pending hits {Volatile.Read(ref _partialFactorPendingHits)}"); // Console.WriteLine($"Partial factor pending hits {Volatile.Read(ref _partialFactorPendingHits)}");
// bool isPrime = PrimeTester.IsPrimeCpu(composite, CancellationToken.None); // bool isPrime = PrimeTester.IsPrimeCpu(composite, CancellationToken.None);
bool isPrime = tester.IsPrimeGpu(composite); bool isPrime = PrimeTester.IsPrime(composite);
// bool isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(composite); // bool isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(composite);
entry = entry.WithPrimality(isPrime); entry = entry.WithPrimality(isPrime);
@@ -1257,7 +1257,7 @@ internal static partial class PrimeOrderCalculator
// Atomic.Add(ref _partialFactorCofactorHits, 1UL); // Atomic.Add(ref _partialFactorCofactorHits, 1UL);
// Console.WriteLine($"Partial factor cofactor hits {Volatile.Read(ref _partialFactorCofactorHits)}"); // Console.WriteLine($"Partial factor cofactor hits {Volatile.Read(ref _partialFactorCofactorHits)}");
cofactorIsPrime = tester.IsPrimeGpu(cofactor); cofactorIsPrime = PrimeTester.IsPrime(cofactor);
// cofactorIsPrime = PrimeTester.IsPrimeGpu(cofactor); // cofactorIsPrime = PrimeTester.IsPrimeGpu(cofactor);
// cofactorIsPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(cofactor); // cofactorIsPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(cofactor);
} }
@@ -1782,8 +1782,8 @@ internal static partial class PrimeOrderCalculator
// private static ulong _factorCompletelyHits; // private static ulong _factorCompletelyHits;
// private static ulong _factorCompletelyPollardRhoHits; // private static ulong _factorCompletelyPollardRhoHits;
[ThreadStatic] // [ThreadStatic]
private static HeuristicPrimeTester? _tester; // private static HeuristicPrimeTester? _tester;
private static void FactorCompletely(ulong value, Dictionary<ulong, int> counts, bool knownComposite) private static void FactorCompletely(ulong value, Dictionary<ulong, int> counts, bool knownComposite)
{ {
@@ -1794,10 +1794,10 @@ internal static partial class PrimeOrderCalculator
// Atomic.Add(ref _factorCompletelyHits, 1UL); // Atomic.Add(ref _factorCompletelyHits, 1UL);
// Console.WriteLine($"Factor completely hits {Volatile.Read(ref _factorCompletelyHits)}"); // Console.WriteLine($"Factor completely hits {Volatile.Read(ref _factorCompletelyHits)}");
HeuristicPrimeTester tester = _tester ??= new(); // HeuristicPrimeTester tester = _tester ??= new();
// bool isPrime = primeTester.HeuristicIsPrimeGpu(value); // bool isPrime = primeTester.HeuristicIsPrimeGpu(value);
bool isPrime = tester.IsPrimeGpu(value); bool isPrime = PrimeTester.IsPrime(value);
// bool isPrime = PrimeTester.IsPrimeGpu(value); // bool isPrime = PrimeTester.IsPrimeGpu(value);
// bool isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(value); // bool isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(value);
if (!knownComposite && isPrime) if (!knownComposite && isPrime)
@@ -1813,7 +1813,7 @@ internal static partial class PrimeOrderCalculator
// Console.WriteLine($"Factor completely after PollardRho hits {Volatile.Read(ref _factorCompletelyPollardRhoHits)}"); // Console.WriteLine($"Factor completely after PollardRho hits {Volatile.Read(ref _factorCompletelyPollardRhoHits)}");
// isPrime = primeTester.HeuristicIsPrimeGpu(factor); // isPrime = primeTester.HeuristicIsPrimeGpu(factor);
isPrime = tester.IsPrimeGpu(factor); isPrime = PrimeTester.IsPrime(factor);
// isPrime = PrimeTester.IsPrimeGpu(factor); // isPrime = PrimeTester.IsPrimeGpu(factor);
// isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(factor); // isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(factor);
if (isPrime) if (isPrime)
@@ -1850,7 +1850,7 @@ internal static partial class PrimeOrderCalculator
// Atomic.Add(ref _partialFactorCofactorHits, 1UL); // Atomic.Add(ref _partialFactorCofactorHits, 1UL);
// Console.WriteLine($"Partial factor cofactor hits {Volatile.Read(ref _partialFactorCofactorHits)}"); // Console.WriteLine($"Partial factor cofactor hits {Volatile.Read(ref _partialFactorCofactorHits)}");
isPrime = tester.IsPrimeGpu(quotient); isPrime = PrimeTester.IsPrime(quotient);
// isPrime = PrimeTester.IsPrimeGpu(quotient); // isPrime = PrimeTester.IsPrimeGpu(quotient);
// isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(quotient); // isPrime = Open.Numeric.Primes.Prime.Numbers.IsPrime(quotient);
} }
@@ -950,7 +950,7 @@ internal static partial class PrimeOrderCalculator
if (value <= ulong.MaxValue) if (value <= ulong.MaxValue)
{ {
// return HeuristicPrimeTester.Exclusive.IsPrimeCpu((ulong)value, CancellationToken.None); // return HeuristicPrimeTester.Exclusive.IsPrimeCpu((ulong)value, CancellationToken.None);
return PrimeTester.IsPrimeCpu((ulong)value, CancellationToken.None); return PrimeTester.IsPrime((ulong)value);
} }
if ((value & UInt128.One) == UInt128.Zero) if ((value & UInt128.One) == UInt128.Zero)
+251 -265
View File
@@ -1,7 +1,5 @@
using System;
using System.Buffers; using System.Buffers;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@@ -22,7 +20,7 @@ public sealed class PrimeTester
public static PrimeTester Exclusive => _tester ??= new(); public static PrimeTester Exclusive => _tester ??= new();
public static bool IsPrime(ulong n, CancellationToken ct) public static bool IsPrime(ulong n)
{ {
if (n <= 1UL) if (n <= 1UL)
{ {
@@ -92,310 +90,298 @@ public sealed class PrimeTester
return result; return result;
} }
public static bool IsPrimeGpu(ulong n)
{
return Exclusive.IsPrimeGpu(n, CancellationToken.None);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsPrimeGpu(ulong n, CancellationToken ct) public bool IsPrimeGpu(ulong n)
{
bool forceCpu = GpuContextPool.ForceCpu;
bool belowGpuRange = n < 31UL;
if (forceCpu || belowGpuRange)
{
return IsPrimeCpu(n, ct);
}
var limiter = GpuPrimeWorkLimiter.Acquire();
var gpu = PrimeTesterGpuContextPool.Rent(1);
var accelerator = gpu.Accelerator;
var kernel = gpu.Kernel;
ulong value = n;
byte flag = 0;
var input = gpu.Input;
var output = gpu.Output;
var inputView = input.View;
var outputView = output.View;
inputView.CopyFromCPU(ref value, 1);
kernel(
1,
inputView,
gpu.DevicePrimesDefault.View,
gpu.DevicePrimesLastOne.View,
gpu.DevicePrimesLastSeven.View,
gpu.DevicePrimesLastThree.View,
gpu.DevicePrimesLastNine.View,
gpu.DevicePrimesPow2Default.View,
gpu.DevicePrimesPow2LastOne.View,
gpu.DevicePrimesPow2LastSeven.View,
gpu.DevicePrimesPow2LastThree.View,
gpu.DevicePrimesPow2LastNine.View,
outputView);
accelerator.Synchronize();
outputView.CopyToCPU(ref flag, 1);
gpu.Dispose();
limiter.Dispose();
return flag != 0;
}
public static bool IsPrimeCpu(ulong n, CancellationToken ct)
{ {
// Preserve the legacy entry point for callers that bypass the thread-local caches. bool forceCpu = GpuContextPool.ForceCpu;
return IsPrime(n, ct); bool belowGpuRange = n < 31UL;
}
if (forceCpu || belowGpuRange)
{
return IsPrime(n);
}
var limiter = GpuPrimeWorkLimiter.Acquire();
var gpu = PrimeTesterGpuContextPool.Rent(1);
var accelerator = gpu.Accelerator;
var kernel = gpu.Kernel;
ulong value = n;
byte flag = 0;
var input = gpu.Input;
var output = gpu.Output;
var inputView = input.View;
var outputView = output.View;
inputView.CopyFromCPU(ref value, 1);
kernel(
1,
inputView,
gpu.DevicePrimesDefault.View,
gpu.DevicePrimesLastOne.View,
gpu.DevicePrimesLastSeven.View,
gpu.DevicePrimesLastThree.View,
gpu.DevicePrimesLastNine.View,
gpu.DevicePrimesPow2Default.View,
gpu.DevicePrimesPow2LastOne.View,
gpu.DevicePrimesPow2LastSeven.View,
gpu.DevicePrimesPow2LastThree.View,
gpu.DevicePrimesPow2LastNine.View,
outputView);
accelerator.Synchronize();
outputView.CopyToCPU(ref flag, 1);
gpu.Dispose();
limiter.Dispose();
return flag != 0;
}
public static int GpuBatchSize { get; set; } = 262_144; public static int GpuBatchSize { get; set; } = 262_144;
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsPrimeBatchGpu(ReadOnlySpan<ulong> values, Span<byte> results) public static void IsPrimeBatchGpu(ReadOnlySpan<ulong> values, Span<byte> results)
{ {
var limiter = GpuPrimeWorkLimiter.Acquire(); var limiter = GpuPrimeWorkLimiter.Acquire();
var gpu = PrimeTesterGpuContextPool.Rent(GpuBatchSize); var gpu = PrimeTesterGpuContextPool.Rent(GpuBatchSize);
var accelerator = gpu.Accelerator; var accelerator = gpu.Accelerator;
var kernel = gpu.Kernel; var kernel = gpu.Kernel;
int totalLength = values.Length; int totalLength = values.Length;
int batchSize = GpuBatchSize; int batchSize = GpuBatchSize;
var input = gpu.Input; var input = gpu.Input;
var output = gpu.Output; var output = gpu.Output;
var inputView = input.View; var inputView = input.View;
var outputView = output.View; var outputView = output.View;
int pos = 0; int pos = 0;
while (pos < totalLength) while (pos < totalLength)
{ {
int remaining = totalLength - pos; int remaining = totalLength - pos;
int count = remaining > batchSize ? batchSize : remaining; int count = remaining > batchSize ? batchSize : remaining;
var valueSlice = values.Slice(pos, count); var valueSlice = values.Slice(pos, count);
ref ulong valueRef = ref MemoryMarshal.GetReference(valueSlice); ref ulong valueRef = ref MemoryMarshal.GetReference(valueSlice);
inputView.CopyFromCPU(ref valueRef, count); inputView.CopyFromCPU(ref valueRef, count);
kernel( kernel(
count, count,
inputView, inputView,
gpu.DevicePrimesDefault.View, gpu.DevicePrimesDefault.View,
gpu.DevicePrimesLastOne.View, gpu.DevicePrimesLastOne.View,
gpu.DevicePrimesLastSeven.View, gpu.DevicePrimesLastSeven.View,
gpu.DevicePrimesLastThree.View, gpu.DevicePrimesLastThree.View,
gpu.DevicePrimesLastNine.View, gpu.DevicePrimesLastNine.View,
gpu.DevicePrimesPow2Default.View, gpu.DevicePrimesPow2Default.View,
gpu.DevicePrimesPow2LastOne.View, gpu.DevicePrimesPow2LastOne.View,
gpu.DevicePrimesPow2LastSeven.View, gpu.DevicePrimesPow2LastSeven.View,
gpu.DevicePrimesPow2LastThree.View, gpu.DevicePrimesPow2LastThree.View,
gpu.DevicePrimesPow2LastNine.View, gpu.DevicePrimesPow2LastNine.View,
outputView); outputView);
accelerator.Synchronize(); accelerator.Synchronize();
var resultSlice = results.Slice(pos, count); var resultSlice = results.Slice(pos, count);
ref byte resultRef = ref MemoryMarshal.GetReference(resultSlice); ref byte resultRef = ref MemoryMarshal.GetReference(resultSlice);
outputView.CopyToCPU(ref resultRef, count); outputView.CopyToCPU(ref resultRef, count);
pos += count; pos += count;
} }
gpu.Dispose(); gpu.Dispose();
limiter.Dispose(); limiter.Dispose();
} }
internal static class PrimeTesterGpuContextPool internal static class PrimeTesterGpuContextPool
{ {
private static readonly ConcurrentQueue<PrimeTesterGpuContextLease> Pool = new(); private static readonly ConcurrentQueue<PrimeTesterGpuContextLease> Pool = new();
internal static PrimeTesterGpuContextLease Rent(int minBufferCapacity = 1) internal static PrimeTesterGpuContextLease Rent(int minBufferCapacity = 1)
{ {
if (!Pool.TryDequeue(out var lease)) if (!Pool.TryDequeue(out var lease))
{ {
lease = new PrimeTesterGpuContextLease(minBufferCapacity); lease = new PrimeTesterGpuContextLease(minBufferCapacity);
} }
else else
{ {
lease.EnsureCapacity(minBufferCapacity); lease.EnsureCapacity(minBufferCapacity);
} }
lease.ResetReturnFlag(); lease.ResetReturnFlag();
return lease; return lease;
} }
internal static void Return(PrimeTesterGpuContextLease lease) internal static void Return(PrimeTesterGpuContextLease lease)
{ {
lease.Accelerator.Synchronize(); lease.Accelerator.Synchronize();
Pool.Enqueue(lease); Pool.Enqueue(lease);
} }
internal static void DisposeAll() internal static void DisposeAll()
{ {
while (Pool.TryDequeue(out var lease)) while (Pool.TryDequeue(out var lease))
{ {
lease.DisposeResources(); lease.DisposeResources();
} }
} }
internal static void Clear(Accelerator accelerator) internal static void Clear(Accelerator accelerator)
{ {
if (accelerator is null) if (accelerator is null)
{ {
return; return;
} }
var retained = new List<PrimeTesterGpuContextLease>(); var retained = new List<PrimeTesterGpuContextLease>();
while (Pool.TryDequeue(out var lease)) while (Pool.TryDequeue(out var lease))
{ {
if (lease.Accelerator == accelerator) if (lease.Accelerator == accelerator)
{ {
lease.DisposeResources(); lease.DisposeResources();
} }
else else
{ {
retained.Add(lease); retained.Add(lease);
} }
} }
int retainedCount = retained.Count; int retainedCount = retained.Count;
for (int i = 0; i < retainedCount; i++) for (int i = 0; i < retainedCount; i++)
{ {
Pool.Enqueue(retained[i]); Pool.Enqueue(retained[i]);
} }
} }
internal sealed class PrimeTesterGpuContextLease : IDisposable internal sealed class PrimeTesterGpuContextLease : IDisposable
{ {
private bool _returned; private bool _returned;
internal readonly Context AcceleratorContext; internal readonly Context AcceleratorContext;
public readonly Accelerator Accelerator; public readonly Accelerator Accelerator;
public readonly Action<Index1D, ArrayView<ulong>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<byte>> Kernel; public readonly Action<Index1D, ArrayView<ulong>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<byte>> Kernel;
public readonly Action<Index1D, ArrayView<ulong>, ulong, ArrayView<int>> HeuristicTrialDivisionKernel; public readonly Action<Index1D, ArrayView<ulong>, ulong, ArrayView<int>> HeuristicTrialDivisionKernel;
public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesDefault; public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesDefault;
public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesLastOne; public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesLastOne;
public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesLastSeven; public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesLastSeven;
public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesLastThree; public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesLastThree;
public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesLastNine; public readonly MemoryBuffer1D<uint, Stride1D.Dense> DevicePrimesLastNine;
public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2Default; public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2Default;
public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2LastOne; public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2LastOne;
public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2LastSeven; public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2LastSeven;
public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2LastThree; public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2LastThree;
public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2LastNine; public readonly MemoryBuffer1D<ulong, Stride1D.Dense> DevicePrimesPow2LastNine;
public MemoryBuffer1D<ulong, Stride1D.Dense> Input; public MemoryBuffer1D<ulong, Stride1D.Dense> Input;
public MemoryBuffer1D<byte, Stride1D.Dense> Output; public MemoryBuffer1D<byte, Stride1D.Dense> Output;
public MemoryBuffer1D<int, Stride1D.Dense> HeuristicFlag; public MemoryBuffer1D<int, Stride1D.Dense> HeuristicFlag;
public int BufferCapacity; public int BufferCapacity;
internal PrimeTesterGpuContextLease(int minBufferCapacity) internal PrimeTesterGpuContextLease(int minBufferCapacity)
{ {
AcceleratorContext = Context.CreateDefault(); AcceleratorContext = Context.CreateDefault();
Accelerator = AcceleratorContext.GetPreferredDevice(false).CreateAccelerator(AcceleratorContext); Accelerator = AcceleratorContext.GetPreferredDevice(false).CreateAccelerator(AcceleratorContext);
Kernel = Accelerator.LoadAutoGroupedStreamKernel<Index1D, ArrayView<ulong>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<byte>>(PrimeTesterKernels.SmallPrimeSieveKernel); Kernel = Accelerator.LoadAutoGroupedStreamKernel<Index1D, ArrayView<ulong>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<uint>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<ulong>, ArrayView<byte>>(PrimeTesterKernels.SmallPrimeSieveKernel);
HeuristicTrialDivisionKernel = Accelerator.LoadAutoGroupedStreamKernel<Index1D, ArrayView<ulong>, ulong, ArrayView<int>>(PrimeTesterKernels.HeuristicTrialDivisionKernel); HeuristicTrialDivisionKernel = Accelerator.LoadAutoGroupedStreamKernel<Index1D, ArrayView<ulong>, ulong, ArrayView<int>>(PrimeTesterKernels.HeuristicTrialDivisionKernel);
var primesDefault = DivisorGenerator.SmallPrimes; var primesDefault = DivisorGenerator.SmallPrimes;
DevicePrimesDefault = Accelerator.Allocate1D<uint>(primesDefault.Length); DevicePrimesDefault = Accelerator.Allocate1D<uint>(primesDefault.Length);
DevicePrimesDefault.View.CopyFromCPU(primesDefault); DevicePrimesDefault.View.CopyFromCPU(primesDefault);
var primesLastOne = DivisorGenerator.SmallPrimesLastOne; var primesLastOne = DivisorGenerator.SmallPrimesLastOne;
DevicePrimesLastOne = Accelerator.Allocate1D<uint>(primesLastOne.Length); DevicePrimesLastOne = Accelerator.Allocate1D<uint>(primesLastOne.Length);
DevicePrimesLastOne.View.CopyFromCPU(primesLastOne); DevicePrimesLastOne.View.CopyFromCPU(primesLastOne);
var primesLastSeven = DivisorGenerator.SmallPrimesLastSeven; var primesLastSeven = DivisorGenerator.SmallPrimesLastSeven;
DevicePrimesLastSeven = Accelerator.Allocate1D<uint>(primesLastSeven.Length); DevicePrimesLastSeven = Accelerator.Allocate1D<uint>(primesLastSeven.Length);
DevicePrimesLastSeven.View.CopyFromCPU(primesLastSeven); DevicePrimesLastSeven.View.CopyFromCPU(primesLastSeven);
var primesLastThree = DivisorGenerator.SmallPrimesLastThree; var primesLastThree = DivisorGenerator.SmallPrimesLastThree;
DevicePrimesLastThree = Accelerator.Allocate1D<uint>(primesLastThree.Length); DevicePrimesLastThree = Accelerator.Allocate1D<uint>(primesLastThree.Length);
DevicePrimesLastThree.View.CopyFromCPU(primesLastThree); DevicePrimesLastThree.View.CopyFromCPU(primesLastThree);
var primesLastNine = DivisorGenerator.SmallPrimesLastNine; var primesLastNine = DivisorGenerator.SmallPrimesLastNine;
DevicePrimesLastNine = Accelerator.Allocate1D<uint>(primesLastNine.Length); DevicePrimesLastNine = Accelerator.Allocate1D<uint>(primesLastNine.Length);
DevicePrimesLastNine.View.CopyFromCPU(primesLastNine); DevicePrimesLastNine.View.CopyFromCPU(primesLastNine);
var primesPow2Default = DivisorGenerator.SmallPrimesPow2; var primesPow2Default = DivisorGenerator.SmallPrimesPow2;
DevicePrimesPow2Default = Accelerator.Allocate1D<ulong>(primesPow2Default.Length); DevicePrimesPow2Default = Accelerator.Allocate1D<ulong>(primesPow2Default.Length);
DevicePrimesPow2Default.View.CopyFromCPU(primesPow2Default); DevicePrimesPow2Default.View.CopyFromCPU(primesPow2Default);
var primesPow2LastOne = DivisorGenerator.SmallPrimesPow2LastOne; var primesPow2LastOne = DivisorGenerator.SmallPrimesPow2LastOne;
DevicePrimesPow2LastOne = Accelerator.Allocate1D<ulong>(primesPow2LastOne.Length); DevicePrimesPow2LastOne = Accelerator.Allocate1D<ulong>(primesPow2LastOne.Length);
DevicePrimesPow2LastOne.View.CopyFromCPU(primesPow2LastOne); DevicePrimesPow2LastOne.View.CopyFromCPU(primesPow2LastOne);
var primesPow2LastSeven = DivisorGenerator.SmallPrimesPow2LastSeven; var primesPow2LastSeven = DivisorGenerator.SmallPrimesPow2LastSeven;
DevicePrimesPow2LastSeven = Accelerator.Allocate1D<ulong>(primesPow2LastSeven.Length); DevicePrimesPow2LastSeven = Accelerator.Allocate1D<ulong>(primesPow2LastSeven.Length);
DevicePrimesPow2LastSeven.View.CopyFromCPU(primesPow2LastSeven); DevicePrimesPow2LastSeven.View.CopyFromCPU(primesPow2LastSeven);
var primesPow2LastThree = DivisorGenerator.SmallPrimesPow2LastThree; var primesPow2LastThree = DivisorGenerator.SmallPrimesPow2LastThree;
DevicePrimesPow2LastThree = Accelerator.Allocate1D<ulong>(primesPow2LastThree.Length); DevicePrimesPow2LastThree = Accelerator.Allocate1D<ulong>(primesPow2LastThree.Length);
DevicePrimesPow2LastThree.View.CopyFromCPU(primesPow2LastThree); DevicePrimesPow2LastThree.View.CopyFromCPU(primesPow2LastThree);
var primesPow2LastNine = DivisorGenerator.SmallPrimesPow2LastNine; var primesPow2LastNine = DivisorGenerator.SmallPrimesPow2LastNine;
DevicePrimesPow2LastNine = Accelerator.Allocate1D<ulong>(primesPow2LastNine.Length); DevicePrimesPow2LastNine = Accelerator.Allocate1D<ulong>(primesPow2LastNine.Length);
DevicePrimesPow2LastNine.View.CopyFromCPU(primesPow2LastNine); DevicePrimesPow2LastNine.View.CopyFromCPU(primesPow2LastNine);
BufferCapacity = minBufferCapacity < 1 ? 1 : minBufferCapacity; BufferCapacity = minBufferCapacity < 1 ? 1 : minBufferCapacity;
Input = Accelerator.Allocate1D<ulong>(BufferCapacity); Input = Accelerator.Allocate1D<ulong>(BufferCapacity);
Output = Accelerator.Allocate1D<byte>(BufferCapacity); Output = Accelerator.Allocate1D<byte>(BufferCapacity);
HeuristicFlag = Accelerator.Allocate1D<int>(BufferCapacity); HeuristicFlag = Accelerator.Allocate1D<int>(BufferCapacity);
_returned = false; _returned = false;
} }
public void EnsureCapacity(int minCapacity) public void EnsureCapacity(int minCapacity)
{ {
int required = minCapacity < 1 ? 1 : minCapacity; int required = minCapacity < 1 ? 1 : minCapacity;
if (required <= BufferCapacity) if (required <= BufferCapacity)
{ {
return; return;
} }
Input.Dispose(); Input.Dispose();
Output.Dispose(); Output.Dispose();
HeuristicFlag.Dispose(); HeuristicFlag.Dispose();
Input = Accelerator.Allocate1D<ulong>(required); Input = Accelerator.Allocate1D<ulong>(required);
Output = Accelerator.Allocate1D<byte>(required); Output = Accelerator.Allocate1D<byte>(required);
HeuristicFlag = Accelerator.Allocate1D<int>(required); HeuristicFlag = Accelerator.Allocate1D<int>(required);
BufferCapacity = required; BufferCapacity = required;
} }
internal void ResetReturnFlag() internal void ResetReturnFlag()
{ {
_returned = false; _returned = false;
} }
public void Dispose() public void Dispose()
{ {
if (_returned) if (_returned)
{ {
return; return;
} }
_returned = true; _returned = true;
PrimeTesterGpuContextPool.Return(this); PrimeTesterGpuContextPool.Return(this);
} }
internal void DisposeResources() internal void DisposeResources()
{ {
Input.Dispose(); Input.Dispose();
Output.Dispose(); Output.Dispose();
HeuristicFlag.Dispose(); HeuristicFlag.Dispose();
DevicePrimesDefault.Dispose(); DevicePrimesDefault.Dispose();
DevicePrimesLastOne.Dispose(); DevicePrimesLastOne.Dispose();
DevicePrimesLastSeven.Dispose(); DevicePrimesLastSeven.Dispose();
DevicePrimesLastThree.Dispose(); DevicePrimesLastThree.Dispose();
DevicePrimesLastNine.Dispose(); DevicePrimesLastNine.Dispose();
DevicePrimesPow2Default.Dispose(); DevicePrimesPow2Default.Dispose();
DevicePrimesPow2LastOne.Dispose(); DevicePrimesPow2LastOne.Dispose();
DevicePrimesPow2LastSeven.Dispose(); DevicePrimesPow2LastSeven.Dispose();
DevicePrimesPow2LastThree.Dispose(); DevicePrimesPow2LastThree.Dispose();
DevicePrimesPow2LastNine.Dispose(); DevicePrimesPow2LastNine.Dispose();
Accelerator.Dispose(); Accelerator.Dispose();
AcceleratorContext.Dispose(); AcceleratorContext.Dispose();
} }
} }
} }
// Expose cache clearing for accelerator disposal coordination // Expose cache clearing for accelerator disposal coordination
public static void ClearGpuCaches(Accelerator accelerator) public static void ClearGpuCaches(Accelerator accelerator)
{ {
PrimeTesterGpuContextPool.Clear(accelerator); PrimeTesterGpuContextPool.Clear(accelerator);