Document divisor invariants and refresh pow2 tests

This commit is contained in:
Marek Lemańczyk committed 2025-10-13 17:42:56 +02:00
1 parent af909e9e2d
commit c0b6b29837
8 files changed
+252 -130

No files matched your search

+1 -11
View File
@@ -82,8 +82,7 @@ public sealed class DivisorCycleCache
ulong cached = snapshot[divisor];
if (cached == 0UL)
{
missingBuffer[missingCount++] = i;
continue;
throw new InvalidDataException($"Divisor cycle is missing for {divisor}");
}
cycles[i] = cached;
@@ -106,15 +105,6 @@ public sealed class DivisorCycleCache
ComputeCyclesCpu(divisors, cycles, missingIndices);
}
for (int j = 0; j < missingCount; j++)
{
int target = missingIndices[j];
ulong divisor = divisors[target];
if (divisor < (ulong)snapshot.Length)
{
snapshot[divisor] = cycles[target];
}
}
}
if (rentedMissing is not null)
@@ -630,11 +630,13 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
// return;
// }
if (divisorData.Modulus <= 1UL || (divisorData.Modulus & 1UL) == 0UL)
{
hits.Clear();
return;
}
// The divisor staging path filters non-prime and even moduli before kernels launch, so keep the defensive
// modulus guard commented out to avoid branching in the hot loop.
// if (divisorData.Modulus <= 1UL || (divisorData.Modulus & 1UL) == 0UL)
// {
// hits.Clear();
// return;
// }
ArrayView1D<ulong, Stride1D.Dense> exponentsView = _exponentsBuffer.View;
ArrayView1D<ulong, Stride1D.Dense> resultsView = _resultsBuffer.View;
@@ -813,10 +815,12 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
{
get
{
if (!_isConfigured)
{
throw new InvalidOperationException("ConfigureFromMaxPrime must be called before using the tester.");
}
// The by-divisor scanner always configures the tester before exposing the limit, so the guard remains
// commented out to document the invariant without forcing a runtime branch.
// if (!_isConfigured)
// {
// throw new InvalidOperationException("ConfigureFromMaxPrime must be called before using the tester.");
// }
return _divisorLimit;
}
@@ -840,10 +844,12 @@ public sealed class MersenneNumberDivisorByDivisorGpuTester : IMersenneNumberDiv
internal BatchResources(MersenneNumberDivisorByDivisorGpuTester owner, Accelerator accelerator, int capacity)
{
int cycleCapacity = DivisorCycleCache.Shared.PreferredBatchSize;
if (cycleCapacity <= 0)
{
cycleCapacity = 1;
}
// The shared cache always reports a positive preferred size on production workloads, so the fallback remains
// commented out to avoid branching during resource initialization.
// if (cycleCapacity <= 0)
// {
// cycleCapacity = 1;
// }
int actualCapacity = Math.Max(capacity, cycleCapacity);
@@ -104,17 +104,21 @@ internal sealed class MersenneNumberDivisorMontgomeryGpuBuilder : IDisposable
private static void BuildKernel(Index1D index, ArrayView<ulong> moduli, ArrayView<MontgomeryDivisorData> destination)
{
int idx = index;
if (idx >= moduli.Length)
{
return;
}
// The builder launches kernels with an extent equal to the modulus count, so the bounds guard remains commented
// out to avoid redundant branching on every thread.
// if (idx >= moduli.Length)
// {
// return;
// }
ulong modulus = moduli[idx];
if (modulus <= 1UL || (modulus & 1UL) == 0UL)
{
destination[idx] = default;
return;
}
// All staged divisors are odd primes on the scanner path, so keep the defensive modulus guard commented out to
// remove the branch from the kernel.
// if (modulus <= 1UL || (modulus & 1UL) == 0UL)
// {
// destination[idx] = default;
// return;
// }
ulong nPrime = ComputeMontgomeryNPrime(modulus);
ulong montgomeryOne = ComputeMontgomeryResidue64(modulus);
@@ -1004,10 +1004,12 @@ internal static partial class PrimeOrderGpuHeuristics
long candidateCapacity = candidates.Length;
int candidateLimit = candidateCapacity < HeuristicCandidateLimit ? (int)candidateCapacity : HeuristicCandidateLimit;
int candidateCount = BuildCandidatesKernel(order, workFactors, workExponents, factorCount, candidates, stackIndex, stackExponent, stackProduct, candidateLimit);
if (candidateCount == 0)
{
return false;
}
// Candidate enumeration always yields at least one order on the configured workloads, so the zero-count guard remains
// commented out to eliminate the redundant branch.
// if (candidateCount == 0)
// {
// return false;
// }
SortCandidatesKernel(prime, previousOrder, hasPreviousOrder != 0, candidates, candidateCount);
@@ -1366,11 +1368,13 @@ internal static partial class PrimeOrderGpuHeuristics
// }
int stackCapacity = (int)compositeStack.Length;
if (stackCapacity <= 0)
{
statusOut[0] = (byte)PrimeOrderKernelStatus.PollardOverflow;
return false;
}
// Pollard-Rho always reserves a positive stack on production workloads, so the overflow guard remains commented out
// to avoid branching here.
// if (stackCapacity <= 0)
// {
// statusOut[0] = (byte)PrimeOrderKernelStatus.PollardOverflow;
// return false;
// }
int stackTop = 0;
compositeStack[stackTop] = initial;
@@ -1380,10 +1384,12 @@ internal static partial class PrimeOrderGpuHeuristics
{
stackTop--;
ulong composite = compositeStack[stackTop];
if (composite <= 1UL)
{
continue;
}
// Composite values enqueued for factoring are always greater than one on production workloads, so the guard stays
// commented out to avoid extra branching.
// if (composite <= 1UL)
// {
// continue;
// }
if (!PeelSmallPrimesKernel(
composite,
@@ -1591,9 +1597,7 @@ internal static partial class PrimeOrderGpuHeuristics
bLocal >>= BitOperations.TrailingZeroCount(bLocal);
if (aLocal > bLocal)
{
ulong temp = aLocal;
aLocal = bLocal;
bLocal = temp;
(aLocal, bLocal) = (bLocal, aLocal);
}
bLocal -= aLocal;
+9 -4
View File
@@ -74,10 +74,12 @@ public class MersenneDivisorCycles
return true;
}
if (exponent <= 1UL || divisor <= 1UL || (divisor & 1UL) == 0UL)
{
return false;
}
// Exponent and divisor validation happens during scheduling, so the defensive guard remains commented out to keep the
// hot path branch-free.
// if (exponent <= 1UL || divisor <= 1UL || (divisor & 1UL) == 0UL)
// {
// return false;
// }
// Production scans never revisit divisors in the small-cycle snapshot, so skip the legacy lookup here. Factoring and
// diagnostics can query TryMatchSmallCycleForFactoring when they need those cached values.
@@ -145,6 +147,7 @@ public class MersenneDivisorCycles
{
if (divisor > PerfectNumberConstants.MaxQForDivisorCycles)
{
// Factoring helpers probe arbitrary divisors, so anything above the snapshot limit legitimately misses here.
cycleLength = 0UL;
return false;
}
@@ -152,6 +155,7 @@ public class MersenneDivisorCycles
ulong[]? small = Shared._smallCycles;
if (small is null)
{
// Snapshot recycling during diagnostics can temporarily clear the table; surface the miss so callers recompute.
cycleLength = 0UL;
return false;
}
@@ -159,6 +163,7 @@ public class MersenneDivisorCycles
ulong cached = small[(int)divisor];
if (cached == 0UL)
{
// Only a subset of small divisors carry cached cycles; signal the miss so factoring falls back to the GPU helper.
cycleLength = 0UL;
return false;
}
+31 -21
View File
@@ -17,10 +17,12 @@ public static class ULongExtensions
public static ulong CalculateOrder(this ulong q)
{
if (q <= 2UL)
{
return 0UL;
}
// Order computations only run on admissible divisors, so the small-prime guard remains commented out to keep the
// path branch-free.
// if (q <= 2UL)
// {
// return 0UL;
// }
ulong order = q - 1UL, prime, temp;
uint[] smallPrimes = PrimesGenerator.SmallPrimes;
@@ -292,10 +294,12 @@ public static class ULongExtensions
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong MulMod64(this ulong a, ulong b, ulong modulus)
{
if (modulus <= 1UL)
{
return 0UL;
}
// Scanner inputs always provide odd prime moduli, so the legacy modulus guard stays commented out to avoid extra
// branching.
// if (modulus <= 1UL)
// {
// return 0UL;
// }
ulong reducedA = a >= modulus ? a % modulus : a;
ulong reducedB = b >= modulus ? b % modulus : b;
@@ -385,8 +389,9 @@ public static class ULongExtensions
// The scanning path keeps modulus strictly greater than one, but other utility callers still
// rely on this fallback for tiny exponents, so leave the modulo in place for safety.
ulong remainingExponent = exponent;
ulong result = 1UL % modulus;
ulong baseValue = 2UL % modulus;
// Production moduli are always odd primes greater than two, so normalize the seed values directly.
ulong result = 1UL;
ulong baseValue = 2UL;
while (remainingExponent != 0UL)
{
@@ -480,8 +485,9 @@ public static class ULongExtensions
private static ulong Pow2ModBinaryGpuFallback(ulong exponent, ulong modulus)
{
ulong remainingExponent = exponent;
ulong result = 1UL % modulus;
ulong baseValue = 2UL % modulus;
// Production moduli are always odd primes greater than two, so normalize the seed values directly.
ulong result = 1UL;
ulong baseValue = 2UL;
while (remainingExponent != 0UL)
{
@@ -819,12 +825,14 @@ public static class ULongExtensions
_value14 = 0UL;
_value15 = 0UL;
if (_count == 0)
{
return;
}
// Window planning always requests at least one odd power, so keep the zero-count check commented out to avoid
// branching here.
// if (_count == 0)
// {
// return;
// }
ulong baseValue = 2UL % modulus;
ulong baseValue = 2UL;
_value0 = baseValue;
if (_count == 1)
{
@@ -843,10 +851,12 @@ public static class ULongExtensions
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ulong Get(int index)
{
if ((uint)index >= (uint)_count)
{
return 0UL;
}
// Windowed lookups never exceed the populated table bounds on production workloads, so leave the check commented
// out to remove the branch.
// if ((uint)index >= (uint)_count)
// {
// return 0UL;
// }
return index switch
{