"""route176/cuda_kernel.py -- CUDA evaluation of F(h) via the validated per-residue sum. STRUCTURE COPIED FROM THE VALIDATED `sieve2.F_array` (3.8e-15 vs the exact engine): F(h) = (5/3)/head(6) * head(h) * T(h), head(h) = prod_{3<=p<=h+2} f_p(h), T(h) = prod_{8
= p-2. So for each (p, r): add log f_p(r) to every h in [k, H] with k = p-2 + ((r - (p-2)) mod p), step p. The kernel loops the primes 3..H+2 per h with early exit at p > h+2. This is O(pi(h)) per thread -- fine to H ~ 1e6, not to 1e8 -- but it is the structure that validates, so it is the one shipped. The zeros of f_3 (r = 1) are handled with the additive-offset trick `log(f + 1e-300)`: f = 3/2 stays put, f = 0 gives `log(1e-300)` which underflows the running product to exactly 0.0, and f = 3 gives `log 3`. This file also EXPORTS the exact correction recipe the segmented rewrite needs (see the docstring of cuda_sieve.py): the exceptional classes are i = -2 (r=0), i = 0 (r=2) and i = -4 (r=p-2) mod p, with c0 = (p-1)(p-2)/(p(p-4)) and c1 = p/(p-4); p = 3 must NOT receive the generic baseline. """ from __future__ import annotations import math import sys import time import numpy as np sys.path.insert(0, "work/route176") from fobj import HEAD6 # noqa: E402 NORM = (5.0 / 3.0) / float(HEAD6) # 25/21 SEG = 2_000_000 from numba import cuda # noqa: E402 try: cuda.current_context() HAVE_CUDA = True except Exception: # pragma: no cover HAVE_CUDA = False def primes_upto(n: int) -> np.ndarray: if n < 2: return np.zeros(0, dtype=np.int64) s = bytearray([1]) * (n + 1) s[0] = s[1] = 0 for i in range(2, math.isqrt(n) + 1): if s[i]: s[i * i :: i] = bytearray(len(range(i * i, n + 1, i))) return np.array([i for i in range(2, n + 1) if s[i]], dtype=np.int64) if HAVE_CUDA: @cuda.jit def _head_kernel(h0, n, primes, logf, out): """out[i] = sum_{3<=p<=h+2} log(f_p(h0+i)) using the precomputed per-residue logs.""" i = cuda.grid(1) if i >= n: return h = h0 + i acc = 0.0 for j in range(primes.shape[0]): p = primes[j] if p < 3: continue if p > h + 2: break acc += logf[j, h % p] out[i] = acc def build_logf(prmax: int) -> np.ndarray: """logf[j, r] = log(f_p(r) + 1e-300) for p = primes[prmax-index], r in [0, p-1].""" pr = primes_upto(prmax) pr = pr[pr >= 3] width = int(pr[-1]) if pr.size else 3 M = np.zeros((pr.size, width), dtype=np.float64) for j in range(pr.size): p = int(pr[j]) for r in range(p): nu = len({0, 2, r, (r + 2) % p}) f = (p - nu) / p / ((p - 2) / p) ** 2 M[j, r] = math.log(f + 1e-300) return pr, M def gpu_head(H: int, prmax: int | None = None) -> np.ndarray: if not HAVE_CUDA: raise RuntimeError("no CUDA device") if prmax is None: prmax = H + 2 pr, M = build_logf(prmax) d_pr = cuda.to_device(pr) d_M = cuda.to_device(M) lg = np.empty(H + 3, dtype=np.float64) tpb = 128 for lo in range(0, H + 1, SEG): hi = min(lo + SEG, H + 1) n = hi - lo d_out = cuda.device_array(n, dtype=np.float64) _head_kernel[(int((n + tpb - 1) // tpb),), (tpb,)](lo, n, d_pr, d_M, d_out) lg[lo:hi] = d_out.copy_to_host() return lg def tail_logs(H: int) -> np.ndarray: d = np.zeros(H + 4, dtype=np.float64) for p in primes_upto(H + 2): if p > 8: d[p - 2] += math.log((p - 1) / (p - 2)) return np.cumsum(d[: H + 3]) def gpu_F(H: int) -> np.ndarray: lg = gpu_head(H) + tail_logs(H) F = NORM * np.exp(lg) h = np.arange(H + 3, dtype=np.int64) F[(h % 3 != 0) | (h < 6)] = 0.0 return F def validate(limit: int = 3998) -> tuple[int, float]: from fobj import F_engine F = gpu_F(limit) worst, n = 0.0, 0 for hh in range(6, limit + 1, 3): e = float(F_engine(hh)) if e <= 0: if F[hh] != 0.0: worst = max(worst, 1.0) continue worst = max(worst, abs(e - F[hh]) / e) n += 1 return n, worst if __name__ == "__main__": n, w = validate(3998) print(f"cuda_kernel.gpu_F vs exact engine: {n} h, max rel dev {w:.3e}")