r"""kstar-1943.py -- run the PINNED K* engine at 19# -> 43#, in resumable chunks. WHY THIS FILE EXISTS AND NOT THE PINNED SCRIPT. `kstar-engine-check.py` (the artifact of return 1100) packs the killed-residue set of an entering prime q into a 32-bit mask: one bit per residue mod q. That is exact for q <= 31 -- which is every step it was used on, 13#->29# and 13#->31# (q <= 31) and 17#->31# -- and it raises OverflowError at 19#->43#, whose entering primes are 23, 29, 31, 37, 41, 43: `1 << 36` does not fit a uint32. So the shipped engine CANNOT be run at this step at all, for a representation reason and not a mathematical one. This runner therefore changes ONE thing -- the representation: the same residue bitmask and the same union-by-subset (SOS) transform, in 64-bit words, which covers q <= 63 and so covers this step with room to spare. Everything else is imported from the pinned engine: `slot_word` (the ascending-position-order word), `PRIMES`, and the pinned global configuration, asserted below. LICENCE FOR USING IT: a representation change is only trustworthy if it is a regression-free re-implementation. `--check` re-runs the frozen steps with this 64-bit code and compares cell by cell against the committed curves that the 32-bit engine already reproduced -- 11 cells at 13#->29#, 18 at 13#->31#, 14 at 17#->31#. The new step is only computed after that passes. Falsifiers, registered before any cell of the new step was computed: G1 the 64-bit code reproduces all 43 committed cells (representation regression). G2 at 19#->43#, D must equal the corpus slot count 378675. G3 at 19#->43#, the engine's k = 1 cell must equal the convention-free closed form N_1 = D*(NCOPY - prod_{q in Q}(q-2)) = 162280751678100. G4 N_k must be non-increasing in k, and the chunked partial sums must add to the whole-D result (the chunks are disjoint ranges of one additive sum). """ import argparse import importlib.util import json import os import sys import time import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) ENGINE = os.path.join(HERE, "kstar-engine-check.py") STEPS = [(13, 29, 10, [105221160, 29114520, 6942634, 1470674, 285422, 52048, 9456, 1712, 270, 36, 0]), (13, 31, 17, [3691273410, 1208132640, 357506328, 98048374, 25570726, 6426266, 1601992, 403958, 103170, 25738, 5568, 1180, 296, 80, 18, 6, 2, 0]), (17, 31, 13, [2524470300, 607806150, 128515868, 25793636, 5037414, 929548, 167144, 29148, 4894, 710, 138, 22, 6, 0])] D_EXPECT = {13: 1485, 17: 22275, 19: 378675} NEW = (19, 43) # default step; --P/--PP override it KMAX_DEFAULT = 12 SIXTY_FOUR = np.uint64 FAST = True # strided-view SOS instead of boolean fancy indexing (same result) BITCOUNT = getattr(np, "bitwise_count", None) # numpy >= 2.0 def sos_or_fast(U, kmax): """Subset-sum (SOS) transform of OR, by strided views. For bit b, U viewed as (2^(k-b-1), 2, 2^b) has index (i, s, j) at J = i*2^(b+1) + s*2^b + j, so J ^ 2^b is the same element with s = 0: one in-place strided OR with no gather, no scatter and no boolean mask. Same arithmetic as the pinned engine's loop. """ n = U.shape[0] for b in range(kmax): if (1 << b) >= n: break v = U.reshape(-1, 2, 1 << b) v[:, 1, :] |= v[:, 0, :] return U def count_bits(U): if BITCOUNT is not None: return BITCOUNT(U) return popcount64(U) def load_engine(): spec = importlib.util.spec_from_file_location("kstar_pinned_engine", ENGINE) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) assert (mod.CONV, mod.NONWRAP, mod.DESC, mod.LASTONLY, mod.WRAPSUB) == \ (0, False, False, False, False), "the imported engine is not in its pinned configuration" return mod def popcount64(x): """SWAR popcount on uint64 (wraparound multiply is the standard trick, not an error).""" x = x.astype(SIXTY_FOUR) m1 = SIXTY_FOUR(0x5555555555555555) m2 = SIXTY_FOUR(0x3333333333333333) m4 = SIXTY_FOUR(0x0F0F0F0F0F0F0F0F) x = x - ((x >> SIXTY_FOUR(1)) & m1) x = (x & m2) + ((x >> SIXTY_FOUR(2)) & m2) x = (x + (x >> SIXTY_FOUR(4))) & m4 return (x * SIXTY_FOUR(0x0101010101010101)) >> SIXTY_FOUR(56) def masks_for_shape(mod, slots, D, Psharp, Q, i, kmax): """The pinned formula, in 64-bit words: bit r of mask[k, a] iff prime Q[a] kills residue r. Slot index is signed and resolved by floor division, exactly as in the pinned engine: t = i + k ascending, copy = t // D, u = slots[t % D] + Psharp * copy. """ masks = np.zeros((kmax, len(Q)), dtype=SIXTY_FOUR) for k in range(kmax): t = i + k u = slots[int(t % D)] + Psharp * int(t // D) for a, q in enumerate(Q): inv = pow(Psharp % q, -1, q) r1 = (-u * inv) % q r2 = (-u - 2) * inv % q masks[k, a] = SIXTY_FOUR((1 << int(r1)) | (1 << int(r2))) return masks def nk_range(mod, slots, Psharp, Q, kmax, D, lo, hi): """N_k for k = 1..kmax summed over shapes i in [lo, hi).""" n = 1 << kmax Jidx = np.arange(n, dtype=SIXTY_FOUR) parity = (popcount64(Jidx) & SIXTY_FOUR(1)).astype(bool) Nk = [0] * (kmax + 1) for i in range(lo, hi): masks = masks_for_shape(mod, slots, D, Psharp, Q, i, kmax) prod = np.ones(n, dtype=np.int64) for a, q in enumerate(Q): U = np.zeros(n, dtype=SIXTY_FOUR) for k in range(kmax): U[1 << k] = masks[k, a] if FAST: sos_or_fast(U, kmax) else: for b in range(kmax): bit = SIXTY_FOUR(1 << b) sel = (Jidx & bit).astype(bool) U[sel] |= U[Jidx[sel] ^ bit] prod *= (q - count_bits(U).astype(np.int64)) term = np.where(parity, -prod, prod) for k in range(1, kmax + 1): Nk[k] += int(term[:1 << k].sum()) return Nk def f1_values(mod, P, PP): slots, Psharp = mod.slot_word(P) Q = [q for q in mod.PRIMES if P < q <= PP] ncopy = int(np.prod(Q)) prodq = int(np.prod([q - 2 for q in Q])) return slots, Psharp, Q, ncopy, prodq, len(slots) * (ncopy - prodq) def main(): ap = argparse.ArgumentParser() ap.add_argument("--check", action="store_true") ap.add_argument("--only", default=None, help="comma-separated step indices for --check (0=13#->29#, " "1=13#->31#, 2=17#->31#); partial checks do not set G1_ok") ap.add_argument("--f1", action="store_true") ap.add_argument("--kmax", type=int, default=KMAX_DEFAULT) ap.add_argument("--lo", type=int, default=0) ap.add_argument("--hi", type=int, default=None) ap.add_argument("--out", default=None) ap.add_argument("--P", type=int, default=NEW[0]) ap.add_argument("--PP", type=int, default=NEW[1]) ap.add_argument("--slow", action="store_true") a = ap.parse_args() global FAST if a.slow: FAST = False step = (a.P, a.PP) mod = load_engine() if a.check: want = [int(x) for x in a.only.split(",")] if a.only else list(range(len(STEPS))) out = {"check": "representation regression: 64-bit code vs the committed curves", "steps_run": want, "partial": bool(a.only)} ok_all = True for si, (P, PP, kstar, curve) in enumerate(STEPS): if si not in want: continue slots, Psharp, Q, ncopy, prodq, closed = f1_values(mod, P, PP) D = len(slots) t0 = time.time() # nk_range returns the raw Nk list, index 0 unused: drop it to align with curve. got = nk_range(mod, slots, Psharp, Q, len(curve), D, 0, D)[1:] dt = time.time() - t0 mism = [(k + 1, got[k], curve[k]) for k in range(len(curve)) if got[k] != curve[k]] kst = max([k for k in range(1, len(curve) + 1) if got[k - 1] >= 1] or [0]) ok = not mism and kst == kstar and got[0] == closed ok_all &= ok sys.stderr.write("%d#->%d# D=%d %.1fs mismatches=%s K*=%d/%d closed_form=%s\n" % (P, PP, D, dt, mism, kst, kstar, got[0] == closed)) out["%d#->%d#" % (P, PP)] = {"D": D, "seconds": round(dt, 1), "mismatches": mism, "kstar": kst, "kstar_committed": kstar, "N1_engine": got[0], "N1_closed_form": closed, "ok": ok} if not a.only: out["G1_ok"] = ok_all print(json.dumps(out, indent=1)) return 0 if ok_all else 1 if a.f1: slots, Psharp, Q, ncopy, prodq, closed = f1_values(mod, *step) exp = D_EXPECT.get(step[0]) rec = {"step": "%d#->%d#" % step, "D": len(slots), "D_expected": exp, "D_ok": exp is None or len(slots) == exp, "Q": Q, "NCOPY": ncopy, "prod(q-2)": prodq, "closed_form_N1": closed, "kmax_default": KMAX_DEFAULT} sys.stderr.write("G2 D=%d expected %s ok=%s; G3 target N_1=%d\n" % (len(slots), exp, rec["D_ok"], closed)) print(json.dumps(rec, indent=1)) return 0 if rec["D_ok"] else 1 slots, Psharp, Q, ncopy, prodq, closed = f1_values(mod, *step) D = len(slots) hi = D if a.hi is None else a.hi t0 = time.time() Nk = nk_range(mod, slots, Psharp, Q, a.kmax, D, a.lo, hi) dt = time.time() - t0 rec = {"step": "%d#->%d#" % step, "kmax": a.kmax, "lo": a.lo, "hi": hi, "D": D, "Q": Q, "N1_closed_form": closed, "N1_engine": Nk[1], "Nk_summed": Nk[1:], "seconds": round(dt, 1), "shapes": hi - a.lo, "ms_per_shape": round(1000 * dt / max(1, hi - a.lo), 4)} sys.stderr.write("chunk [%d,%d) kmax=%d -> %.1fs (%.3f ms/shape)\n" % (a.lo, hi, a.kmax, dt, 1000 * dt / max(1, hi - a.lo))) if a.out: open(a.out, "w", encoding="utf-8", newline="\n").write(json.dumps(rec, indent=1) + "\n") sys.stderr.write("wrote %s\n" % a.out) print(json.dumps(rec, indent=1)) return 0 if __name__ == "__main__": sys.exit(main())