"""Exact rank certificates for ternary-weight.cpp using blocked CUDA elimination.""" import argparse import os import tempfile from pathlib import Path from concurrent.futures import ThreadPoolExecutor import numpy as np import torch import triton import triton.language as tl try: from flint import nmod_mat except ImportError: nmod_mat = None from ternary_basis import monomial_basis, swap_orbits PRIME = int(os.environ.get("FOULKES_RANK_PRIME", "251")) if PRIME not in (239, 241, 251): raise ValueError("expected rank prime 239, 241 or 251") PANEL = 256 def split_coefficients(k, terms, rows, rng): poly = np.zeros((rows, k + 1, k + 1), dtype=np.int32) poly[:, 0, 0] = 1 for _ in range(k): factors = rng.integers(0, PRIME, (2, rows, 1, 1), dtype=np.int32) old = poly.copy() poly[:, 1:, :] += factors[0] * old[:, :-1, :] poly[:, :, 1:] += factors[1] * old[:, :, :-1] poly %= PRIME return np.stack([poly[:, i, j] for i, j in terms], axis=1).copy() @triton.jit def evaluate(matrix, factors, partners, coeffs, n, stride, terms, a: tl.constexpr, swap: tl.constexpr, chunk: tl.constexpr, prime: tl.constexpr=PRIME): row = tl.program_id(1).to(tl.int64) col = tl.program_id(0) * chunk + tl.arange(0, chunk) value = tl.full((chunk,), 1, tl.int32) for h in tl.static_range(a): term = tl.load(factors + h * n + col, mask=col < n, other=0) value = (value * tl.load(coeffs + row * terms + term)) % prime if swap: partner = tl.full((chunk,), 1, tl.int32) for h in tl.static_range(a): term = tl.load(partners + h * n + col, mask=col < n, other=0) partner = (partner * tl.load(coeffs + row * terms + term)) % prime value = (value + partner) % prime tl.store(matrix + row * stride + col, tl.where(value > prime//2, value - prime, value), mask=col < n) @triton.jit def subtract(matrix, correction, start, stride: tl.constexpr, width: tl.constexpr, chunk: tl.constexpr, prime: tl.constexpr=PRIME): row = tl.program_id(1).to(tl.int64) col = tl.program_id(0) * chunk + tl.arange(0, chunk) addr = matrix + row * stride + start + col old = tl.load(addr, mask=col < width, other=0).to(tl.int32) delta = tl.load(correction + row * width + col, mask=col < width, other=0) value = (old - delta) % prime value = tl.where(value > prime//2, value - prime, tl.where(value < -(prime//2), value + prime, value)) tl.store(addr, value, mask=col < width) def centered(tensor): return ((tensor + PRIME//2) % PRIME - PRIME//2).to(torch.int8) def subtract_product(matrix, first_row, left, right, first_col): if left.size(0) == 0 or right.size(1) == 0: return left = left.contiguous() right = right.T.contiguous().T width = right.size(1) for row in range(0, left.size(0), 512): tile = left[row:row + 512] delta = torch._int_mm(tile, right) target = matrix[first_row + row:first_row + row + tile.size(0)] grid = (triton.cdiv(width, 256), tile.size(0)) subtract[grid](target, delta, first_col, matrix.stride(0), width, 256) del delta def invert_pivots(panel): """Select independent original rows and invert their square submatrix.""" a = panel.astype(np.int32) % PRIME m, n = a.shape if nmod_mat is not None: try: inverse = nmod_mat(a[:n].tolist(), PRIME).inv() return n, np.arange(m), np.asarray(inverse.tolist(), dtype=np.int32) except ZeroDivisionError: pass transform = np.eye(m, dtype=np.int32) order = np.arange(m) for j in range(n): choices = np.flatnonzero(a[j:, j]) if not len(choices): return j, None, None k = j + choices[0] if k != j: a[[j, k]] = a[[k, j]] transform[[j, k]] = transform[[k, j]] order[[j, k]] = order[[k, j]] scale = pow(int(a[j, j]), -1, PRIME) a[j, j:] = (a[j, j:] * scale) % PRIME transform[j] = (transform[j] * scale) % PRIME multiples = a[:, j:j + 1].copy() multiples[j, 0] = 0 a[:, j:] = (a[:, j:] - multiples * a[j, j:]) % PRIME transform[:] = (transform - multiples * transform[j]) % PRIME return n, order, transform[:n, order[:n]] def certify(a, k, y, t, slab, scratch, swap=None, seed=20261201): terms, columns = monomial_basis(a, k, y, t) if swap: columns, partners = swap_orbits(terms, columns, k, swap) partner_ids = torch.from_numpy(partners).cuda() n = columns.shape[1] width = (n + 31) // 32 * 32 ids = torch.from_numpy(columns).cuda() if not swap: partner_ids = ids print(f'a={a} k={k} y={y} t={t} swap={swap} columns={n}', flush=True) def samples(matrix, rng): rows = matrix.size(0) values = torch.from_numpy(split_coefficients(k, terms, rows, rng)).cuda() evaluate[(triton.cdiv(n, 128), rows)]( matrix, ids, partner_ids, values, n, width, len(terms), a, bool(swap), 128) return certify_samples(n, slab, scratch, samples, seed) def prior_panels(echelon, resident, scratch, prefetch): missing = [old for old, _ in echelon if old not in resident] if prefetch and missing: largest = max((scratch / f'{old}.npy').stat().st_size for old in missing) prefetch = torch.cuda.mem_get_info()[0] > largest + (1 << 30) if not prefetch or not missing: for old, after in echelon: right = resident.get(old) if right is None: right = torch.from_numpy(np.load(scratch / f'{old}.npy')).cuda().T yield old, after, right return stream = torch.cuda.Stream() def read(old): # The mapped host buffer stays alive through the asynchronous transfer. saved = np.load(scratch / f'{old}.npy', mmap_mode='c') with torch.cuda.stream(stream): right = torch.from_numpy(saved).to(device='cuda', non_blocking=True).T stream.synchronize() return right files = iter(missing) with ThreadPoolExecutor(max_workers=1) as pool: future = pool.submit(read, next(files)) for old, after in echelon: right = resident.get(old) if right is None: right = future.result() right.record_stream(torch.cuda.current_stream()) following = next(files, None) future = pool.submit(read, following) if following is not None else None yield old, after, right def certify_samples(n, slab, scratch, samples, seed=20261201, initial=(), saved_rows=None, minor_rows=None, update_product=subtract_product, resident_bytes=0, audit_minor=None, prefetch_panels=False): width = (n + 31) // 32 * 32 rng = np.random.Generator(np.random.PCG64(seed)) blocks = [] start = 0 for size in initial: if start >= n: break stop = min(start + size, n) blocks.append((start, stop)) start = stop blocks.extend((base, min(base + slab, n)) for base in range(start, n, slab)) echelon = [] resident = {} sampled = 0 for base, stop in blocks: size = stop - base rows = (size + 31) // 32 * 32 + 32 matrix = torch.zeros((rows, width), device='cuda', dtype=torch.int8) samples(matrix, rng) if minor_rows is not None: row_ids = np.arange(sampled, sampled + rows) sampled += rows # Earlier slabs have the form [0 | I | saved right block]. for old, after, right in prior_panels(echelon, resident, scratch, prefetch_panels): update_product(matrix, 0, matrix[:, old:after], right, after) del right first = 0 for lo in range(0, size, PANEL): hi = min(lo + PANEL, size) w = hi - lo candidates = min(rows - lo, w + 32) panel = matrix[lo:lo + candidates, base + lo:base + hi].cpu().numpy() rank, order, inverse = invert_pivots(panel) if rank != w: print(f'certified_rank_at_least={base + lo + rank}', flush=True) return False if audit_minor is not None and base == lo == 0 and w >= 8: # These rows are independent on the selected panel. The first eight columns may be singular. audit_rows = panel[order[:8]].astype(np.int32) % PRIME reduced, _ = nmod_mat(audit_rows.tolist(), PRIME).rref() columns = [next(i for i, value in enumerate(row) if value) for row in reduced.tolist()] audit_minor["audit_columns"] = np.array(columns, dtype=np.uint32) audit_minor["audit_det"] = int(nmod_mat(audit_rows[:, columns].tolist(), PRIME).det()) if minor_rows is not None: row_ids[lo:lo + candidates] = row_ids[lo + order] minor_rows.extend(row_ids[lo:hi]) if base + hi == n: break matrix[lo:lo + candidates] = matrix[lo + torch.as_tensor(order, device='cuda')] inv = centered(torch.from_numpy(inverse.copy()).cuda()) rhs = matrix[lo:hi, base + hi:].T.contiguous().T right = centered(torch._int_mm(inv, rhs)) del rhs if stop < n: update_product(matrix, first, matrix[first:lo, base + lo:base + hi], right, base + hi) update_product(matrix, hi, matrix[hi:, base + lo:base + hi], right, base + hi) matrix[lo:hi, base + hi:] = right del right # Each saved group has its own identity pivot block. A wide sampling # slab can thus reuse disk reads without making the old blocks wider. if stop < n and (hi == size or hi-first == saved_rows): saved = matrix[first:hi, base+hi:].T.contiguous() if saved.numel() <= resident_bytes: resident[base+first] = saved.T resident_bytes -= saved.numel() else: np.save(scratch / f'{base+first}.npy', saved.cpu().numpy()) echelon.append((base+first, base+hi)) del saved first = hi del matrix print(f'pivots={stop}', flush=True) print(f'rank_mod_{PRIME}={n}', flush=True) return True if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) for name in ('a', 'k', 'y', 't'): parser.add_argument(name, type=int) parser.add_argument('--slab', type=int, default=8192) parser.add_argument('--seed', type=int, default=20261201, help='PCG64 evaluation seed') parser.add_argument('--scratch', help='parent directory for temporary echelon blocks') parser.add_argument('--swap', choices=['xy', 'yt'], help='test the invariant subspace only') args = parser.parse_args() if args.a < 1 or args.k < 1 or min(args.y, args.t) < 0 or args.y + args.t > args.a * args.k: parser.error('invalid weight or degree') if args.slab <= 0 or args.slab % PANEL or args.slab * 125**2 >= 2**31 - 125: parser.error('slab must be a positive multiple of 256 with signed 32-bit dot products') if ((args.swap == 'xy' and args.a * args.k - args.y - args.t != args.y) or (args.swap == 'yt' and args.y != args.t)): parser.error('the two swapped coordinates must have equal weight') with tempfile.TemporaryDirectory(dir=args.scratch) as path: success = certify(args.a, args.k, args.y, args.t, args.slab, Path(path), args.swap, args.seed) raise SystemExit(not success)