"""Test a ternary weight via the kernels of a binary raising operator.""" import argparse import tempfile from pathlib import Path import numpy as np import torch import triton from ternary_rank_gpu import PANEL, PRIME, centered, certify_samples, evaluate, split_coefficients def partitions(total, slots, maximum): if slots == 0: if total == 0: yield () return for d in range((total + slots - 1) // slots, min(total, maximum) + 1): for tail in partitions(total - d, slots - 1, d): yield (d,) + tail def profiles(degrees, h): """t-exponents at a fixed list of y,t totals; sort ties within each group.""" suffix = [0] * (len(degrees) + 1) for i in reversed(range(len(degrees))): suffix[i] = suffix[i + 1] + degrees[i] result = [] def visit(i, left, path): if i == len(degrees): result.append(tuple(path)) return low = path[-1] if i and degrees[i] == degrees[i - 1] else 0 for j in range(max(low, left - suffix[i + 1]), min(degrees[i], left) + 1): path.append(j) visit(i + 1, left - j, path) path.pop() if 0 <= h <= suffix[0]: visit(0, h, []) return result def primitive_basis(degrees, h, monomials): n = len(monomials) down = profiles(degrees, h - 1) if not down: return np.eye(n, dtype=np.int8) positions = {values: i for i, values in enumerate(down)} equations = [{} for _ in down] for col, values in enumerate(monomials): i = 0 while i < len(degrees): j = i + 1 while j < len(degrees) and (degrees[j], values[j]) == (degrees[i], values[i]): j += 1 if values[i]: parent = values[:i] + (values[i] - 1,) + values[i + 1:] equations[positions[parent]][col] = (degrees[i] - values[i] + 1) * (j - i) % PRIME i = j pivots = {} for equation in sorted(equations, key=lambda row: (min(row), len(row)), reverse=True): while equation: j = min(equation) value = equation.pop(j) if j not in pivots: inv = pow(value, -1, PRIME) pivots[j] = [(i, -c * inv % PRIME) for i, c in equation.items()] break for i, c in pivots[j]: new = (equation.get(i, 0) + value * c) % PRIME if new: equation[i] = new else: equation.pop(i, None) free = [j for j in range(n) if j not in pivots] if len(free) != n - len(down): raise ArithmeticError('raising matrix failed the expected full row rank') basis = np.zeros((n, len(free)), dtype=np.int32) basis[free, np.arange(len(free))] = 1 for j, entries in sorted(pivots.items(), reverse=True): if entries: indices, coeffs = zip(*entries) basis[j] = (np.asarray(coeffs, dtype=np.int64) @ basis[np.asarray(indices)]) % PRIME return ((basis + PRIME//2) % PRIME - PRIME//2).astype(np.int8) def certify_layer(a, k, total, h, slab, scratch, initial=()): terms = [(d - j, j) for d in range(k + 1) for j in range(d + 1)] positions = {term: i for i, term in enumerate(terms)} blocks = [] n = 0 for degrees in partitions(total, a, k): monomials = profiles(degrees, h) if not monomials: continue kernel = primitive_basis(degrees, h, monomials) local, cols = kernel.shape if not cols: continue inner = (local + 31) // 32 * 32 if inner * 125**2 >= 2**31 - 125: raise ArithmeticError('primitive block exceeds the int32 dot-product bound') ids = [[positions[d - j, j] for d, j in zip(degrees, row)] for row in monomials] ids = torch.tensor(ids, dtype=torch.int32).T.contiguous().cuda() transform = torch.zeros((inner, (cols + 31) // 32 * 32), device='cuda', dtype=torch.int8) transform[:local, :cols] = torch.from_numpy(kernel).cuda() blocks.append((ids, transform.T.contiguous().T, local, cols, n)) n += cols print(f'a={a} k={k} total={total} h={h} blocks={len(blocks)} columns={n}', flush=True) def samples(matrix, rng): rows = matrix.size(0) coeffs = torch.from_numpy(split_coefficients(k, terms, rows, rng)).cuda() for ids, transform, local, cols, offset in blocks: inner = transform.size(0) raw = torch.zeros((rows, inner), device='cuda', dtype=torch.int8) evaluate[(triton.cdiv(local, 128), rows)]( raw, ids, ids, coeffs, local, inner, len(terms), a, False, 128) matrix[:, offset:offset + cols] = centered(torch._int_mm(raw, transform)[:, :cols]) return certify_samples(n, slab, scratch, samples, initial=initial) 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('--initial-slabs', nargs=2, type=int, metavar=('COUNT', 'SIZE'), help='begin the first primitive layer with COUNT slabs of SIZE rows') parser.add_argument('--scratch', help='parent directory for temporary echelon blocks') args = parser.parse_args() if not (0 <= args.t <= args.y and args.y + args.t <= args.a * args.k < PRIME): parser.error(f'expected 0 <= t <= y and y+t <= a*k < {PRIME}') if args.slab <= 0 or args.slab % PANEL or args.slab * 125**2 >= 2**31 - 125: parser.error('invalid slab size') count, size = args.initial_slabs or (0, args.slab) if count < 0 or size <= 0 or size % PANEL or size * 125**2 >= 2**31 - 125: parser.error('invalid initial slab schedule') for h in range(args.t, -1, -1): with tempfile.TemporaryDirectory(dir=args.scratch) as path: if not certify_layer(args.a, args.k, args.y + args.t, h, args.slab, Path(path), (size,) * count if h == args.t else ()): raise SystemExit(1)