"""Replay prepared decic root ladders on the GPU, then eliminate the Schur multiplicity block.""" import argparse import importlib import json import math import sys import tempfile from time import perf_counter from pathlib import Path import numpy as np import torch import triton import triton.language as tl sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from ternary_rank_gpu import PRIME, PANEL, centered, certify_samples cpu = importlib.import_module("schur-projector") @triton.jit def monomial_values( out, ids, coeff, count, batch: tl.constexpr, rows: tl.constexpr, tile: tl.constexpr ): ix = tl.program_id(0) * rows + tl.arange(0, rows) b = tl.program_id(1) * tile + tl.arange(0, tile) value = tl.full((rows, tile), 1, tl.uint32) for j in tl.static_range(10): key = tl.load(ids + ix * 10 + j, mask=ix < count, other=0).to(tl.int32) z = tl.load(coeff + key[:, None] * batch + b[None, :], mask=b[None, :] < batch, other=0) # 238**4 fits in uint32. After each reduction at most three more factors follow. value = value * z.to(tl.uint32) if j == 3 or j == 6 or j == 9: value = value % 239 tl.store( out + ix[:, None].to(tl.int64) * batch + b[None, :], value, mask=(ix[:, None] < count) & (b[None, :] < batch), ) @triton.jit def apply_ladder( out, x, previous, offsets, edges, size, scale, add: tl.constexpr, batch: tl.constexpr, rows: tl.constexpr, tile: tl.constexpr, ): ix = tl.program_id(0) * rows + tl.arange(0, rows) b = tl.program_id(1) * tile + tl.arange(0, tile) start = tl.load(offsets + ix, mask=ix < size, other=0) stop = tl.load(offsets + ix + 1, mask=ix < size, other=0) value = tl.full((rows, tile), 0, tl.int32) for z in tl.static_range(10): mask = start + z < stop edge = tl.load(edges + start + z, mask=mask, other=0).to(tl.uint32) addr = (edge >> 8).to(tl.int64) * batch v = tl.load( x + addr[:, None] + b[None, :], mask=mask[:, None] & (b[None, :] < batch), other=0 ) value += (edge & 255).to(tl.int32)[:, None] * v.to(tl.int32) addr = ix.to(tl.int64)[:, None] * batch + b[None, :] active = (ix[:, None] < size) & (b[None, :] < batch) if add: value = tl.load(previous + addr, mask=active, other=0).to(tl.int32) + scale * value tl.store(out + addr, value % 239, mask=active) @triton.jit def expand_flag(out, src, order, offset, n, batch: tl.constexpr, tile: tl.constexpr): row = tl.program_id(0) * 8 + tl.arange(0, 8) b = tl.program_id(1) * tile + tl.arange(0, tile) ix = tl.load(order + row, mask=row < n, other=0).to(tl.int64) - offset vals = tl.load( src + ix[:, None] * batch + b[None, :], mask=(ix[:, None] >= 0) & (row[:, None] < n) & (b[None, :] < batch), other=0, ) tl.store( out + row[:, None].to(tl.int64) * batch + b[None, :], vals, mask=(row[:, None] < n) & (b[None, :] < batch), ) @triton.jit def compress( out, x, order, coeff, n, m, batch: tl.constexpr, span: tl.constexpr, tile: tl.constexpr ): bucket = tl.program_id(0).to(tl.int64) start = bucket * n // m stop = (bucket + 1) * n // m ix = start + tl.arange(0, span) b = tl.program_id(1) * tile + tl.arange(0, tile) source = tl.load(order + ix, mask=ix < stop, other=0).to(tl.int64) weight = tl.load(coeff + ix, mask=ix < stop, other=0).to(tl.int32) v = tl.load( x + source[:, None] * batch + b[None, :], mask=(ix[:, None] < stop) & (b[None, :] < batch), other=0, ) value = tl.sum(weight[:, None] * v.to(tl.int32), axis=0) % 239 tl.store(out + b.to(tl.int64) * m + bucket, value, mask=b < batch) def gpu(data): return torch.from_numpy(np.array(data, copy=True)).cuda() class GraphBin: def __init__(self, path, height): data = np.memmap(path, dtype=" 3 else None self.single_offset = self.flag_offset self.nested = tuple(parts[4:]) if len(parts) == 7 else None self.repeat_first = False parts = parts[:3] if ( tuple(shape) != lam or len(parts) != 3 or min(parts[:2]) <= 0 or (not binary and parts[2] <= 0) ): raise ValueError("prepared graph shape does not match the requested Schur block") self.lam = lam self.batch = batch self.sample_seconds = 0.0 self.capture = capture self.replay = None self.n = cpu.multiplicity(10, lam) terms = [(10 - y - t, y, t) for y in range(11) for t in range(11 - y)] self.terms = terms self.inv = np.array( [pow(math.comb(10, t) * math.comb(10 - t, y), -1, 239) for _, y, t in terms], dtype=np.int32, ) ids = np.memmap(path / "monomials.bin", mode="r", dtype=np.uint8).reshape(-1, 10) self.total = len(ids) self.ids = gpu(ids[self.flag_offset or 0 :]) self.single_ids = self.ids self.binary = None self.binary_order = None if binary: readout = importlib.import_module("binary-readout") if (path / "binary-readout.npz").is_file(): self.binary_order, self.binary = readout.load_prepared(path, lam) else: order13, active_rows = readout.root_order(path, parts[1], len(ids)) self.binary_order = gpu(order13) self.binary = readout.BinaryReadout( ids[order13], lam, strings, active_rows=active_rows ) self.features = self.binary.size if binary else self.total if binary: char = importlib.import_module("seed-vectors").diagonal_weights() if self.features != char[lam[1], lam[2]] - char[lam[1] - 1, lam[2]]: raise ArithmeticError("binary readout disagrees with the weight character") self.order = torch.empty(self.features, device="cuda", dtype=torch.int32) self.coef = torch.empty(self.features, device="cuda", dtype=torch.uint8) self.set_sketch(sketch_seed) self.graphs = [] remaining = float("inf") if cache else cache_gib * 2**30 for (i, j), count in zip(((1, 2), (0, 2), (0, 1)), parts): if j == 1 and binary: continue files = [path / f"root{i + 1}{j + 1}-{part}.bin" for part in range(count)] scales = [ -pow(r * (lam[i] - lam[j] + j - i + r), -1, 239) % 239 for r in range(1, lam[j] + 1) ] bins = [] for f in files: size = f.stat().st_size if size <= remaining: bins.append(GraphBin(f, lam[j])) remaining -= size else: bins.append(f) self.graphs.append((scales, bins)) self.capture = self.capture and all( not isinstance(x, Path) for _, bins in self.graphs for x in bins ) def set_sketch(self, seed): # In-place copies keep CUDA graph pointers valid on a new exact rank attempt. rng = np.random.Generator(np.random.PCG64(seed)) self.order.copy_(torch.from_numpy(rng.permutation(self.features).astype(np.int32))) self.coef.copy_(torch.from_numpy(rng.integers(1, 239, size=self.features, dtype=np.uint8))) def use_repeated(self, repeated): if repeated == self.repeat_first: return self.repeat_first = repeated if self.nested is not None: self.flag_offset = self.nested[0] if repeated else self.single_offset self.ids = self.single_ids[self.flag_offset - self.single_offset :] if self.replay is not None: self.replay = None del self.static_coeff, self.static_result def coefficients(self, count, rng): coeff = cpu.split_values( 10, self.terms, count, rng, fix_first=self.flag_offset is not None, repeat_first=self.repeat_first, ) return (self.inv[:, None] * coeff % 239).astype(np.uint8) def rows(self, count, rng): return self._project(gpu(self.coefficients(count, rng))) def _project(self, coeff): count = coeff.shape[1] raw = torch.empty((len(self.ids), count), device="cuda", dtype=torch.uint8) tile = min(128, max(32, triton.next_power_of_2(count))) monomial_values[(triton.cdiv(len(self.ids), 8), triton.cdiv(count, tile))]( raw, self.ids, coeff, len(self.ids), count, 8, tile ) for root, (scales, bins) in enumerate(self.graphs): if self.repeat_first and self.nested is not None: bins = bins[self.nested[1] :] if root == 0 else bins[: self.nested[2]] reordered = root == 1 and self.binary_order is not None if reordered: if self.flag_offset is None: raw = raw.index_select(0, self.binary_order) else: full = torch.empty((self.total, count), device="cuda", dtype=torch.uint8) expand_flag[(triton.cdiv(self.total, 8), triton.cdiv(count, tile))]( full, raw, self.binary_order, self.flag_offset, self.total, count, tile ) raw = full first = 0 for item in bins: graph = GraphBin(item, len(scales)) if isinstance(item, Path) else item stop = first + len(graph.ids) contiguous = reordered or (root == 0 and self.flag_offset is not None) graph.apply(raw, scales, slice(first, stop) if contiguous else None) first = stop del graph if self.binary is not None: raw = self.binary.apply(raw) out = torch.empty((count, self.n), device="cuda", dtype=torch.uint8) span = triton.next_power_of_2(triton.cdiv(self.features, self.n)) compress[(self.n, triton.cdiv(count, 16))]( out, raw, self.order, self.coef, self.features, self.n, count, span, 16 ) return out def sample(self, matrix, rng): torch.cuda.synchronize() start = perf_counter() counts = [min(self.batch, len(matrix) - i) for i in range(0, len(matrix), self.batch)] packed = gpu(np.concatenate([self.coefficients(n, rng).ravel() for n in counts])) offset = 0 for i, count in zip(range(0, len(matrix), self.batch), counts): coeff = packed[offset : offset + 66 * count].view(66, count) offset += 66 * count if self.capture and count == self.batch: if self.replay is None: self.static_coeff = coeff.clone() self._project(self.static_coeff) torch.cuda.synchronize() self.replay = torch.cuda.CUDAGraph() with torch.cuda.graph(self.replay): self.static_result = self._project(self.static_coeff) self.static_coeff.copy_(coeff) self.replay.replay() vals = self.static_result else: vals = self._project(coeff) matrix[i : i + count, : self.n] = centered(vals.to(torch.int32)) torch.cuda.synchronize() self.sample_seconds += perf_counter() - start def sample_with_repetitions(job, slab, limit): base = 0 def sample(matrix, rng): nonlocal base size = min(job.n - base, slab) cut = cpu.repeat_rows(size, len(matrix), job.batch, limit - base) if cut: job.use_repeated(True) job.sample(matrix[:cut], rng) if cut < len(matrix): job.use_repeated(False) job.sample(matrix[cut:], rng) base += size return sample if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("graphs", type=Path) parser.add_argument("shape", nargs=3, type=int) parser.add_argument("--batch", type=int, default=128) parser.add_argument("--slab", type=int, default=2048) caching = parser.add_mutually_exclusive_group() caching.add_argument("--cache", action="store_true", help="keep all graph indices on the GPU") caching.add_argument( "--cache-gib", type=float, default=0, help="budget in GiB for resident graph files" ) parser.add_argument( "--binary", action="store_true", help="couple the first two letters directly on the last root", ) parser.add_argument("--strings", type=Path, help="reuse local binary strings across shapes") parser.add_argument( "--capture", action="store_true", help="replay the resident projection operations as one CUDA graph", ) parser.add_argument( "--panel-gib", type=float, default=0, help="GPU budget for previously reduced panels" ) parser.add_argument("--scratch", type=Path) parser.add_argument( "--minor", type=Path, help="save the selected sample rows after a full rank check" ) parser.add_argument("--pilot", type=int, help="measure and check a prefix minor of this size") parser.add_argument( "--replay", type=Path, help="regenerate the registered minor and compare its full pivot row sequence" ) args = parser.parse_args() seed, sketch_seed = 50159, 50158 double_limit = 0 expected_rows = None if args.replay is not None: certificate = json.loads(args.replay.read_text()) if tuple(certificate["shape"]) != tuple(args.shape) or certificate["prime"] != PRIME: parser.error("certificate shape or prime differs from the requested calculation") if (args.batch, args.slab) != (certificate["batch"], certificate["slab"]): parser.error("use the batch and slab sizes recorded in the certificate") expected_rows = certificate["rows"] seed, sketch_seed = certificate["seed"], certificate["sketch_seed"] double_limit = certificate.get("double_limit", 0) if PRIME != 239 or args.cache_gib < 0 or args.batch <= 0 or args.slab <= 0 or args.slab % PANEL: parser.error("use FOULKES_RANK_PRIME=239, positive batches and a slab divisible by 256") start = perf_counter() job = ProjectedSamples( args.graphs, tuple(args.shape), args.batch, args.cache, args.cache_gib, args.capture, args.binary, args.strings, sketch_seed, ) torch.cuda.synchronize() print(f"raw={job.total} columns={job.n} load_seconds={perf_counter() - start:.2f}", flush=True) if not job.n: print("rank_mod_239=0") raise SystemExit(0) if args.replay is None and job.nested is not None: loss = importlib.import_module("collision-bound").bound(10, job.lam[1], job.lam[2]) double_limit = max(0, job.n - loss) print(f"double_factor_pivots={double_limit}", flush=True) if args.pilot is not None: from flint import nmod_mat if not 1 <= args.pilot <= min(job.n, args.slab): parser.error("invalid prefix size") rng = np.random.Generator(np.random.PCG64(seed)) start = perf_counter() pieces = [] pivots = min(args.slab, job.n) rows_in_slab = ((pivots + 31) // 32) * 32 + 32 cut = cpu.repeat_rows(pivots, rows_in_slab, args.batch, double_limit) for i in range(0, args.pilot, args.batch): job.use_repeated(i < cut) # Match the first production sampling slab when checking a small prefix. count = min(args.batch, args.pilot - i) rows = job.rows( min(args.batch, ((min(args.slab, job.n) + 31) // 32) * 32 + 32 - i), rng ) pieces.append(rows[:count, : args.pilot].cpu().numpy()) mat = nmod_mat(np.vstack(pieces).tolist(), 239) det = int(mat.det()) print(f"prefix={args.pilot} det={det} seconds={perf_counter() - start:.2f}", flush=True) raise SystemExit(not det) attempts = 3 if args.minor is not None and args.replay is None else 1 for attempt in range(attempts): if attempt: seed += 2 sketch_seed += 2 job.set_sketch(sketch_seed) print(f"retry sample_seed={seed} sketch_seed={sketch_seed}", flush=True) with tempfile.TemporaryDirectory(dir=args.scratch) as work: selected = [] if args.minor is not None or expected_rows is not None else None audit = {} limit = 0 if attempt == 2 else double_limit ok = certify_samples( job.n, args.slab, Path(work), sample_with_repetitions(job, args.slab, limit), seed=seed, saved_rows=2048, minor_rows=selected, audit_minor=audit if selected is not None else None, resident_bytes=int(args.panel_gib * 2**30), ) if ok and expected_rows is not None: if not np.array_equal(selected, expected_rows): raise ArithmeticError("the regenerated pivot rows differ from the certificate") print(f"verified {len(selected)} pivot rows", flush=True) if ok and args.minor is not None: data = dict(shape=list(job.lam), readout="binary" if args.binary else "projector", prime=PRIME, seed=seed, sketch_seed=sketch_seed, double_limit=limit, slab=args.slab, batch=args.batch, rows=[int(i) for i in selected]) data.update({k: np.asarray(value).tolist() for k, value in audit.items()}) temporary = args.minor.with_suffix(".writing.json") temporary.write_text(json.dumps(data, separators=(",", ":")) + "\n") temporary.replace(args.minor) print( f"sample_seconds={job.sample_seconds:.2f} peak_gpu_GiB={torch.cuda.max_memory_allocated() / 2**30:.2f}", flush=True, ) if ok: break raise SystemExit(not ok)