"""Highest weight in the last two letters of a quaternary coefficient ring.""" import argparse import tempfile from collections import Counter, defaultdict from functools import lru_cache from pathlib import Path import numpy as np import torch, triton from ternary_basis import monomial_basis from ternary_rank_gpu import PANEL, PRIME as P, certify_samples, evaluate, centered def pad(n): return (n + 31) // 32 * 32 @lru_cache(None) def basis(signature, h): """Primitive columns of binary forms grouped by identical passive labels.""" degrees = tuple(d for d, m in signature for _ in range(m)) groups = tuple(i for i, (d, m) in enumerate(signature) for _ in range(m)) def profiles(h): out = [] def walk(i, w, v): if i == len(degrees): if not w: out.append(tuple(v)) return lo = v[-1] if i and groups[i] == groups[i - 1] else 0 for q in range(lo, min(degrees[i], w) + 1): v.append(q) walk(i + 1, w - q, v) v.pop() walk(0, h, []) return out up = profiles(h) down = profiles(h - 1) if h else [] ids = {p: i for i, p in enumerate(down)} mat = np.zeros((len(down), len(up)), dtype=np.int64) for i, p in enumerate(up): for j, v in enumerate(p): if not v or (j and groups[j] == groups[j - 1] and p[j] == p[j - 1]): continue m = 1 while j + m < len(p) and groups[j + m] == groups[j] and p[j + m] == v: m += 1 parent = p[:j] + (v - 1,) + p[j + 1 :] mat[ids[parent], i] = (degrees[j] - v + 1) * m r = 0 piv = [] for j in range(len(up)): nz = np.flatnonzero(mat[r:, j]) if not len(nz): continue k = r + nz[0] mat[[r, k]] = mat[[k, r]] mat[r] = mat[r] * pow(int(mat[r, j]), -1, P) % P multipliers = mat[:, j].copy() multipliers[r] = 0 mat = (mat - multipliers[:, None] * mat[r]) % P piv.append(j) r += 1 if r != len(down): raise ArithmeticError("binary raising rank") pivots = set(piv) free = [i for i in range(len(up)) if i not in pivots] b = np.zeros((pad(len(up)), pad(len(free))), dtype=np.int8) b[free, np.arange(len(free))] = 1 if piv and free: b[np.ix_(piv, range(len(free)))] = ((-mat[:, free] + P // 2) % P - P // 2).astype(np.int8) return up, b, len(free) def split(k, terms, n, rng): f = np.zeros((n, k + 1, k + 1, k + 1), dtype=np.int32) f[:, 0, 0, 0] = 1 for _ in range(k): a, b, c = rng.integers(0, P, (3, n, 1, 1, 1), dtype=np.int32) old = f.copy() f[:, 1:, :, :] += a * old[:, :-1, :, :] f[:, :, 1:, :] += b * old[:, :, :-1, :] f[:, :, :, 1:] += c * old[:, :, :, :-1] f %= P return np.stack([f[:, y, t, u] for y, t, u in terms], axis=1).copy() def certify(a, k, y, total, h, slab, scratch): passive, profiles = monomial_basis(a, k, y, total) terms = [(i, j - q, q) for i, j in passive for q in range(j + 1)] pos = {t: i for i, t in enumerate(terms)} batches = defaultdict(list) # Profiles with the same group degrees and multiplicities share one transform. for line in profiles.T: groups = Counter(passive[i] for i in line) order = sorted(groups, key=lambda t: (t[1], groups[t], t[0])) sig = tuple((j, groups[i, j]) for i, j in order) up, b, c = basis(sig, h) if not c: continue labels = [(i, j) for i, j in order for _ in range(groups[i, j])] terms_id = [[pos[i, j - q, q] for (i, j), q in zip(labels, p)] for p in up] batches[sig].extend(terms_id) blocks = [] count = 0 for sig, located in batches.items(): up, b, c = basis(sig, h) if pad(len(up)) * (P // 2) ** 2 >= 2**31 - P // 2: raise ArithmeticError("int32 primitive dot-product bound exceeded") m = len(located) // len(up) ids = torch.from_numpy(np.asarray(located, dtype=np.int32).T.copy()).cuda() mat = torch.from_numpy(b.T.copy()).cuda().T blocks.append((ids, mat, len(up), c, m, count)) count += m * c print(f"a={a} k={k} y={y} mark={total} h={h} groups={len(blocks)} columns={count}", flush=True) def sample(matrix, rng): rows = matrix.size(0) coeff = torch.from_numpy(split(k, terms, rows, rng)).cuda() for ids, mat, raw, c, m, offset in blocks: for start in range(0, rows, 1024): size = min(rows - start, 1024) v = torch.empty((size, m * raw), device="cuda", dtype=torch.int8) evaluate[(triton.cdiv(m * raw, 128), size)]( v, ids, ids, coeff[start:], m * raw, m * raw, len(terms), a, False, 128 ) v = v.reshape(size * m, raw) if raw % 32: v = torch.nn.functional.pad(v, (0, pad(raw) - raw)) proj = centered(torch._int_mm(v, mat)[:, :c]) matrix[start : start + size, offset : offset + m * c] = proj.reshape(size, m * c) return certify_samples(count, slab, Path(scratch), sample) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) for name in ("a", "k", "y", "marked", "h"): parser.add_argument(name, type=int) parser.add_argument("--slab", type=int, default=8192) parser.add_argument("--scratch") args = parser.parse_args() if not ( args.a > 0 and args.k > 0 and 0 <= 2 * args.h <= args.marked and 0 <= args.y and args.marked + args.y <= args.a * args.k < P ): parser.error("invalid quaternary weight") if args.slab <= 0 or args.slab % PANEL or args.slab * (P // 2) ** 2 >= 2**31 - P // 2: parser.error("invalid elimination slab") with tempfile.TemporaryDirectory(dir=args.scratch) as tmp: raise SystemExit(not certify(args.a, args.k, args.y, args.marked, args.h, args.slab, tmp))