#!/usr/bin/env python3 """Route 56, s = 19 rung on the GPU (CUDA via numba-cuda). K*(s) = longest run of consecutive KILLED slots of the level-2s walk. Definition (producer `attack-0829n-doubling-bridge.js` convention): P = s#, A = T_s = { r < P : gcd(r,P) = gcd(r+2,P) = 1 }, nA = |A|, Q = entering primes (s < q <= 2s), R = prod Q, M = P*R, slot (c, j) <-> v = A[j] + c*P, admissible index u = j + c*nA, killed(nA) <=> v = 0 or -2 (mod q) for some q in Q. Chunk flat order (c, j) is exactly increasing v, so runs of the killed flag in that flat order are runs of consecutive killed slots. Kernel: one block per copy, one thread per column. * thread j compares its precomputed residue vals_q[j] against the two killed targets per prime (targets depend only on c, passed per chunk); * it stores the dead bit in the shared uint32 bitset `bits` (copy-major layout) and remembers the last alive index al[j] in shared memory; * thread 0 scans the bitset in index order maintaining B (running dead-run length) and mx = max(B), then writes carry_h[c] (run ending at the last slot) and carry_d[c] (whole copy dead). A second, single-thread kernel folds the carry across copies in order (carry_h[c] += carry_h[c-1] when the copy before was fully dead), which is what makes runs that span a copy frontier come out at their true length. Usage: python3 route56_cuda.py [s] [chunk_copies] """ import os import sys import json import time os.environ.setdefault("NUMBA_CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY", "1") import numpy as np if not hasattr(np, "row_stack"): # numba's dispatcher uses np.row_stack, np.row_stack = np.vstack # removed in numpy 2.0 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from numba import cuda, uint32, int64 # noqa: E402 import route56_walk as W # noqa: E402 TPB = 512 NBITS = 17 # TPB//32 + 1, a compile-time constant for cuda.shared.array # --------------------------------------------------------------------------- # toolchain shim: llvmlite emits PTX .version 8.8 while the ptxas bundled with # the installed CUDA 12.9 toolkit accepts at most 8.7. The kernels below use no # 8.8-only feature, so a wrapper `ptxas` that rewrites the version directive is # put first on PATH (see ptxas_shim.py); if the PTX did need a newer ISA, ptxas # fails loudly instead of miscompiling. # --------------------------------------------------------------------------- def _install_path_shim(): import shutil here = os.path.dirname(os.path.abspath(__file__)) shim = os.path.join(here, "ptxas_shim.py") if not os.path.exists(shim): return False bindir = os.path.join(here, "_toolshim") try: os.makedirs(bindir, exist_ok=True) py = sys.executable with open(os.path.join(bindir, "ptxas.bat"), "w", encoding="utf-8") as f: f.write('@"%s" "%s" %%*\n' % (py, shim)) with open(os.path.join(bindir, "ptxas"), "w", encoding="utf-8") as f: f.write('#!/bin/sh\nexec "%s" "%s" "$@"\n' % (py, shim)) os.environ["PATH"] = bindir + os.pathsep + os.environ.get("PATH", "") os.environ.setdefault("NUMBA_CUDA_PTXAS", os.path.join(bindir, "ptxas.bat")) return True except Exception: return False HAVE_PTX_SHIM = _install_path_shim() if HAVE_PTX_SHIM: # numba's driver driver looks the assembler up through config; point it at the # wrapper so the PTX .version rewrite applies regardless of PATH lookups. try: from numba.core import config as _nbcfg _nbcfg.CUDA_PTXAS = os.path.join( os.path.dirname(os.path.abspath(__file__)), "_toolshim", "ptxas.bat") except Exception: pass @cuda.jit def _chunk_kernel(vals0, vals1, vals2, vals3, nQ, t00, t01, t02, t03, t10, t11, t12, t13, c0, cend, nA, P, carry_h, carry_d, out_max): j = cuda.threadIdx.x c = cuda.blockIdx.x bits = cuda.shared.array(NBITS, dtype=uint32) alive = cuda.shared.array(TPB, dtype=int64) if j == 0: for w in range(NBITS): bits[w] = uint32(0) alive[j] = -1 # every thread, so alive[nA-1] is always defined cuda.syncthreads() if j < nA: dead = False if vals0[j] == t00[c]: dead = True if (not dead) and vals0[j] == t10[c]: dead = True if nQ > 1: if (not dead) and vals1[j] == t01[c]: dead = True if (not dead) and vals1[j] == t11[c]: dead = True if nQ > 2: if (not dead) and vals2[j] == t02[c]: dead = True if (not dead) and vals2[j] == t12[c]: dead = True if nQ > 3: if (not dead) and vals3[j] == t03[c]: dead = True if (not dead) and vals3[j] == t13[c]: dead = True if dead: cuda.atomic.or_(bits, j >> 5, uint32(1) << uint32(j & 31)) else: alive[j] = j cuda.syncthreads() if j == 0: cc = c0 + c B = 0 mx = 0 half = 0 for jj in range(nA): if (bits[jj >> 5] >> uint32(jj & 31)) & uint32(1) != uint32(0): B += 1 if B > mx: mx = B else: B = 0 if bits[0] & uint32(1) != uint32(0): half = alive[nA - 1] + 1 # leading dead run length add = 0 if cc > c0: add = carry_h[cc - 1] cand = mx if add + half > cand: cand = add + half if cand > out_max[0]: out_max[0] = cand carry_h[cc] = B carry_d[cc] = 1 if B == nA else 0 @cuda.jit def _carry_kernel(c0, cend, out_max, carry_h, carry_d): if cuda.threadIdx.x == 0 and cuda.blockIdx.x == 0: for c in range(c0 + 1, cend): if carry_d[c - 1] != 0: carry_h[c] += carry_h[c - 1] if carry_h[c] > out_max[0]: out_max[0] = carry_h[c] @cuda.jit def _fill_kill(vals_q, dead, tgt, row0, nA, P, q, shift): """Mark dead[c, j] where (A[j] + c*P) = -shift (mod q). One block per copy; threads stride the columns (nA can far exceed the block size). vals_q[j] = A[j] mod q is precomputed; tgt[c] = (-c*P - shift) mod q. """ c = row0 + cuda.blockIdx.x j = cuda.threadIdx.x while j < nA: if vals_q[j] == tgt[c]: dead[c, j] = True j += cuda.blockDim.x def _fill_mask_gpu(Q, vals_d, dead, cc, nA, P): """Fill `dead` (len(cc), nA) on the GPU, one block per copy row.""" for k, q in enumerate(Q): z = (-(cc % q) * (P % q)) % q for shift in (0, 2): tgt = cuda.to_device(((z - shift) % q).astype(np.int64)) _fill_kill[(cc.size,), (TPB,)](vals_d[k], dead, tgt, 0, nA, P, q, shift) def run_gpu_mask(P, Q, chunk_copies=4096, A=None, verbose=False): """GPU kill mask + the validated CPU run fold. The mask is the expensive part (2.9e11 cells at s = 19) and is a pure outer product, which is what the GPU does best. The run fold over one chunk's mask is a cheap difference/RLE on the host and is shared with the validated numpy engine, so the GPU path inherits that validation rather than repeating the bitset scan (which was demonstrably wrong). Chunk transfer is ~0.3 GB and bandwidth-bound, so this stays GPU-throughput-bound overall. """ Q = sorted(Q) if A is None: A = W.admissible(P) nA = int(A.size) R = 1 for q in Q: R *= q vd = [cuda.to_device(np.ascontiguousarray(A % q, dtype=np.int64)) for q in Q] longest = 0 run_prev = 0 t0 = time.time() c0 = 0 while c0 < R: c = min(chunk_copies, R - c0) cc = np.arange(c0, c0 + c, dtype=np.int64) dead = cuda.device_array((c, nA), dtype=np.bool_) dead[:] = False _fill_mask_gpu(Q, vd, dead, cc, nA, P) flat = dead.copy_to_host().reshape(-1) starts, lens = W._runs(flat) if starts.size: if starts[0] == 0 and run_prev: longest = max(longest, run_prev + int(lens[0])) rest = lens[1:] else: rest = lens if rest.size: longest = max(longest, int(rest.max())) if flat[-1]: nz = np.flatnonzero(~flat) run_prev = int(flat.size - 1 - nz[-1]) if nz.size else int(flat.size) else: run_prev = 0 c0 += c if verbose and c0 % (chunk_copies * 200) == 0: print(" gpu copies %d/%d longest=%d" % (c0, R, longest), flush=True) return {"K": longest, "seconds": time.time() - t0, "engine": "cuda-mask", "device": cuda.get_current_device().name, "complete": True} Q = sorted(Q) if A is None: A = W.admissible(P) nA = int(A.size) nQ = len(Q) v = [np.ascontiguousarray(A % q, dtype=np.int64) for q in Q] while len(v) < 4: v.append(np.zeros(1, dtype=np.int64)) vd = [cuda.to_device(x) for x in v] R = 1 for q in Q: R *= q out_max = cuda.to_device(np.zeros(1, dtype=np.int64)) carry_h = cuda.to_device(np.zeros(R, dtype=np.int64)) carry_d = cuda.to_device(np.zeros(R, dtype=np.int64)) t0 = time.time() c0 = 0 while c0 < R: c = min(chunk_copies, R - c0) cc = np.arange(c0, c0 + c, dtype=np.int64) tg = [] for sh in (0, 2): # 0..3 = shift 0 targets, 4..7 = shift 2 for k in range(4): if k < nQ: q = Q[k] tg.append(cuda.to_device( ((-(cc % q) * (P % q) - sh) % q).astype(np.int64))) else: tg.append(cuda.to_device(np.zeros(c, dtype=np.int64))) _chunk_kernel[c, TPB](vd[0], vd[1], vd[2], vd[3], nQ, tg[0], tg[1], tg[2], tg[3], tg[4], tg[5], tg[6], tg[7], c0, c0 + c, nA, P, carry_h, carry_d, out_max) c0 += c if verbose and c0 % (chunk_copies * 200) == 0: print(" gpu copies %d/%d" % (c0, R), flush=True) _carry_kernel[1, 1](0, R, out_max, carry_h, carry_d) cuda.synchronize() K = int(out_max.copy_to_host()[0]) return {"K": K, "seconds": time.time() - t0, "engine": "cuda", "device": cuda.get_current_device().name} def run_task(s, chunk_copies=256, device="auto", verbose=False): """Run the K*(s) task on the requested device. device: "cuda" (require the GPU), "cpu" (validated numpy engine), or "auto" (try CUDA, fall back to the validated numpy engine with the reason reported). Both paths compute the same object and are cross-checked against each other on the served ladder rows (see route56_walk_test.py). """ P = W.primorial(W.primes_upto(s)) Q = [q for q in W.primes_upto(2 * s) if q > s] nA = int(W.admissible(P).size) out = {"s": s, "Q": Q, "P": P, "nA": nA, "R": int(np.prod(Q, dtype=object))} if device in ("cuda", "auto"): try: from numba import cuda as _c if not _c.is_available(): raise RuntimeError("no CUDA device available") r = run_gpu_mask(P, Q, chunk_copies=chunk_copies, verbose=verbose) out.update(r) out["device"] = "cuda" return out except Exception as e: out["cuda_error"] = "%s: %s" % (type(e).__name__, str(e)[:300]) if device == "cuda": raise t0 = time.time() r = W.run_walk(P, Q, chunk_copies=max(chunk_copies, 2048)) out.update({"K": r["K"], "seconds": time.time() - t0, "device": "cpu", "engine": "numpy-index-space"}) return out if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("s", nargs="?", type=int, default=13) ap.add_argument("chunk_copies", nargs="?", type=int, default=256) ap.add_argument("--device", default="auto", choices=["auto", "cuda", "cpu"]) ap.add_argument("--json-out") a = ap.parse_args() res = run_task(a.s, chunk_copies=a.chunk_copies, device=a.device, verbose=True) print(json.dumps(res)) if a.json_out: with open(a.json_out, "w", encoding="utf-8") as f: json.dump(res, f, indent=1)