--gpu-ration command-line argument added. AscendingDivisorRemainderStepper implemented in PrimeTester.IsPrimeCpu. PrimeOrderCalculator.RunOnCpu adjusted for low GPU ratios to prevent infinite increase of the counter.

This commit is contained in:
mlemanczyk committed 2025-12-02 23:36:18 +01:00
1 parent f43c67c86f
commit 85a90c70bf
9 files changed
+297 -213

No files matched your search

+24 -12
View File
@@ -51,8 +51,9 @@ internal readonly struct CliArguments
internal readonly double ZeroFractionConjecture; internal readonly double ZeroFractionConjecture;
internal readonly int MaxZeroConjecture; internal readonly int MaxZeroConjecture;
internal readonly ulong MinK; internal readonly ulong MinK;
internal readonly int GpuRatio;
private CliArguments( private CliArguments(
ulong startPrime, ulong startPrime,
bool startPrimeProvided, bool startPrimeProvided,
UInt128 maxPrimeLimit, UInt128 maxPrimeLimit,
@@ -95,7 +96,8 @@ internal readonly struct CliArguments
double zeroFractionHard, double zeroFractionHard,
double zeroFractionConjecture, double zeroFractionConjecture,
int maxZeroConjecture, int maxZeroConjecture,
ulong minK) ulong minK,
int gpuRatio)
{ {
StartPrime = startPrime; StartPrime = startPrime;
StartPrimeProvided = startPrimeProvided; StartPrimeProvided = startPrimeProvided;
@@ -140,6 +142,7 @@ internal readonly struct CliArguments
ZeroFractionConjecture = zeroFractionConjecture; ZeroFractionConjecture = zeroFractionConjecture;
MaxZeroConjecture = maxZeroConjecture; MaxZeroConjecture = maxZeroConjecture;
MinK = minK; MinK = minK;
GpuRatio = gpuRatio;
} }
internal bool UseFilter => !TestMode && !string.IsNullOrEmpty(FilterFile); internal bool UseFilter => !TestMode && !string.IsNullOrEmpty(FilterFile);
@@ -189,6 +192,7 @@ internal readonly struct CliArguments
double zeroFractionConjecture = -1.0; double zeroFractionConjecture = -1.0;
int maxZeroConjecture = -1; int maxZeroConjecture = -1;
ulong minK = 1UL; ulong minK = 1UL;
int gpuRatio = PerfectNumberConstants.GpuRatio;
foreach (string argument in args) foreach (string argument in args)
{ {
@@ -239,6 +243,12 @@ internal readonly struct CliArguments
continue; continue;
} }
if (argument.StartsWith("--gpu-ratio=", StringComparison.OrdinalIgnoreCase))
{
gpuRatio = Math.Max(1, Utf8CliParser.ParseInt32(argument.AsSpan("--gpu-ratio=".Length)));
continue;
}
if (argument.StartsWith("--threads=", StringComparison.OrdinalIgnoreCase)) if (argument.StartsWith("--threads=", StringComparison.OrdinalIgnoreCase))
{ {
threadCount = Math.Max(1, Utf8CliParser.ParseInt32(argument.AsSpan("--threads=".Length))); threadCount = Math.Max(1, Utf8CliParser.ParseInt32(argument.AsSpan("--threads=".Length)));
@@ -590,7 +600,8 @@ internal readonly struct CliArguments
zeroFractionHard, zeroFractionHard,
zeroFractionConjecture, zeroFractionConjecture,
maxZeroConjecture, maxZeroConjecture,
minK); minK,
gpuRatio);
} }
internal static void PrintHelp() internal static void PrintHelp()
@@ -598,22 +609,23 @@ internal readonly struct CliArguments
Console.WriteLine("Usage: EvenPerfectBitScanner [options]"); Console.WriteLine("Usage: EvenPerfectBitScanner [options]");
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("Options:"); Console.WriteLine("Options:");
Console.WriteLine(" --block-size=<value> values processed per thread batch");
Console.WriteLine(" --prime=<value> starting exponent (p)"); Console.WriteLine(" --prime=<value> starting exponent (p)");
Console.WriteLine(" --max-prime=<value> inclusive upper bound for primes from filter files"); Console.WriteLine(" --max-prime=<value> inclusive upper bound for primes from filter files");
Console.WriteLine(" --increment=bit|add exponent increment method"); Console.WriteLine(" --increment=bit|add exponent increment method (default add)");
Console.WriteLine(" --threads=<value> number of worker threads"); Console.WriteLine(" --threads=<value> number of worker threads");
Console.WriteLine(" --block-size=<value> values processed per thread batch");
Console.WriteLine(" --mersenne=pow2mod|incremental|lucas|residue|divisor|bydivisor Mersenne test method"); Console.WriteLine(" --mersenne=pow2mod|incremental|lucas|residue|divisor|bydivisor Mersenne test method");
Console.WriteLine(" --residue-max-k=<value> max k for residue Mersenne test (q = 2*p*k + 1)"); Console.WriteLine(" --residue-max-k=<value> max k for residue Mersenne test (q = 2*p*k + 1)");
Console.WriteLine(" --mersenne-device=cpu|gpu|hybrid Device for Mersenne method (default gpu)"); Console.WriteLine(" --mersenne-device=cpu|gpu|hybrid Device for Mersenne method (default gpu)");
Console.WriteLine(" --primes-device=cpu|gpu Device for prime-scan kernels (default gpu)"); Console.WriteLine(" --primes-device=cpu|gpu device for prime-scan kernels (default gpu)");
Console.WriteLine(" --gpu-prime-batch=<n> Batch size for GPU primality sieve (default 262144)"); Console.WriteLine(" --gpu-prime-batch=<n> batch size for GPU primality sieve (default 262144)");
Console.WriteLine(" --order-device=cpu|gpu|hybrid Device for order computations (default gpu)"); Console.WriteLine($" --gpu-ratio=<n> ratio of GPU operations vs CPU in hybrid device mode (default {PerfectNumberConstants.GpuRatio})");
Console.WriteLine(" --ntt=reference|staged GPU NTT backend (default staged)");
Console.WriteLine(" --mod-reduction=auto|uint128|mont64|barrett128 staged NTT reduction (default auto)");
Console.WriteLine(" --gpu-prime-threads=<value> max concurrent GPU prime checks (default 1)"); Console.WriteLine(" --gpu-prime-threads=<value> max concurrent GPU prime checks (default 1)");
Console.WriteLine(" --ll-slice=<value> Lucas–Lehmer iterations per slice (default 32)");
Console.WriteLine(" --gpu-scan-batch=<value> GPU q-scan batch size (default 2_097_152)"); Console.WriteLine(" --gpu-scan-batch=<value> GPU q-scan batch size (default 2_097_152)");
Console.WriteLine(" --order-device=cpu|gpu|hybrid Device for order computations (default gpu)");
Console.WriteLine(" --ll-slice=<value> Lucas–Lehmer iterations per slice (default 32)");
Console.WriteLine(" --mod-reduction=auto|uint128|mont64|barrett128 staged NTT reduction (default auto)");
Console.WriteLine(" --ntt=reference|staged GPU NTT backend (default staged)");
Console.WriteLine(" --order-warmup-limit=<value> Warm-up order candidates (default 5_000_000)"); Console.WriteLine(" --order-warmup-limit=<value> Warm-up order candidates (default 5_000_000)");
Console.WriteLine(" --rle-blacklist=<path> enable RLE blacklist for p (hard filter up to --rle-hard-max)"); Console.WriteLine(" --rle-blacklist=<path> enable RLE blacklist for p (hard filter up to --rle-hard-max)");
Console.WriteLine(" --rle-hard-max=<p> apply RLE blacklist only for p <= this (default ulong.MaxValue = no limit)"); Console.WriteLine(" --rle-hard-max=<p> apply RLE blacklist only for p <= this (default ulong.MaxValue = no limit)");
+10 -5
View File
@@ -51,22 +51,27 @@ internal static class Program
return; return;
} }
NttGpuMath.GpuTransformBackend = _cliArguments.NttBackend; Console.WriteLine("Initializing");
NttGpuMath.ReductionMode = _cliArguments.ModReductionMode; int gpuPrimeThreads = Math.Max(1, _cliArguments.GpuPrimeThreads);
int threadCount = Math.Max(1, _cliArguments.ThreadCount);
PerfectNumberConstants.GpuRatio = _cliArguments.GpuRatio;
PerfectNumberConstants.RollingAccelerators = Math.Min(Math.Min(PerfectNumberConstants.RollingAccelerators, gpuPrimeThreads), threadCount);
// NttGpuMath.GpuTransformBackend = _cliArguments.NttBackend;
// NttGpuMath.ReductionMode = _cliArguments.ModReductionMode;
_runPrimesOnCpu = _cliArguments.ForcePrimeKernelsOnCpu; _runPrimesOnCpu = _cliArguments.ForcePrimeKernelsOnCpu;
ulong currentP = _cliArguments.StartPrime; ulong currentP = _cliArguments.StartPrime;
ulong remainder = currentP % 6UL; ulong remainder = currentP % 6UL;
bool startPrimeProvided = _cliArguments.StartPrimeProvided; bool startPrimeProvided = _cliArguments.StartPrimeProvided;
int threadCount = Math.Max(1, _cliArguments.ThreadCount);
int gpuPrimeBatch = Math.Max(1, _cliArguments.GpuPrimeBatch); int gpuPrimeBatch = Math.Max(1, _cliArguments.GpuPrimeBatch);
// int gpuPrimeThreads = SharedGpuContext.Device.MaxNumThreads; // int gpuPrimeThreads = SharedGpuContext.Device.MaxNumThreads;
int gpuPrimeThreads = Math.Max(1, _cliArguments.GpuPrimeThreads); Console.WriteLine("Setting up parameters");
UnboundedTaskScheduler.ConfigureThreadCount(threadCount); UnboundedTaskScheduler.ConfigureThreadCount(threadCount);
PrimeTester.GpuBatchSize = gpuPrimeBatch; PrimeTester.GpuBatchSize = gpuPrimeBatch;
GpuPrimeWorkLimiter.SetLimit(gpuPrimeThreads); GpuPrimeWorkLimiter.SetLimit(gpuPrimeThreads);
Console.WriteLine("Warming up GPU kernels"); Console.WriteLine("Warming up GPU kernels");
PrimeTester.WarmUpGpuKernels(1024); PrimeTester.WarmUpGpuKernels(PerfectNumberConstants.RollingAccelerators);
// PrimeTester.WarmUpGpuKernels(gpuPrimeThreads >> 4); // PrimeTester.WarmUpGpuKernels(gpuPrimeThreads >> 4);
Console.WriteLine("Starting up threads..."); Console.WriteLine("Starting up threads...");
_ = UnboundedTaskScheduler.Instance; _ = UnboundedTaskScheduler.Instance;
+15
View File
@@ -29,11 +29,26 @@ internal static class Utf8CliParser
return result; return result;
} }
public static uint ParseUInt32(ReadOnlySpan<char> value)
{
if (!TryParseUInt32(value, out uint result))
{
ThrowFormatException(value);
}
return result;
}
public static bool TryParseUInt64(ReadOnlySpan<char> value, out ulong result) public static bool TryParseUInt64(ReadOnlySpan<char> value, out ulong result)
{ {
return TryParse(value, static (ReadOnlySpan<byte> source, out ulong parsed, out int consumed) => Utf8Parser.TryParse(source, out parsed, out consumed), out result); return TryParse(value, static (ReadOnlySpan<byte> source, out ulong parsed, out int consumed) => Utf8Parser.TryParse(source, out parsed, out consumed), out result);
} }
public static bool TryParseUInt32(ReadOnlySpan<char> value, out uint result)
{
return TryParse(value, static (ReadOnlySpan<byte> source, out uint parsed, out int consumed) => Utf8Parser.TryParse(source, out parsed, out consumed), out result);
}
public static bool TryParseInt32(ReadOnlySpan<char> value, out int result) public static bool TryParseInt32(ReadOnlySpan<char> value, out int result)
{ {
return TryParse(value, static (ReadOnlySpan<byte> source, out int parsed, out int consumed) => Utf8Parser.TryParse(source, out parsed, out consumed), out result); return TryParse(value, static (ReadOnlySpan<byte> source, out int parsed, out int consumed) => Utf8Parser.TryParse(source, out parsed, out consumed), out result);
@@ -0,0 +1,38 @@
using System.Runtime.CompilerServices;
namespace PerfectNumbers.Core;
public struct AscendingDivisorRemainderStepper
{
private readonly ulong dividend;
private ulong maxDivisor;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public AscendingDivisorRemainderStepper(ulong value)
{
dividend = value;
ulong root = (ulong)Math.Sqrt(value);
if ((UInt128)root * root < value)
{
root++;
}
maxDivisor = root;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool ShouldContinue(ulong divisor) => divisor <= maxDivisor;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Divides(ulong divisor)
{
ulong quotient = dividend / divisor;
ulong remainder = dividend - (quotient * divisor);
if (quotient < maxDivisor)
{
maxDivisor = quotient;
}
return remainder == 0UL;
}
}
@@ -58,19 +58,11 @@ namespace PerfectNumbers.Core.Gpu
var device = context.GetPreferredDevice(false); var device = context.GetPreferredDevice(false);
Context = context; Context = context;
Device = device; Device = device;
int acceleratorsInContext = 0;
int acceleratorIndex = 0; int acceleratorIndex = 0;
Accelerators = [.. Enumerable.Range(0, capacity).Select(_ => Accelerators = [.. Enumerable.Range(0, capacity).Select(_ =>
{ {
Console.WriteLine($"Preparing accelerator {acceleratorIndex++}"); Console.WriteLine($"Preparing accelerator {acceleratorIndex++}");
Accelerator accelerator = device.CreateAccelerator(context); Accelerator accelerator = device.CreateAccelerator(context);
acceleratorsInContext++;
if (acceleratorsInContext >= 128)
{
context = Context.CreateDefault();
device = context.GetPreferredDevice(false);
acceleratorsInContext = 0;
}
return accelerator; return accelerator;
})]; })];
@@ -4,7 +4,7 @@ namespace PerfectNumbers.Core.Gpu;
public static class GpuPrimeWorkLimiter public static class GpuPrimeWorkLimiter
{ {
private static readonly TimeSpan _pauseBetweenChecks = TimeSpan.FromSeconds(2); private static readonly TimeSpan _pauseBetweenChecks = TimeSpan.FromSeconds(10);
private static PollingSemaphore _semaphore = new(1, _pauseBetweenChecks); private static PollingSemaphore _semaphore = new(1, _pauseBetweenChecks);
private static int _currentLimit = 1; private static int _currentLimit = 1;
@@ -1,3 +1,5 @@
#pragma warning disable CA2211 // Non-constant fields should not be visible
namespace PerfectNumbers.Core; namespace PerfectNumbers.Core;
public static class PerfectNumberConstants public static class PerfectNumberConstants
@@ -8,14 +10,14 @@ public static class PerfectNumberConstants
public const int DefaultSmallPrimeFactorSlotCount = 64; public const int DefaultSmallPrimeFactorSlotCount = 64;
public const int DefaultSpecialMaxFactorCapacity = 1024; public const int DefaultSpecialMaxFactorCapacity = 1024;
public const ulong ExtraDivisorCycleSearchLimit = 64UL; public const ulong ExtraDivisorCycleSearchLimit = 64UL;
public const int GpuFrequency = 16384 - 1; public static int GpuRatio = 16384 - 1;
public const int MaxQForDivisorCycles = 4_000_000; public const int MaxQForDivisorCycles = 4_000_000;
public static readonly uint PrimesLimit = 1_000_000; //(ulong)Array.MaxLength;// 1_000_000; public static readonly uint PrimesLimit = 1_000_000; //(ulong)Array.MaxLength;// 1_000_000;
public const int MaxOddPowersCount = 128; public const int MaxOddPowersCount = 128;
public const int PooledArrayThreshold = 64; public const int PooledArrayThreshold = 64;
public const int Pow2WindowSize = 8; public const int Pow2WindowSize = 8;
public static int RollingAccelerators = 298; //SharedGpuContext.Device.MaxNumThreadsPerGroup; public static int RollingAccelerators = 160; //SharedGpuContext.Device.MaxNumThreadsPerGroup;
public const int ThreadsByAccelerator = 8; public const int ThreadsByAccelerator = 1;
public const int ByDivisorStateSaveInterval = 10_000; public const int ByDivisorStateSaveInterval = 10_000;
public const string ByDivisorStateDirectory = "Checks"; public const string ByDivisorStateDirectory = "Checks";
// TODO: Load these limits from the benchmark-driven configuration so CPU and GPU scans stay aligned with the optimal // TODO: Load these limits from the benchmark-driven configuration so CPU and GPU scans stay aligned with the optimal
@@ -2499,17 +2499,40 @@ internal static partial class PrimeOrderCalculator
private static bool RunOnCpu() private static bool RunOnCpu()
{ {
int cpuCount = Atomic.Add(ref _cpuCount, 1); if (PerfectNumberConstants.GpuRatio == 0)
if (cpuCount == PerfectNumberConstants.GpuFrequency)
{ {
Atomic.Add(ref _cpuCount, -PerfectNumberConstants.GpuFrequency); return false;
}
else if (cpuCount > PerfectNumberConstants.GpuFrequency)
{
cpuCount -= PerfectNumberConstants.GpuFrequency;
} }
return cpuCount != PerfectNumberConstants.GpuFrequency; if (PerfectNumberConstants.GpuRatio == 1)
{
while (true)
{
if (Atomic.CompareExchange(ref _cpuCount, 0, 1) == 0)
{
return true;
}
if (Atomic.CompareExchange(ref _cpuCount, 1, 0) == 1)
{
return false;
}
Thread.Yield();
}
}
int cpuCount = Atomic.Add(ref _cpuCount, 1);
if (cpuCount == PerfectNumberConstants.GpuRatio)
{
Atomic.Add(ref _cpuCount, -PerfectNumberConstants.GpuRatio);
}
else if (cpuCount > PerfectNumberConstants.GpuRatio)
{
cpuCount -= PerfectNumberConstants.GpuRatio;
}
return cpuCount != PerfectNumberConstants.GpuRatio;
} }
private static void PopulateSmallPrimeFactorsCpu( private static void PopulateSmallPrimeFactorsCpu(
+172 -175
View File
@@ -1,3 +1,4 @@
using System;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using ILGPU; using ILGPU;
@@ -8,219 +9,215 @@ namespace PerfectNumbers.Core;
public sealed class PrimeTester public sealed class PrimeTester
{ {
public PrimeTester() public PrimeTester()
{ {
} }
[ThreadStatic] [ThreadStatic]
private static PrimeTester? _tester; private static PrimeTester? _tester;
public static PrimeTester Exclusive => _tester ??= new(); public static PrimeTester Exclusive => _tester ??= new();
public static bool IsPrimeCpu(ulong n) public static bool IsPrimeCpu(ulong n)
{ {
if (n <= 1UL) if (n <= 1UL)
{ {
return false; return false;
} }
if (n == 2UL) if (n == 2UL)
{ {
throw new InvalidOperationException("PrimeTester.IsPrime encountered the sentinel input 2."); throw new InvalidOperationException("PrimeTester.IsPrime encountered the sentinel input 2.");
} }
bool isOdd = (n & 1UL) != 0UL; if ((n & 1UL) == 0UL)
bool result = isOdd; {
return false;
}
bool requiresTrialDivision = result && n >= 7UL; if (n < 7UL)
{
return true;
}
if (requiresTrialDivision) var remainderStepper = new AscendingDivisorRemainderStepper(n);
{ uint[] smallPrimeDivisors = PrimesGenerator.SmallPrimes;
// EvenPerfectBitScanner streams exponents starting at 136,279,841, so the Mod10/GCD guard never fires on the int smallPrimeDivisorsLength = smallPrimeDivisors.Length;
// production path. Leave the logic commented out as instrumentation for diagnostic builds.
// bool sharesMaxExponentFactor = n.Mod10() == 1UL && SharesFactorWithMaxExponent(n);
// result &= !sharesMaxExponentFactor;
if (result) for (int i = 1; i < smallPrimeDivisorsLength; i++)
{ {
uint[] smallPrimeDivisors = PrimesGenerator.SmallPrimes; uint divisor = smallPrimeDivisors[i];
ulong[] smallPrimeDivisorsMul = PrimesGenerator.SmallPrimesPow2;
int smallPrimeDivisorsLength = smallPrimeDivisors.Length;
for (int i = 0; i < smallPrimeDivisorsLength; i++)
{
if (smallPrimeDivisorsMul[i] > n)
{
break;
}
if (n % smallPrimeDivisors[i] == 0) if (!remainderStepper.ShouldContinue(divisor))
{ {
result = false; break;
break; }
}
}
}
}
return result; if (remainderStepper.Divides(divisor))
} {
return false;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] return true;
public static bool IsPrimeGpu(PrimeOrderCalculatorAccelerator gpu, ulong n) }
{
byte flag = 0;
var inputView = gpu.InputView;
var outputView = gpu.OutputByteView;
int acceleratorIndex = gpu.AcceleratorIndex; [MethodImpl(MethodImplOptions.AggressiveInlining)]
AcceleratorStream stream = AcceleratorStreamPool.Rent(acceleratorIndex); public static bool IsPrimeGpu(PrimeOrderCalculatorAccelerator gpu, ulong n)
inputView.CopyFromCPU(stream, ref n, 1); {
byte flag = 0;
var inputView = gpu.InputView;
var outputView = gpu.OutputByteView;
var kernelLauncher = gpu.SmallPrimeSieveKernelLauncher; int acceleratorIndex = gpu.AcceleratorIndex;
AcceleratorStream stream = AcceleratorStreamPool.Rent(acceleratorIndex);
inputView.CopyFromCPU(stream, ref n, 1);
kernelLauncher( var kernelLauncher = gpu.SmallPrimeSieveKernelLauncher;
stream,
1,
inputView,
gpu.DevicePrimesLastOne,
gpu.DevicePrimesLastSeven,
gpu.DevicePrimesLastThree,
gpu.DevicePrimesLastNine,
gpu.DevicePrimesPow2LastOne,
gpu.DevicePrimesPow2LastSeven,
gpu.DevicePrimesPow2LastThree,
gpu.DevicePrimesPow2LastNine,
outputView);
outputView.CopyToCPU(stream, ref flag, 1); kernelLauncher(
stream.Synchronize(); stream,
AcceleratorStreamPool.Return(acceleratorIndex, stream); 1,
inputView,
gpu.DevicePrimesLastOne,
gpu.DevicePrimesLastSeven,
gpu.DevicePrimesLastThree,
gpu.DevicePrimesLastNine,
gpu.DevicePrimesPow2LastOne,
gpu.DevicePrimesPow2LastSeven,
gpu.DevicePrimesPow2LastThree,
gpu.DevicePrimesPow2LastNine,
outputView);
return flag != 0; outputView.CopyToCPU(stream, ref flag, 1);
} stream.Synchronize();
AcceleratorStreamPool.Return(acceleratorIndex, stream);
public static int GpuBatchSize { get; set; } = 262_144; return flag != 0;
}
private static readonly object GpuWarmUpLock = new(); public static int GpuBatchSize { get; set; } = 262_144;
private static int WarmedGpuLeaseCount;
public static void WarmUpGpuKernels(int threadCount) private static readonly object GpuWarmUpLock = new();
{ private static int WarmedGpuLeaseCount;
int target = threadCount >> 2;
if (target == 0)
{
target = threadCount;
}
lock (GpuWarmUpLock) public static void WarmUpGpuKernels(int threadCount)
{ {
if (target <= WarmedGpuLeaseCount) int target = threadCount;
{ if (target == 0)
return; {
} target = threadCount;
}
PrimeOrderCalculatorAccelerator.WarmUp(); lock (GpuWarmUpLock)
WarmedGpuLeaseCount = target; {
} if (target <= WarmedGpuLeaseCount)
} {
return;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] PrimeOrderCalculatorAccelerator.WarmUp();
public static void IsPrimeBatchGpu(PrimeOrderCalculatorAccelerator gpu, ReadOnlySpan<ulong> values, Span<byte> results) WarmedGpuLeaseCount = target;
{ }
// GpuPrimeWorkLimiter.Acquire(); }
int acceleratorIndex = gpu.AcceleratorIndex;
int totalLength = values.Length;
int batchSize = GpuBatchSize;
var inputView = gpu.InputView; [MethodImpl(MethodImplOptions.AggressiveInlining)]
var outputView = gpu.OutputByteView; public static void IsPrimeBatchGpu(PrimeOrderCalculatorAccelerator gpu, ReadOnlySpan<ulong> values, Span<byte> results)
{
// GpuPrimeWorkLimiter.Acquire();
int acceleratorIndex = gpu.AcceleratorIndex;
int totalLength = values.Length;
int batchSize = GpuBatchSize;
int pos = 0; var inputView = gpu.InputView;
AcceleratorStream stream = AcceleratorStreamPool.Rent(acceleratorIndex); var outputView = gpu.OutputByteView;
var kernelLauncher = gpu.SmallPrimeSieveKernelLauncher;
while (pos < totalLength) int pos = 0;
{ AcceleratorStream stream = AcceleratorStreamPool.Rent(acceleratorIndex);
int remaining = totalLength - pos; var kernelLauncher = gpu.SmallPrimeSieveKernelLauncher;
int count = remaining > batchSize ? batchSize : remaining;
var valueSlice = values.Slice(pos, count); while (pos < totalLength)
inputView.CopyFromCPU(stream, valueSlice); {
int remaining = totalLength - pos;
int count = remaining > batchSize ? batchSize : remaining;
kernelLauncher( var valueSlice = values.Slice(pos, count);
stream, inputView.CopyFromCPU(stream, valueSlice);
count,
inputView,
gpu.DevicePrimesLastOne,
gpu.DevicePrimesLastSeven,
gpu.DevicePrimesLastThree,
gpu.DevicePrimesLastNine,
gpu.DevicePrimesPow2LastOne,
gpu.DevicePrimesPow2LastSeven,
gpu.DevicePrimesPow2LastThree,
gpu.DevicePrimesPow2LastNine,
outputView);
var resultSlice = results.Slice(pos, count); kernelLauncher(
outputView.CopyToCPU(stream, resultSlice); stream,
count,
inputView,
gpu.DevicePrimesLastOne,
gpu.DevicePrimesLastSeven,
gpu.DevicePrimesLastThree,
gpu.DevicePrimesLastNine,
gpu.DevicePrimesPow2LastOne,
gpu.DevicePrimesPow2LastSeven,
gpu.DevicePrimesPow2LastThree,
gpu.DevicePrimesPow2LastNine,
outputView);
pos += count; var resultSlice = results.Slice(pos, count);
} outputView.CopyToCPU(stream, resultSlice);
stream.Synchronize(); pos += count;
AcceleratorStreamPool.Return(acceleratorIndex, stream); }
// GpuPrimeWorkLimiter.Release();
}
// Expose cache clearing for accelerator disposal coordination stream.Synchronize();
public static void ClearGpuCaches() AcceleratorStreamPool.Return(acceleratorIndex, stream);
{ // GpuPrimeWorkLimiter.Release();
PrimeOrderCalculatorAccelerator.Clear(); }
}
internal static void DisposeGpuContexts() // Expose cache clearing for accelerator disposal coordination
{ public static void ClearGpuCaches()
PrimeOrderCalculatorAccelerator.DisposeAll(); {
lock (GpuWarmUpLock) PrimeOrderCalculatorAccelerator.Clear();
{ }
WarmedGpuLeaseCount = 0;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void DisposeGpuContexts()
internal static bool SharesFactorWithMaxExponent(ulong n) {
{ PrimeOrderCalculatorAccelerator.DisposeAll();
// TODO: Replace this on-the-fly GCD probe with the cached factor table derived from lock (GpuWarmUpLock)
// ResidueComputationBenchmarks so divisor-cycle metadata can short-circuit the test {
// instead of recomputing binary GCD for every candidate. WarmedGpuLeaseCount = 0;
ulong m = (ulong)BitOperations.Log2(n); }
return n.BinaryGcd(m) != 1UL; }
}
internal static void SharesFactorWithMaxExponentBatch(PrimeOrderCalculatorAccelerator gpu, ReadOnlySpan<ulong> values, Span<byte> results) [MethodImpl(MethodImplOptions.AggressiveInlining)]
{ internal static bool SharesFactorWithMaxExponent(ulong n)
// TODO: Route this batch helper through the shared GPU kernel pool from {
// GpuUInt128BinaryGcdBenchmarks so we reuse cached kernels, pinned host buffers, // TODO: Replace this on-the-fly GCD probe with the cached factor table derived from
// and divisor-cycle staging instead of allocating new device buffers per call. // ResidueComputationBenchmarks so divisor-cycle metadata can short-circuit the test
// Check in benchmarks, which implementation was the fastest, is compatible with GPU, // instead of recomputing binary GCD for every candidate.
// and implement it. ulong m = (ulong)BitOperations.Log2(n);
return n.BinaryGcd(m) != 1UL;
}
int length = values.Length; internal static void SharesFactorWithMaxExponentBatch(PrimeOrderCalculatorAccelerator gpu, ReadOnlySpan<ulong> values, Span<byte> results)
{
// TODO: Route this batch helper through the shared GPU kernel pool from
// GpuUInt128BinaryGcdBenchmarks so we reuse cached kernels, pinned host buffers,
// and divisor-cycle staging instead of allocating new device buffers per call.
// Check in benchmarks, which implementation was the fastest, is compatible with GPU,
// and implement it.
int acceleratorIndex = gpu.AcceleratorIndex; int length = values.Length;
gpu.EnsureCapacity(0, length);
var inputBufferView = gpu.InputView;
var resultBufferView = gpu.OutputByteView;
var kernelLauncher = gpu.SharesFactorKernelLauncher;
AcceleratorStream stream = AcceleratorStreamPool.Rent(acceleratorIndex); int acceleratorIndex = gpu.AcceleratorIndex;
inputBufferView.CopyFromCPU(stream, values); gpu.EnsureCapacity(0, length);
var inputBufferView = gpu.InputView;
var resultBufferView = gpu.OutputByteView;
var kernelLauncher = gpu.SharesFactorKernelLauncher;
kernelLauncher(stream, length, inputBufferView, resultBufferView); AcceleratorStream stream = AcceleratorStreamPool.Rent(acceleratorIndex);
inputBufferView.CopyFromCPU(stream, values);
resultBufferView.CopyToCPU(stream, in results); kernelLauncher(stream, length, inputBufferView, resultBufferView);
stream.Synchronize();
AcceleratorStreamPool.Return(acceleratorIndex, stream); resultBufferView.CopyToCPU(stream, in results);
} stream.Synchronize();
AcceleratorStreamPool.Return(acceleratorIndex, stream);
}
} }