"""Binary strings for a ternary coefficient weight with a fixed marked degree.""" import argparse import importlib import itertools import math import tempfile from functools import lru_cache from pathlib import Path import numpy as np import torch import triton from ternary_rank_gpu import ( PANEL, PRIME as P, certify_samples, centered, evaluate, split_coefficients, ) primitives = importlib.import_module("ternary-primitives") profiles, primitive_basis = primitives.profiles, primitives.primitive_basis def partitions(n, top): if n == 0: yield () for j in range(1, min(n, top) + 1): for tail in partitions(n - j, j): yield (j,) + tail def gpu(x): return torch.from_numpy(np.ascontiguousarray(x)).cuda() def pad(n): return (n + 31) // 32 * 32 def transform(a): m, n = a.shape if pad(m) * 125**2 >= 2**31 - 125: raise ArithmeticError("int32 coupling dot-product bound exceeded") b = np.zeros((pad(m), pad(n)), dtype=np.int8) b[:m, :n] = ((a.astype(np.int32) + P//2) % P - P//2).astype(np.int8) return gpu(b.T).T def binary_string_layers(d, copies, max_weight=None): """Coefficient matrices and multiplicity labels of the divided binary lowering strings.""" total = d * copies degrees = (d,) * copies previous = None old = [] labels = [] last_weight = total if max_weight is None else min(total, max_weight) for w in range(last_weight + 1): rows = profiles(degrees, w) ix = {r: i for i, r in enumerate(rows)} columns = [] nextlabels = [] if old: keep = [i for i, (h, c) in enumerate(labels) if w <= total - h] if keep: div = np.array([pow(w - labels[i][0], -1, P) for i in keep], dtype=np.int32) active = previous[:, keep] new = np.zeros((len(rows), len(keep)), dtype=np.int32) for col, r in enumerate(old): for j in range(copies): if r[j] < d and (j + 1 == copies or r[j + 1] != r[j]): f = r[j] + 1 parent = r[:j] + (f,) + r[j + 1 :] new[ix[parent]] += (f * r.count(r[j])) * active[col] new = (new % P) * div % P columns.append(new) nextlabels.extend(labels[i] for i in keep) if 2 * w <= total: basis = primitive_basis(degrees, w, rows).astype(np.int32) % P if basis.shape[1]: columns.append(basis) nextlabels.extend((w, c) for c in range(basis.shape[1])) mat = np.column_stack(columns) if len(nextlabels) != len(rows): raise ArithmeticError("incomplete local weight basis") yield w, rows, mat, nextlabels labels = nextlabels previous = mat old = rows class BinaryStrings: """Weight bases for Sym^copies(Sym^d C^2), with their divided lowering strings.""" def __init__(self, k, marked, copies, start, positions, max_weight=None): d = k-marked self.blocks = [] self.at = {} self.types = [] for w,rows,mat,labels in binary_string_layers(d,copies,max_weight): primitive = sum(h==w for h,_ in labels) if primitive: self.types.append((d*copies-2*w,primitive,w)) for i,(h,c) in enumerate(labels): self.at[h,c,w-h]=start+i terms = np.array([[positions[y, marked] for y in r] for r in rows], dtype=np.int32) self.blocks.append((gpu(terms.T), transform(mat), len(rows), start, copies)) start += len(rows) self.end = start @lru_cache(None) def tensor_weights(spins, w): if not spins: return [()] if not w else [] return [ (j,) + v for j in range(max(0, w - sum(spins[1:])), min(spins[0], w) + 1) for v in tensor_weights(spins[1:], w - j) ] # Each path successively selects a Clebsch-Gordan summand. Its columns are # expressed in the normalized divided-lowering basis of the input strings. @lru_cache(None) def paths(spins, h): if len(spins) == 1: return [((), spins[0])] if h == 0 else [] return [ (prev + (j,), n + spins[-1] - 2 * j) for j in range(min(h, spins[-1]) + 1) for prev, n in paths(spins[:-1], h - j) if j <= n ] @lru_cache(None) def pascal(m): return np.array([[math.comb(u,i) % P if i<=u else 0 for i in range(m+1)] for u in range(m+1)],dtype=np.int32) @lru_cache(None) def clebsch_table(m,n,h): # Each row and column index is a divided-lowering depth in an input string. coeff=[1] for i in range(h): coeff.append(-coeff[-1]*(n-h+i+1)*pow(m-i,-1,P)%P) left=pascal(m)[:,:h+1]*np.asarray(coeff,dtype=np.int32)%P right=pascal(n)[:,h::-1] return ((left @ right.T)%P).astype(np.int16) def coupling(spins, h): sub = tensor_weights(spins, h) lists = paths(spins, h) if not lists: return None mat = np.ones((len(sub), len(lists)), dtype=np.int16) ws = np.asarray(sub, dtype=int) for c, (path, _) in enumerate(lists): n = spins[0] u = ws[:, 0].copy() for i, j in enumerate(path, 1): s = spins[i] v = ws[:, i] coeff = clebsch_table(n, s, j) mask = (u >= 0) & (u <= n) mat[~mask, c] = 0 mat[mask, c] = (mat[mask, c].astype(np.int32) * coeff[u[mask], v[mask]]) % P u += v - j n += s - 2 * j return sub, mat def prepare(k, a, marked, h): terms = [(y, t) for t in range(k + 1) for y in range(k - t + 1)] positions = {p: i for i, p in enumerate(terms)} profileset = [sorted((0,) * (a - len(p)) + p) for p in partitions(marked, k) if len(p) <= a] factors = {} offset = 0 for prof in profileset: for t in sorted(set(prof)): key = (t, prof.count(t)) if key not in factors: f = BinaryStrings(k, *key, offset, positions, h) factors[key] = f offset = f.end lib = [b for f in factors.values() for b in f.blocks] blocks = [] n = 0 for prof in profileset: f = [factors[t, prof.count(t)] for t in sorted(set(prof))] for names in itertools.product(*(row.types for row in f)): spins, ns, base = zip(*names) rem = h - sum(base) if rem < 0 or 2 * rem > sum(spins): continue cm = coupling(spins, rem) if cm is None: continue sub, mat = cm copies = math.prod(ns) l, c = mat.shape ids = np.array( [ [[x.at[b, i, j] for x, b, i, j in zip(f, base, idx, q)] for q in sub] for idx in itertools.product(*map(range, ns)) ], dtype=np.int32, ) ids = ids.reshape(copies * l, len(f)).T blocks.append((gpu(ids), transform(mat), copies, l, c, n, len(f))) n += copies * c return terms, lib, offset, blocks, n def one_linear_factor(k, terms, rows, rng): """Coefficients of a generic (k-1)-form times an independent linear form.""" poly = rng.integers(0, P, (rows, k + 1, k + 1), dtype=np.int32) for y in range(k + 1): poly[:, y, k - y :] = 0 y, t = rng.integers(0, P, (2, rows, 1, 1), dtype=np.int32) product = poly.copy() product[:, 1:, :] += y * poly[:, :-1, :] product[:, :, 1:] += t * poly[:, :, :-1] return np.stack([product[:, i, j] % P for i, j in terms], axis=1).copy() def certify(k, a, marked, h, slab, scratch, coefficient_sampler): terms, lib, total, blocks, n = prepare(k, a, marked, h) print(f"mark={marked} h={h} local={total} couplings={len(blocks)} columns={n}", flush=True) def sample(matrix, rng): rows = matrix.size(0) coeff = gpu(coefficient_sampler(k, terms, rows, rng)) local = torch.empty((rows, total), device="cuda", dtype=torch.int16) for ids, mat, m, offset, num in lib: r = torch.zeros((rows, pad(m)), device="cuda", dtype=torch.int8) evaluate[(triton.cdiv(m, 128), rows)]( r, ids, ids, coeff, m, pad(m), len(terms), num, False, 128 ) local[:, offset : offset + m] = torch.remainder(torch._int_mm(r, mat)[:, :m], P).to( torch.int16 ) for ids, mat, copies, l, c, offset, num in blocks: raw = torch.empty((rows, copies * l), device="cuda", dtype=torch.int8) evaluate[(triton.cdiv(copies * l, 128), rows)]( raw, ids, ids, local, copies * l, copies * l, total, num, False, 128 ) raw = raw.reshape(rows * copies, l) # Matrix multiply has 32-column tiling; the padded entries are zero. padded = torch.nn.functional.pad(raw, (0, pad(l) - l)) if l % 32 else raw count = padded.size(0) proj = centered(torch._int_mm(padded, mat)[:count, :c]) matrix[:, offset : offset + copies * c] = proj.reshape(rows, copies * c) return certify_samples(n, slab, scratch, sample) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) for name in ("a", "k", "marked", "h"): parser.add_argument(name, type=int) parser.add_argument("--slab", type=int, default=8192) parser.add_argument("--scratch") parser.add_argument( "--one-factor", action="store_true", help="test divisibility by one linear form" ) args = parser.parse_args() if not ( args.a > 0 and args.k > 0 and args.a * args.k < P and 0 <= 2 * args.h <= args.a * args.k - args.marked and 0 <= args.marked <= args.a * args.k ): parser.error("expected a positive degree below the rank prime and a dominant binary weight") if args.slab <= 0 or args.slab % PANEL or args.slab * 125**2 >= 2**31 - 125: parser.error("invalid elimination slab") with tempfile.TemporaryDirectory(dir=args.scratch) as tmp: sampler = one_linear_factor if args.one_factor else split_coefficients raise SystemExit( not certify(args.k, args.a, args.marked, args.h, args.slab, Path(tmp), sampler) )