--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
+140 -56

No files matched your search

+22 -10
View File
@@ -51,6 +51,7 @@ 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,
@@ -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(
+18 -21
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;
@@ -29,40 +30,36 @@ public sealed class PrimeTester
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;
bool requiresTrialDivision = result && n >= 7UL;
if (requiresTrialDivision)
{ {
// EvenPerfectBitScanner streams exponents starting at 136,279,841, so the Mod10/GCD guard never fires on the return false;
// production path. Leave the logic commented out as instrumentation for diagnostic builds. }
// bool sharesMaxExponentFactor = n.Mod10() == 1UL && SharesFactorWithMaxExponent(n);
// result &= !sharesMaxExponentFactor;
if (result) if (n < 7UL)
{ {
return true;
}
var remainderStepper = new AscendingDivisorRemainderStepper(n);
uint[] smallPrimeDivisors = PrimesGenerator.SmallPrimes; uint[] smallPrimeDivisors = PrimesGenerator.SmallPrimes;
ulong[] smallPrimeDivisorsMul = PrimesGenerator.SmallPrimesPow2;
int smallPrimeDivisorsLength = smallPrimeDivisors.Length; int smallPrimeDivisorsLength = smallPrimeDivisors.Length;
for (int i = 0; i < smallPrimeDivisorsLength; i++)
for (int i = 1; i < smallPrimeDivisorsLength; i++)
{ {
if (smallPrimeDivisorsMul[i] > n) uint divisor = smallPrimeDivisors[i];
if (!remainderStepper.ShouldContinue(divisor))
{ {
break; break;
} }
if (n % smallPrimeDivisors[i] == 0) if (remainderStepper.Divides(divisor))
{ {
result = false; return false;
break;
}
}
} }
} }
return result; return true;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -106,7 +103,7 @@ public sealed class PrimeTester
public static void WarmUpGpuKernels(int threadCount) public static void WarmUpGpuKernels(int threadCount)
{ {
int target = threadCount >> 2; int target = threadCount;
if (target == 0) if (target == 0)
{ {
target = threadCount; target = threadCount;