Document unreachable guards in GPU by-divisor pipeline

This commit is contained in:
Marek Lemańczyk committed 2025-10-13 19:56:47 +02:00
1 parent 65e010ded5
commit bccb2f43c9
7 files changed
+178 -122

No files matched your search

@@ -146,10 +146,11 @@ public sealed class MersenneNumberDivisorByDivisorCpuTester : IMersenneNumberDiv
public void PrepareCandidates(ReadOnlySpan<ulong> primes, Span<ulong> allowedMaxValues) public void PrepareCandidates(ReadOnlySpan<ulong> primes, Span<ulong> allowedMaxValues)
{ {
if (allowedMaxValues.Length < primes.Length) // EvenPerfectBitScanner always provides equally sized spans here, so the historical guard never triggers.
{ // if (allowedMaxValues.Length < primes.Length)
throw new ArgumentException("allowedMaxValues span must be at least as long as primes span.", nameof(allowedMaxValues)); // {
} // throw new ArgumentException("allowedMaxValues span must be at least as long as primes span.", nameof(allowedMaxValues));
// }
ulong divisorLimit; ulong divisorLimit;
@@ -236,11 +237,12 @@ public sealed class MersenneNumberDivisorByDivisorCpuTester : IMersenneNumberDiv
} }
UInt128 step = (UInt128)prime << 1; UInt128 step = (UInt128)prime << 1;
if (step == UInt128.Zero) // EvenPerfectBitScanner only supplies primes greater than one here, so the shifted step never becomes zero.
{ // if (step == UInt128.Zero)
processedAll = true; // {
return false; // processedAll = true;
} // return false;
// }
UInt128 limit = allowedMax; UInt128 limit = allowedMax;
UInt128 divisor = step + UInt128.One; UInt128 divisor = step + UInt128.One;
@@ -321,10 +323,11 @@ public sealed class MersenneNumberDivisorByDivisorCpuTester : IMersenneNumberDiv
return true; return true;
} }
if (divisorCycle == 0UL) // DivisorCycleCache guarantees a non-zero cycle for every divisor reached on the EvenPerfectBitScanner path.
{ // if (divisorCycle == 0UL)
Console.WriteLine($"Divisor cycle was not calculated for {prime}"); // {
} // Console.WriteLine($"Divisor cycle was not calculated for {prime}");
// }
} }
divisor += step; divisor += step;
@@ -369,11 +372,13 @@ public sealed class MersenneNumberDivisorByDivisorCpuTester : IMersenneNumberDiv
GpuUInt128 step128 = new GpuUInt128(prime); GpuUInt128 step128 = new GpuUInt128(prime);
step128.ShiftLeft(1); step128.ShiftLeft(1);
if (step128.IsZero) // Primes above one yield a non-zero 2p value even after widening to GpuUInt128, so the defensive
{ // zero guard remains commented out to document the invariant without branching.
processedAll = true; // if (step128.IsZero)
return false; // {
} // processedAll = true;
// return false;
// }
GpuUInt128 limit128 = new GpuUInt128(allowedMax); GpuUInt128 limit128 = new GpuUInt128(allowedMax);
GpuUInt128 divisor128 = step128; GpuUInt128 divisor128 = step128;
@@ -449,10 +454,12 @@ public sealed class MersenneNumberDivisorByDivisorCpuTester : IMersenneNumberDiv
int chunkCount = remainingCandidates > (ulong)batchCapacity int chunkCount = remainingCandidates > (ulong)batchCapacity
? batchCapacity ? batchCapacity
: (int)remainingCandidates; : (int)remainingCandidates;
if (chunkCount <= 0) // batchCapacity and remainingCandidates are strictly positive in this path, so the zero-count
{ // shortcut never executes on production scans.
break; // if (chunkCount <= 0)
} // {
// break;
// }
Span<ulong> candidateSpan = candidateBuffer.AsSpan(0, chunkCount); Span<ulong> candidateSpan = candidateBuffer.AsSpan(0, chunkCount);
Span<byte> maskSpan = maskBuffer.AsSpan(0, chunkCount); Span<byte> maskSpan = maskBuffer.AsSpan(0, chunkCount);
@@ -604,11 +611,12 @@ public sealed class MersenneNumberDivisorByDivisorCpuTester : IMersenneNumberDiv
} }
ulong interval = PerfectNumberConstants.ConsoleInterval; ulong interval = PerfectNumberConstants.ConsoleInterval;
if (interval == 0UL) // PerfectNumberConstants.ConsoleInterval is a positive constant, so this guard never triggers on EvenPerfectBitScanner.
{ // if (interval == 0UL)
_lastStatusDivisor = 0UL; // {
return; // _lastStatusDivisor = 0UL;
} // return;
// }
ulong total = _lastStatusDivisor + processedCount; ulong total = _lastStatusDivisor + processedCount;
// TODO: Replace this modulo with the ring-buffer style counter (subtract loop) used in the fast CLI // TODO: Replace this modulo with the ring-buffer style counter (subtract loop) used in the fast CLI
@@ -696,11 +704,14 @@ public sealed class MersenneNumberDivisorByDivisorCpuTester : IMersenneNumberDiv
} }
ulong modulus = effectiveDivisorData.Modulus; ulong modulus = effectiveDivisorData.Modulus;
if (modulus <= 1UL || (modulus & 1UL) == 0UL) // EvenPerfectBitScanner only schedules odd divisors greater than one, and the fallback
{ // above rebuilds Montgomery data when the modulus mismatches, so this guard never
hits.Clear(); // triggers for production scans.
return; // if (modulus <= 1UL || (modulus & 1UL) == 0UL)
} // {
// hits.Clear();
// return;
// }
if (divisorCycle == 0UL) if (divisorCycle == 0UL)
{ {
@@ -803,10 +814,12 @@ public sealed class MersenneNumberDivisorByDivisorCpuTester : IMersenneNumberDiv
private void EnsureCapacity(int requiredLength) private void EnsureCapacity(int requiredLength)
{ {
if (requiredLength <= 0) // Prime batches are never empty on the by-divisor scanner path, so the zero-length guard stays commented
{ // out to remove the redundant branch.
return; // if (requiredLength <= 0)
} // {
// return;
// }
// Sessions release pooled buffers between scans; a single null check covers every array because buffers are rented and returned together. // Sessions release pooled buffers between scans; a single null check covers every array because buffers are rented and returned together.
if (requiredLength <= _bufferCapacity && _primeDeltas is not null) if (requiredLength <= _bufferCapacity && _primeDeltas is not null)
@@ -873,11 +886,13 @@ public sealed class MersenneNumberDivisorByDivisorCpuTester : IMersenneNumberDiv
private static void ComputeCycleRemainders(ulong cycleLength, ReadOnlySpan<ulong> primes, ReadOnlySpan<ulong> deltas, Span<ulong> remainders) private static void ComputeCycleRemainders(ulong cycleLength, ReadOnlySpan<ulong> primes, ReadOnlySpan<ulong> deltas, Span<ulong> remainders)
{ {
if (cycleLength == 0UL || primes.Length == 0) // Divisor cycles are validated before reaching the GPU helper, and prime batches are non-empty, so
{ // the defensive zero checks remain commented out here.
remainders.Clear(); // if (cycleLength == 0UL || primes.Length == 0)
return; // {
} // remainders.Clear();
// return;
// }
ulong remainder = primes[0] % cycleLength; ulong remainder = primes[0] % cycleLength;
remainders[0] = remainder; remainders[0] = remainder;
@@ -87,11 +87,13 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
batchCapacity = _gpuBatchSize; batchCapacity = _gpuBatchSize;
} }
if (allowedMax < 3UL) // The GPU path always receives an allowed maximum well above the minimal divisor, so the legacy
{ // guard stays commented out to document the invariant without branching.
divisorsExhausted = true; // if (allowedMax < 3UL)
return true; // {
} // divisorsExhausted = true;
// return true;
// }
bool composite; bool composite;
bool coveredRange; bool coveredRange;
@@ -222,7 +224,8 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
ArrayView1D<ulong, Stride1D.Dense> exponentView; ArrayView1D<ulong, Stride1D.Dense> exponentView;
ArrayView1D<byte, Stride1D.Dense> hitsView; ArrayView1D<byte, Stride1D.Dense> hitsView;
cycleCapacity = Math.Max(1, cycleCapacity); // Batch resources expose a positive cycle capacity, so skip the redundant clamp here.
// cycleCapacity = Math.Max(1, cycleCapacity);
int chunkCapacity = Math.Min(batchCapacity, cycleCapacity); int chunkCapacity = Math.Min(batchCapacity, cycleCapacity);
int maxThreadsPerGroup = (int)accelerator.MaxNumThreadsPerGroup; int maxThreadsPerGroup = (int)accelerator.MaxNumThreadsPerGroup;
@@ -231,20 +234,22 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
chunkCapacity = Math.Min(chunkCapacity, maxThreadsPerGroup); chunkCapacity = Math.Min(chunkCapacity, maxThreadsPerGroup);
} }
if (chunkCapacity <= 0) // cycleCapacity already bounds chunkCapacity above zero, so the fallback would never execute.
{ // if (chunkCapacity <= 0)
chunkCapacity = cycleCapacity; // {
} // chunkCapacity = cycleCapacity;
// }
ulong[] filteredDivisors = ArrayPool<ulong>.Shared.Rent(chunkCapacity); ulong[] filteredDivisors = ArrayPool<ulong>.Shared.Rent(chunkCapacity);
ulong[] divisorGaps = ArrayPool<ulong>.Shared.Rent(chunkCapacity); ulong[] divisorGaps = ArrayPool<ulong>.Shared.Rent(chunkCapacity);
UInt128 twoP128 = (UInt128)prime << 1; UInt128 twoP128 = (UInt128)prime << 1;
if (twoP128 == UInt128.Zero) // Primes above one yield a non-zero 2p value, so the legacy zero guard remains commented out.
{ // if (twoP128 == UInt128.Zero)
coveredRange = true; // {
return false; // coveredRange = true;
} // return false;
// }
UInt128 allowedMax128 = allowedMax; UInt128 allowedMax128 = allowedMax;
UInt128 firstDivisor128 = twoP128 + UInt128.One; UInt128 firstDivisor128 = twoP128 + UInt128.One;
@@ -255,11 +260,13 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
} }
UInt128 maxK128 = (allowedMax128 - UInt128.One) / twoP128; UInt128 maxK128 = (allowedMax128 - UInt128.One) / twoP128;
if (maxK128 == UInt128.Zero) // Once the first divisor falls within the allowed range, at least one multiplier k is admissible,
{ // so keep the defensive zero check commented out.
coveredRange = true; // if (maxK128 == UInt128.Zero)
return false; // {
} // coveredRange = true;
// return false;
// }
ulong maxK = maxK128 > ulong.MaxValue ? ulong.MaxValue : (ulong)maxK128; ulong maxK = maxK128 > ulong.MaxValue ? ulong.MaxValue : (ulong)maxK128;
ulong currentK = 1UL; ulong currentK = 1UL;
@@ -301,10 +308,12 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
chunkCount = (int)remainingK; chunkCount = (int)remainingK;
} }
if (chunkCount <= 0) // chunkCapacity and the remaining multiplier range are strictly positive here, so the zero
{ // chunk fallback never triggers on production scans.
break; // if (chunkCount <= 0)
} // {
// break;
// }
Span<ulong> candidateSpan = cycleCandidates.AsSpan(0, chunkCount); Span<ulong> candidateSpan = cycleCandidates.AsSpan(0, chunkCount);
Span<ulong> gapSpan = divisorGaps.AsSpan(0, chunkCount); Span<ulong> gapSpan = divisorGaps.AsSpan(0, chunkCount);
@@ -465,10 +474,12 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
Action<Index1D, ArrayView<ulong>, ArrayView<byte>, byte> deltaKernel, Action<Index1D, ArrayView<ulong>, ArrayView<byte>, byte> deltaKernel,
Action<KernelConfig, Index1D, ArrayView<byte>, ArrayView<byte>, byte, byte> scanKernel) Action<KernelConfig, Index1D, ArrayView<byte>, ArrayView<byte>, byte, byte> scanKernel)
{ {
if (count <= 0) // GPU batches always contain at least one divisor gap, so the empty-count guard remains commented
{ // to eliminate redundant branching.
return; // if (count <= 0)
} // {
// return;
// }
deltaKernel(count, gapView, deltaView, modulus); deltaKernel(count, gapView, deltaView, modulus);
SharedMemoryConfig sharedMemoryConfig = SharedMemoryConfig.RequestDynamic<int>(count); SharedMemoryConfig sharedMemoryConfig = SharedMemoryConfig.RequestDynamic<int>(count);
@@ -491,11 +502,13 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
Span<byte> destination, Span<byte> destination,
Action<Index1D, ArrayView<byte>, ArrayView<byte>, ArrayView<byte>, ArrayView<byte>, byte, ArrayView<byte>> maskKernel) Action<Index1D, ArrayView<byte>, ArrayView<byte>, ArrayView<byte>, ArrayView<byte>, byte, ArrayView<byte>> maskKernel)
{ {
if (count <= 0) // Candidate batches always provide at least one entry, so the zero-count guard stays commented out
{ // to avoid clearing spans unnecessarily.
destination.Clear(); // if (count <= 0)
return; // {
} // destination.Clear();
// return;
// }
maskKernel(count, remainder10View, remainder8View, remainder5View, remainder3View, lastIsSevenFlag, maskView); maskKernel(count, remainder10View, remainder8View, remainder5View, remainder3View, lastIsSevenFlag, maskView);
maskView.CopyToCPU(ref MemoryMarshal.GetReference(destination), count); maskView.CopyToCPU(ref MemoryMarshal.GetReference(destination), count);
@@ -503,10 +516,12 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
private static byte FetchLastRemainder(ArrayView1D<byte, Stride1D.Dense> remainderView, int count) private static byte FetchLastRemainder(ArrayView1D<byte, Stride1D.Dense> remainderView, int count)
{ {
if (count <= 0) // Kernels always process at least one remainder in this path, so the empty-span guard remains
{ // commented to document the invariant.
return 0; // if (count <= 0)
} // {
// return 0;
// }
byte value = 0; byte value = 0;
remainderView.SubView(count - 1, 1).CopyToCPU(ref value, 1); remainderView.SubView(count - 1, 1).CopyToCPU(ref value, 1);
@@ -519,10 +534,11 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
if (result >= modulus) if (result >= modulus)
{ {
result -= modulus; result -= modulus;
if (result >= modulus) // The step deltas remain below the modulus, so a single subtraction suffices on this path.
{ // if (result >= modulus)
result %= modulus; // {
} // result %= modulus;
// }
} }
return (byte)result; return (byte)result;
@@ -68,10 +68,12 @@ internal sealed class MersenneNumberDivisorCandidateGpuEvaluator : IDisposable
} }
int count = candidates.Length; int count = candidates.Length;
if (count == 0) // Candidate batches always carry at least one divisor on the by-divisor path, so the empty-count
{ // guard remains commented out to eliminate the branch.
return; // if (count == 0)
} // {
// return;
// }
EnsureCapacity(count); EnsureCapacity(count);
@@ -115,7 +117,12 @@ internal sealed class MersenneNumberDivisorCandidateGpuEvaluator : IDisposable
return; return;
} }
int newCapacity = _capacity == 0 ? 1 : _capacity; int newCapacity = _capacity;
// The evaluator always starts with a positive capacity, so the zero-capacity fallback remains commented.
// if (newCapacity == 0)
// {
// newCapacity = 1;
// }
while (newCapacity < required) while (newCapacity < required)
{ {
newCapacity <<= 1; newCapacity <<= 1;
@@ -188,10 +195,11 @@ internal sealed class MersenneNumberDivisorCandidateGpuEvaluator : IDisposable
private static int ComputeRemainder(byte remainder, byte step, int index, int modulus) private static int ComputeRemainder(byte remainder, byte step, int index, int modulus)
{ {
if (modulus == 0) // Modulus lookups only cover {10, 8, 5, 3, 7, 11}, so the zero-modulus guard stays commented out.
{ // if (modulus == 0)
return 0; // {
} // return 0;
// }
long value = remainder; long value = remainder;
value += (long)step * index; value += (long)step * index;
@@ -54,10 +54,12 @@ internal sealed class MersenneNumberDivisorMontgomeryGpuBuilder : IDisposable
} }
int length = moduli.Length; int length = moduli.Length;
if (length == 0) // Montgomery batches always include at least one modulus on the by-divisor path, so the empty-length
{ // guard stays commented out to avoid branching.
return; // if (length == 0)
} // {
// return;
// }
EnsureCapacity(length); EnsureCapacity(length);
@@ -83,7 +85,12 @@ internal sealed class MersenneNumberDivisorMontgomeryGpuBuilder : IDisposable
return; return;
} }
int newCapacity = _capacity == 0 ? 1 : _capacity; int newCapacity = _capacity;
// The builder always starts with a positive capacity, so the zero-capacity fallback remains commented.
// if (newCapacity == 0)
// {
// newCapacity = 1;
// }
while (newCapacity < required) while (newCapacity < required)
{ {
newCapacity <<= 1; newCapacity <<= 1;
@@ -71,10 +71,12 @@ internal sealed class MersenneNumberDivisorRemainderGpuStepper : IDisposable
throw new ObjectDisposedException(nameof(MersenneNumberDivisorRemainderGpuStepper)); throw new ObjectDisposedException(nameof(MersenneNumberDivisorRemainderGpuStepper));
} }
if (advanceCount <= 0 || remainders.Length == 0) // GPU remainder batches always advance by a positive chunk count and operate on fixed-size tables, so
{ // the defensive early-return remains commented out.
return; // if (advanceCount <= 0 || remainders.Length == 0)
} // {
// return;
// }
if (remainders.Length != _length) if (remainders.Length != _length)
{ {
@@ -99,17 +101,20 @@ internal sealed class MersenneNumberDivisorRemainderGpuStepper : IDisposable
private static void AdvanceRemaindersKernel(Index1D index, int advanceCount, ArrayView<byte> remainders, ArrayView<byte> steps, ArrayView<byte> results) private static void AdvanceRemaindersKernel(Index1D index, int advanceCount, ArrayView<byte> remainders, ArrayView<byte> steps, ArrayView<byte> results)
{ {
int idx = index; int idx = index;
if (idx >= remainders.Length) // Kernel launches match the remainder table length, so the bounds guard stays commented to avoid redundant branching.
{ // if (idx >= remainders.Length)
return; // {
} // return;
// }
int modulus = GetModulus(idx); int modulus = GetModulus(idx);
if (modulus == 0) // The modulus selector only emits positive bases (10, 8, 5, 3, 7, 11) for the configured indices, so the zero-modulus
{ // fallback remains commented out.
results[idx] = remainders[idx]; // if (modulus == 0)
return; // {
} // results[idx] = remainders[idx];
// return;
// }
int remainder = remainders[idx] % modulus; int remainder = remainders[idx] % modulus;
int step = steps[idx] % modulus; int step = steps[idx] % modulus;
@@ -51,10 +51,12 @@ internal sealed class MersenneNumberDivisorResidueGpuEvaluator : IDisposable
} }
int length = exponents.Length; int length = exponents.Length;
if (length == 0) // Residue batches always include at least one exponent when scheduled from the by-divisor scanner, so
{ // the empty-length guard remains commented out to avoid branching.
return; // if (length == 0)
} // {
// return;
// }
EnsureCapacity(length); EnsureCapacity(length);
@@ -79,10 +81,11 @@ internal sealed class MersenneNumberDivisorResidueGpuEvaluator : IDisposable
} }
int newCapacity = _capacity; int newCapacity = _capacity;
if (newCapacity == 0) // The evaluator always starts with a positive capacity, so the zero-capacity fallback stays commented.
{ // if (newCapacity == 0)
newCapacity = 1; // {
} // newCapacity = 1;
// }
while (newCapacity < required) while (newCapacity < required)
{ {
@@ -180,11 +180,13 @@ public static class MersenneNumberDivisorByDivisorTester
return; return;
} }
if (maxPrime <= 1UL) // EvenPerfectBitScanner removes candidates <= 1 before reaching this point,
{ // so this guard never triggers during production runs.
Console.WriteLine("The filter specified by --filter-p must contain at least one prime exponent greater than 1 for --mersenne=bydivisor."); // if (maxPrime <= 1UL)
return; // {
} // Console.WriteLine("The filter specified by --filter-p must contain at least one prime exponent greater than 1 for --mersenne=bydivisor.");
// return;
// }
tester.ConfigureFromMaxPrime(maxPrime); tester.ConfigureFromMaxPrime(maxPrime);