Fewer-T field multiplication, m = 283

T count submission #114

zihan_chen · submitted · verified 7 d ago · Accepted CC BY 4.0

T gates8,167

Verifier report

m
283
n
849
r
8167
check
all 611960049 signature-tensor entries match
verify seconds
8.53
View raw report
{
 "m": 283,
 "n": 849,
 "r": 8167,
 "check": "all 611960049 signature-tensor entries match",
 "verify_seconds": 8.53
}

Submission file

Download submission JSON under Creative Commons Attribution 4.0 International (license file)

sha256 a05b797b6e6527fbbcb4e1ade7164f559ed740e910fb5f2ea1c3f214a504f8c7 · 1,764,113 bytes · verifier 0183d00bf58d

License

License: Creative Commons Attribution 4.0 International (CC BY 4.0, the default). Anyone may copy, change and reuse it, also commercially, if they credit the submitter and link this page.

Credit: zihan_chen, QArena submission T count #114, with a link to this page. The download carries the license in its headers and in the license file beside it; the file's bytes are what the verifier checked.

Builds on

This submission names no earlier submission.

Cited by

No other submission names this submission yet.

How citations count

Attached code

solve.py 74.1 KB

#!/usr/bin/env python3
"""Frozen standalone QArena tcount generator (Python 3.10+, standard library).
Usage: python3 -I solve.py mult-233 output.json

MIT Polytof small-field CPD/Waring data is embedded with the full notice below:
https://github.com/ZIB-IOL/polytof/tree/0dcac107d15adc34dc646242d222f21ae7d32699
Khoruzhii, Gelss, Pokutta, arXiv:2602.15285v2 (paper CC BY 4.0).
Original CRT/Toom assembly and affine-flat descent are accompanied by an
independent packed-integer implementation of TOHPE: Vandaele,
arXiv:2407.08695v2 (CC BY 4.0), Theorem 1 and Algorithm 2.
All data comes from licensed original paper repositories; no contestant
artifacts are used. This generator needs no other source file, official
example, network, third-party package, subprocess, or solver installation.
Deterministic iteration counts and shifts replace all wall-time stopping.
"""
import argparse,collections,json,random,types
from pathlib import Path
POLYTOF_LICENSE = 'MIT License\n\nCopyright (c) 2026 Kirill Khoruzhii\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'
SMALL_LIBRARY = {'10': {'polynomial': 1033, 'triples': [[143, 143, 563], [874, 874, 933], [997, 997, 406], [321, 321, 635], [76, 76, 1018], [269, 269, 385], [557, 557, 748], [574, 574, 455], [19, 19, 811], [633, 633, 104], [934, 934, 448], [479, 479, 424], [648, 648, 606], [920, 920, 316], [272, 272, 866], [671, 671, 900], [848, 848, 228], [463, 463, 864], [880, 880, 578], [2, 2, 802], [882, 882, 352], [495, 495, 740], [850, 850, 678], [701, 701, 66], [421, 421, 207], [968, 968, 169], [621, 621, 102], [746, 746, 347], [700, 700, 832], [86, 86, 539], [847, 847, 911], [372, 372, 690], [571, 571, 317]]}, '2': {'polynomial': 7, 'triples': [[1, 1, 3], [2, 2, 1], [3, 3, 2]]}, '3': {'polynomial': 11, 'triples': [[1, 1, 7], [2, 2, 5], [4, 4, 1], [3, 3, 2], [5, 5, 4], [6, 6, 3]]}, '4': {'polynomial': 19, 'triples': [[1, 1, 9], [12, 12, 3], [13, 13, 10], [14, 14, 1], [8, 8, 6], [6, 6, 7], [15, 15, 14], [4, 4, 2], [11, 11, 12]]}, '5': {'polynomial': 37, 'triples': [[1, 1, 26], [2, 2, 19], [4, 4, 3], [8, 8, 6], [16, 16, 14], [3, 3, 18], [5, 5, 1], [20, 20, 2], [24, 24, 4], [13, 13, 24], [22, 22, 21], [27, 27, 13], [31, 31, 29]]}, '6': {'polynomial': 67, 'triples': [[55, 55, 17], [32, 32, 25], [23, 23, 8], [37, 37, 57], [26, 26, 15], [63, 63, 54], [47, 47, 45], [46, 46, 4], [1, 1, 41], [61, 61, 63], [20, 20, 19], [41, 41, 44], [34, 34, 3], [38, 38, 14], [4, 4, 13]]}, '7': {'polynomial': 131, 'triples': [[1, 1, 54], [2, 2, 36], [3, 3, 36], [127, 127, 81], [42, 42, 56], [85, 85, 56], [109, 109, 40], [54, 54, 24], [91, 91, 48], [105, 105, 79], [58, 58, 85], [116, 116, 41], [83, 83, 26], [29, 29, 124], [78, 78, 51], [57, 57, 47], [114, 114, 22], [92, 92, 100], [75, 75, 93], [101, 101, 57], [46, 46, 114], [64, 64, 72]]}, '8': {'polynomial': 285, 'triples': [[35, 35, 34], [102, 102, 76], [69, 69, 110], [31, 31, 72], [42, 42, 21], [53, 53, 93], [23, 23, 221], [142, 142, 147], [153, 153, 78], [97, 97, 53], [116, 116, 162], [21, 21, 151], [205, 205, 98], [124, 124, 175], [177, 177, 205], [209, 209, 229], [78, 78, 107], [159, 159, 142], [125, 125, 156], [70, 70, 167], [59, 59, 59], [129, 129, 79], [12, 12, 10], [141, 141, 69]]}, '9': {'polynomial': 529, 'triples': [[33, 33, 87], [252, 252, 167], [302, 302, 434], [221, 221, 240], [271, 271, 277], [466, 466, 322], [493, 493, 314], [454, 454, 103], [376, 376, 246], [43, 43, 349], [149, 149, 145], [190, 190, 427], [161, 161, 196], [166, 166, 308], [22, 22, 207], [7, 7, 496], [183, 183, 507], [176, 176, 319], [217, 217, 228], [134, 134, 165], [416, 416, 394], [95, 95, 65], [377, 377, 303], [294, 294, 459], [212, 212, 444], [276, 276, 88], [450, 450, 19], [448, 448, 484], [278, 278, 75], [214, 214, 503]]}}
MODULI = {2: [2, 1, 0], 3: [3, 1, 0], 4: [4, 1, 0], 5: [5, 2, 0], 6: [6, 1, 0], 7: [7, 1, 0], 8: [8, 4, 3, 1, 0], 9: [9, 4, 0], 10: [10, 3, 0], 16: [16, 5, 3, 1, 0], 32: [32, 7, 3, 2, 0], 163: [163, 7, 6, 3, 0], 233: [233, 74, 0], 283: [283, 12, 7, 5, 0]}

def reduce_poly(v, p):
    degree = p.bit_length() - 1
    while v.bit_length() > degree:
        v ^= p << v.bit_length() - degree - 1
    return v

def transpose(columns, width):
    rows = [0] * width
    for j, column in enumerate(columns):
        while column:
            bit = column & -column
            rows[bit.bit_length() - 1] |= 1 << j
            column ^= bit
    return rows

def invert(rows):
    n = len(rows)
    a = [v | 1 << i << n for i, v in enumerate(rows)]
    for j in range(n):
        pivot = next((i for i in range(j, n) if a[i] >> j & 1))
        a[j], a[pivot] = (a[pivot], a[j])
        for i in range(n):
            if i != j and a[i] >> j & 1:
                a[i] ^= a[j]
    assert [v & (1 << n) - 1 for v in a] == [1 << i for i in range(n)]
    return [v >> n for v in a]

class Linear:

    def __init__(self, images):
        self.tables = []
        for offset in range(0, len(images), 8):
            table = [0] * 256
            for v in range(1, 256):
                bit = v & -v
                j = bit.bit_length() - 1
                table[v] = table[v ^ bit] ^ (images[offset + j] if offset + j < len(images) else 0)
            self.tables.append(table)

    def apply(self, v):
        out = 0
        for table in self.tables:
            out ^= table[v & 255]
            v >>= 8
        return out

    def many(self, rows):
        cache = {v: self.apply(v) for v in set(rows)}
        return [cache[v] for v in rows]

def decode(art):
    m = art['m']
    hexed = art.get('encoding') == 'hex-v1'
    parse = lambda s: int(s, 16) if hexed else int(s[::-1], 2)
    u = [parse(v) for v in art['U']]
    v = [parse(v) for v in art['V']]
    w = transpose([parse(s) for s in art['W']], len(u))
    return (m, u, v, w)

def encode(m, u, v, w):
    rank = len(u)
    hexed = m >= 163

    def fmt(value, width):
        return f'{value:0{(width + 3) // 4}x}' if hexed else f'{value:0{width}b}'[::-1]
    art = {'m': m}
    if hexed:
        art['encoding'] = 'hex-v1'
    art.update(U=[fmt(row, m) for row in u], V=[fmt(row, m) for row in v], W=[fmt(row, rank) for row in transpose(w, m)])
    return art

def xor_count(u, v, w):
    union = 0
    for column in w:
        union |= column
    return sum((x.bit_count() for x in u + v + w)) - sum((bool(x) for x in u + v)) - union.bit_count()

def karatsuba(m):

    def recursion(a, b):
        if len(a) == 1:
            return [(a[0], b[0], 1)] if a[0] and b[0] else []
        k = (len(a) + 1) // 2
        lo = recursion(a[:k], b[:k])
        hi = recursion(a[k:], b[k:])
        aa = [a[i] ^ (a[k + i] if k + i < len(a) else 0) for i in range(k)]
        bb = [b[i] ^ (b[k + i] if k + i < len(b) else 0) for i in range(k)]
        middle = recursion(aa, bb)
        return [(u, v, w ^ w << k) for u, v, w in lo] + [(u, v, w << k ^ w << 2 * k) for u, v, w in hi] + [(u, v, w << k) for u, v, w in middle]
    triples = recursion([1 << i for i in range(m)], [1 << i for i in range(m)])
    p = sum((1 << e for e in MODULI[m]))
    merged = {}
    for u, v, w in triples:
        merged[u, v] = merged.get((u, v), 0) ^ reduce_poly(w, p)
    triples = [(u, v, w) for (u, v), w in merged.items() if w]
    return encode(m, [x[0] for x in triples], [x[1] for x in triples], [x[2] for x in triples])

def gram(m, p):
    coefficients = [m - i for i in range(m) if p >> i & 1]
    powers = [m & 1] + [0] * (2 * m - 2)
    for k in range(1, len(powers)):
        value = k & 1 if k <= m and k in coefficients else 0
        for j in coefficients:
            if j < k or (k > m and j <= k):
                value ^= powers[k - j]
        powers[k] = value
    return [sum((powers[i + j] << j for j in range(m))) for i in range(m)]

def triality_transform(u, v, w, m, p, mode):
    if mode == 0:
        return (u.copy(), v.copy(), w.copy())
    rows = gram(m, p)
    to_dual = Linear(rows)
    from_dual = Linear(transpose(invert(rows), m))
    if mode == 1:
        return (to_dual.many(w), v.copy(), from_dual.many(u))
    if mode == 2:
        return (u.copy(), to_dual.many(w), from_dual.many(v))
    raise ValueError(mode)

def pmul(a, b):
    result = 0
    while b:
        bit = b & -b
        result ^= a << bit.bit_length() - 1
        b ^= bit
    return result

def quotient(a, b):
    q = 0
    d = b.bit_length()
    while a.bit_length() >= d:
        j = a.bit_length() - d
        a ^= b << j
        q ^= 1 << j
    assert a == 0
    return q

def inverse_poly(a, p):
    u, v = (a, p)
    x, y = (1, 0)
    while u != 1:
        if not u:
            raise ValueError('non-unit in CRT inverse')
        j = u.bit_length() - v.bit_length()
        if j < 0:
            u, v = (v, u)
            x, y = (y, x)
            j = -j
        u ^= v << j
        x ^= y << j
    return reduce_poly(x, p)

def gmultiply(a, b, p):
    return reduce_poly(pmul(a, b), p)

def gpower(a, e, p):
    out = 1
    while e:
        if e & 1:
            out = gmultiply(out, a, p)
        a = gmultiply(a, a, p)
        e >>= 1
    return out

def evaluate(poly, a, p):
    value = 0
    for i in reversed(range(poly.bit_length())):
        value = gmultiply(value, a, p) ^ poly >> i & 1
    return value

def irreducibles(d):
    out = []
    for p in range(1 << d | 1, 1 << d + 1, 2):
        reducible = False
        for k in range(1, d // 2 + 1):
            for divisor in range(1 << k | 1, 1 << k + 1, 2):
                if reduce_poly(p, divisor) == 0:
                    reducible = True
                    break
            if reducible:
                break
        if not reducible:
            out.append(p)
    return out

def truncated(k):
    triples = []
    for i in range(k):
        w = 1 << 2 * i if 2 * i < k else 0
        for j in range(k):
            if j != i and i + j < k:
                w ^= 1 << i + j
        triples.append((1 << i, 1 << i, w))
    for i in range(k):
        for j in range(i + 1, k):
            if i + j < k:
                triples.append((1 << i | 1 << j, 1 << i | 1 << j, 1 << i + j))
    return [t for t in triples if t[2]]

def ring4_truncated3(k=3):
    out = []
    for u, v, w in truncated(k):
        for a, b, c in [(1, 1, 3), (2, 2, 1), (3, 3, 2)]:
            embed = lambda value, scalar: sum((scalar << 2 * j for j in range(k) if value >> j & 1))
            out.append((embed(u, a), embed(v, b), embed(w, c)))
    return out

def choose_places(m, seed=0):
    rng = random.Random(seed)
    groups = []
    for tag in ['x', 'x1', 'infty']:
        opts = [(0, 0, None)]
        for k, r in enumerate([0, 1, 3, 5, 8, 11]):
            if k:
                opts.append((k, r, (tag, k)))
        groups.append(opts)
    groups.append([(0, 0, None), (2, 3, ('q2', 1)), (4, 9, ('q2', 2)), (6, 15, ('q2', 3))])
    ranks = {3: 6, 4: 9, 5: 13, 6: 15, 7: 22, 8: 24, 9: 30, 10: 33}
    for d in range(3, 11):
        polys = irreducibles(d)
        if seed:
            rng.shuffle(polys)
        groups += [[(0, 0, None), (d, ranks[d], ('field', p))] for p in polys]
    limit = 2 * m + 10
    dp = [10 ** 9] * (limit + 1)
    path = [None] * (limit + 1)
    dp[0] = 0
    for options in groups:
        new = dp.copy()
        np = path.copy()
        for degree, cost in enumerate(dp):
            if cost == 10 ** 9:
                continue
            for size, rank, place in options:
                if size and degree + size <= limit and (cost + rank < new[degree + size]):
                    new[degree + size] = cost + rank
                    np[degree + size] = (path[degree], place)
        dp, path = (new, np)
    degree = min(range(2 * m - 1, limit + 1), key=lambda d: (dp[d], d))
    places = []
    cursor = path[degree]
    while cursor:
        cursor, place = cursor
        places.append(place)
    return (places[::-1], dp[degree], degree)

def polynomial_place(place):
    tag, v = place
    if tag == 'field':
        return v
    if tag == 'x':
        return 1 << v
    if tag == 'x1':
        return pmul_power(3, v)
    if tag == 'q2':
        return pmul_power(7, v)
    if tag == 'infty':
        return None
    raise ValueError(place)

def pmul_power(a, e):
    out = 1
    for _ in range(e):
        out = pmul(out, a)
    return out

def basis_variants(place, library):
    tag, value = place
    q = polynomial_place(place)
    if tag == 'field':
        d = q.bit_length() - 1
        scheme = library[str(d)]
        srcpoly = scheme['polynomial']
        triples = [tuple(t) for t in scheme['triples']]
        roots = [a for a in range(1 << d) if evaluate(srcpoly, a, q) == 0]
        for root in roots:
            images = [1]
            for _ in range(1, d):
                images.append(gmultiply(images[-1], root, q))
            yield (triples, images, {'root': root})
    elif tag in ['x', 'x1']:
        k = value
        base = 2 if tag == 'x' else 3
        images = [1]
        for _ in range(1, k):
            images.append(gmultiply(images[-1], base, q))
        yield (truncated(k), images, {'coordinate': 'x' if tag == 'x' else 'x+1'})
    elif tag == 'q2':
        if value == 1:
            for a in [2, 3]:
                yield ([(1, 1, 3), (2, 2, 1), (3, 3, 2)], [1, a], {'root': a})
        elif value in [2, 3]:
            base_alpha = 2 ^ 7 ^ (pmul(7, 7) if value == 3 else 0)
            for alpha in [base_alpha, base_alpha ^ 1]:
                scalars = [0, 1, alpha, alpha ^ 1]
                for eta in scalars[1:]:
                    for lam in scalars if value == 3 else [0]:
                        t = gmultiply(eta, 7, q) ^ gmultiply(lam, pmul(7, 7), q)
                        images = []
                        for j in range(value):
                            base = gpower(t, j, q)
                            images += [base, gmultiply(base, alpha, q)]
                        yield (ring4_truncated3(value), images, {'root': alpha, 'eta': eta, 'lambda': lam})
        else:
            raise ValueError('q2^2 construction not selected in supported layouts')
    else:
        raise ValueError(place)

def construct_crt(m, seed=0, root_search=True, triality_search=True):
    library = SMALL_LIBRARY
    places, expected, total_degree = choose_places(m, seed)
    target = sum((1 << e for e in MODULI[m]))
    finite = [p for p in places if p[0] != 'infty']
    infinity = next((v for tag, v in places if tag == 'infty'), 0)
    modulus = 1
    for place in finite:
        modulus = pmul(modulus, polynomial_place(place))
    U = []
    V = []
    W = []
    details = []
    for place in finite:
        q = polynomial_place(place)
        degree = q.bit_length() - 1
        other = quotient(modulus, q)
        h = inverse_poly(reduce_poly(other, q), q)
        outputbasis = [reduce_poly(pmul(other, reduce_poly(h << j, q)), target) for j in range(degree)]
        residues = []
        value = 1
        for i in range(m):
            residues.append(value)
            value = reduce_poly(value << 1, q)
        inputembed = Linear(transpose(residues, degree))
        outputembed = Linear(outputbasis)
        best = None
        for triples, images, choice in basis_variants(place, library):
            invrows = invert(transpose(images, degree))
            to_inner = Linear(invrows)
            to_quotient = Linear(images)
            modes = [0, 1] if triality_search and place[0] == 'field' else [0]
            for mode in modes:
                local = triples
                if mode:
                    source_degree = degree
                    source_poly = library[str(degree)]['polynomial']
                    a, b, c = triality_transform(*map(list, zip(*triples)), source_degree, source_poly, mode)
                    local = list(zip(a, b, c))
                us = [inputembed.apply(to_inner.apply(u)) for u, v, w in local]
                vs = [inputembed.apply(to_inner.apply(v)) for u, v, w in local]
                ws = [outputembed.apply(to_quotient.apply(w)) for u, v, w in local]
                cost = sum((t.bit_count() for t in us + vs + ws))
                if best is None or cost < best[0]:
                    best = (cost, us, vs, ws, {**choice, 'triality': mode})
            if not root_search:
                break
        cost, us, vs, ws, choice = best
        U += us
        V += vs
        W += ws
        details.append({'place': place, 'degree': degree, 'rank': len(us), 'weight': cost, 'basis': choice})
    if infinity:
        outputs = [reduce_poly(1 << 2 * m - 2 - j ^ reduce_poly(1 << 2 * m - 2 - j, modulus), target) for j in range(infinity)]
        outputembed = Linear(outputs)

        def reverse_top(form):
            return sum((1 << m - 1 - j for j in range(infinity) if form >> j & 1))
        triples = truncated(infinity)
        U += [reverse_top(u) for u, v, w in triples]
        V += [reverse_top(v) for u, v, w in triples]
        W += [outputembed.apply(w) for u, v, w in triples]
        details.append({'place': ['infty', infinity], 'degree': infinity, 'rank': len(triples)})
    assert len(U) == expected
    return (encode(m, U, V, W), {'m': m, 'seed': seed, 'rank': len(U), 'xor': xor_count(U, V, W), 'total_degree': total_degree, 'finite_degree': modulus.bit_length() - 1, 'infinity': infinity, 'places': details, 'root_search': root_search, 'triality_search': triality_search, 'source': 'polytof 0dcac107d15adc34dc646242d222f21ae7d32699; small CPDs MIT'})

def construct_toom(m, seed=0):
    if m not in [16, 32]:
        raise ValueError('supported tower sizes: 16,32')
    rng = random.Random(seed)
    k = m // 4
    count = 2 * k - 1
    p = sum((1 << e for e in MODULI[m]))
    inner = SMALL_LIBRARY['4']
    q = inner['polynomial']
    triples = inner['triples']
    for candidate in range(2, 64):
        z = gpower(candidate, ((1 << m) - 1) // 15, p)
        if z not in [0, 1] and gpower(z, 15, p) == 1 and (gpower(z, 5, p) != 1) and (gpower(z, 3, p) != 1):
            break
    roots = [gpower(z, j, p) for j in range(15) if evaluate(q, gpower(z, j, p), p) == 0]
    alpha = roots[rng.randrange(len(roots))] if seed else roots[0]
    apow = [1]
    for _ in range(1, 4):
        apow.append(gmultiply(apow[-1], alpha, p))
    embed = Linear(apow)
    beta = 2 ^ (embed.apply(rng.randrange(16)) if seed else 0)
    images = []
    b = 1
    for _ in range(k):
        images += [gmultiply(a, b, p) for a in apow]
        b = gmultiply(b, beta, p)
    invrows = invert(transpose(images, m))
    inputmap = Linear(invrows)
    infinity = bool(seed % 2)
    points = list(range(16))
    if seed:
        rng.shuffle(points)
    points = points[:count - int(infinity)]
    contributions = []
    for t in points:
        numer = 1
        denom = 1
        for other in points:
            if other != t:
                numer = gmultiply(numer, beta ^ embed.apply(other), p)
                denom = gmultiply(denom, t ^ other, q)
        contributions.append(gmultiply(numer, embed.apply(gpower(denom, 14, q)), p))
    if infinity:
        c = gpower(beta, count - 1, p)
        for t, basis in zip(points, contributions):
            c ^= gmultiply(embed.apply(gpower(t, count - 1, q)), basis, p)
        contributions.append(c)
    labels = points + (['inf'] if infinity else [])
    U = []
    V = []
    W = []
    for label, basis in zip(labels, contributions):
        if label == 'inf':
            coefficient_images = [0] * (k - 1) + [1]
        else:
            coefficient_images = [1]
            for _ in range(1, k):
                coefficient_images.append(gmultiply(coefficient_images[-1], label, q))
        for u, v, w in triples:

            def lift(form):
                tower = 0
                for j, coef in enumerate(coefficient_images):
                    local = 0
                    for a in range(4):
                        local |= ((form & gmultiply(coef, 1 << a, q)).bit_count() & 1) << a
                    tower |= local << 4 * j
                return inputmap.apply(tower)
            U.append(lift(u))
            V.append(lift(v))
            W.append(gmultiply(embed.apply(w), basis, p))
    meta = {'m': m, 'seed': seed, 'rank': len(U), 'xor': xor_count(U, V, W), 'alpha': alpha, 'beta': beta, 'evaluation_points': labels, 'method': 'GF(16) tower, 2k-1 Toom evaluations, rank-9 inner products from MIT polytof data'}
    return (encode(m, U, V, W), meta)

def initial_field(m):
    d = SMALL_LIBRARY[str(m)]
    p = sum((1 << e for e in MODULI[m]))
    triples = d['triples']
    if d['polynomial'] == p:
        return [list(t) for t in zip(*triples)]
    root = next((a for a in range(1 << m) if evaluate(d['polynomial'], a, p) == 0))
    images = [1]
    for _ in range(1, m):
        images.append(gmultiply(images[-1], root, p))
    rowmap = Linear(invert(transpose(images, m)))
    outmap = Linear(images)
    return [[rowmap.apply(t[0]) for t in triples], [rowmap.apply(t[1]) for t in triples], [outmap.apply(t[2]) for t in triples]]

def linear_power(images, power):
    result = [1 << i for i in range(len(images))]
    while power:
        step = Linear(images)
        if power & 1:
            result = step.many(result)
        power >>= 1
        if power:
            images = step.many(images)
    return Linear(result)

def frob_factors(m, u, v, w, power):
    if not power:
        return (u, v, w)
    p = sum((1 << e for e in MODULI[m]))
    columns = [reduce_poly(1 << 2 * i, p) for i in range(m)]
    rows = transpose(columns, m)
    inputs = linear_power(rows, power)
    outputs = linear_power(transpose(invert(rows), m), power)
    return (inputs.many(u), inputs.many(v), outputs.many(w))

def scalar_factors(m, u, v, w, left, right):
    if left == right == 1:
        return (u, v, w)
    p = sum((1 << e for e in MODULI[m]))
    delta = inverse_poly(gmultiply(left, right, p), p)
    il = Linear(transpose([gmultiply(left, 1 << j, p) for j in range(m)], m))
    ir = Linear(transpose([gmultiply(right, 1 << j, p) for j in range(m)], m))
    ow = Linear([gmultiply(delta, 1 << j, p) for j in range(m)])
    return (il.many(u), ir.many(v), ow.many(w))
F=types.SimpleNamespace(**globals().copy())
LIB={'10': {'columns': [565496060,
                    845533474,
                    42256499,
                    846020377,
                    42256636,
                    42398835,
                    42398972,
                    846019874,
                    845533977,
                    468121369,
                    565927027,
                    468120691,
                    468410137,
                    468409459,
                    565495923,
                    177591065,
                    953612057,
                    565797116,
                    953611516,
                    953770777,
                    953770236,
                    991653,
                    423625325,
                    101475860,
                    565797717,
                    101476181,
                    101278228,
                    101278549,
                    566056789,
                    873283059,
                    505239321,
                    107386477,
                    505239381,
                    505177881,
                    505177941,
                    566056468,
                    177590893,
                    967661337,
                    565995028,
                    967661076,
                    967402265,
                    967402004,
                    424492653,
                    566044977,
                    259366193,
                    565564013,
                    259366684,
                    259860785,
                    259861276,
                    424492322,
                    991232,
                    1036374812,
                    566044962,
                    1036374306,
                    1036856092,
                    1036855586,
                    565564175,
                    565550385,
                    319148828,
                    565550863,
                    319148815,
                    319135516,
                    319135503,
                    565693861,
                    565708320,
                    657580576,
                    423624994,
                    657580121,
                    657983008,
                    657982553,
                    364287769,
                    566050413,
                    1035377753,
                    565708799,
                    1035378687,
                    1035469913,
                    1035470847,
                    431603,
                    565305888,
                    993434713,
                    565305734,
                    993435014,
                    993124441,
                    993124742,
                    565994917,
                    565772015,
                    72539887,
                    511475,
                    72539239,
                    72941295,
                    72940647,
                    511397,
                    565183257,
                    846634087,
                    565772287,
                    846635007,
                    846789735,
                    846790655,
                    565615991,
                    565370607,
                    395746407,
                    565370231,
                    395746679,
                    395500647,
                    395500919,
                    364668697,
                    565960406,
                    435266262,
                    364668325,
                    435265609,
                    435936982,
                    435936329,
                    872847129,
                    565693939,
                    217486757,
                    566050291,
                    804691737,
                    805035081,
                    805035801,
                    177210137,
                    565289686,
                    397843529,
                    565289350,
                    397843846,
                    397516873,
                    397517190,
                    107945984,
                    364287397,
                    93756523,
                    565927707,
                    565960473,
                    94067819,
                    94068507,
                    177209765,
                    872846835,
                    328636185,
                    107385856,
                    328636187,
                    328638233,
                    328638235,
                    565613675,
                    565182754,
                    934713113,
                    565615723,
                    934712427,
                    935026457,
                    935025771,
                    94136393,
                    178201197,
                    735865254,
                    431725,
                    735864905,
                    735827366,
                    735827017,
                    565614363,
                    873283353,
                    805033755,
                    93756489,
                    805033033,
                    804691739,
                    217486336,
                    94136742,
                    93397787,
                    29087515,
                    93397414,
                    29087142,
                    28386075,
                    28385702,
                    621,
                    107946605,
                    217055653,
                    178200997,
                    217055232],
        'file': '0733-00173.npy',
        'polynomial': None},
 '2': {'columns': [1, 37, 48, 42, 49, 52, 53, 41, 14, 22, 12, 20, 30, 28, 9, 10, 38],
       'file': '0725-00017.npy',
       'polynomial': None},
 '3': {'columns': [56,
                   385,
                   141,
                   251,
                   448,
                   142,
                   1,
                   253,
                   470,
                   462,
                   464,
                   329,
                   347,
                   272,
                   391,
                   63,
                   275,
                   317,
                   91,
                   127,
                   123,
                   333,
                   150,
                   455,
                   312,
                   89,
                   147,
                   345,
                   457],
       'file': '0726-00029.npy',
       'polynomial': None},
 '4': {'columns': [1792,
                   1928,
                   757,
                   672,
                   3569,
                   3342,
                   3329,
                   872,
                   162,
                   3406,
                   82,
                   3397,
                   110,
                   3573,
                   865,
                   645,
                   1,
                   1806,
                   2904,
                   2949,
                   2952,
                   754,
                   640,
                   1896,
                   1920,
                   1010,
                   856,
                   850,
                   84,
                   78,
                   1902,
                   68,
                   2900,
                   2885,
                   2884,
                   160,
                   97,
                   1009,
                   674],
       'file': '0727-00039.npy',
       'polynomial': None},
 '5': {'columns': [24648,
                   18434,
                   1090,
                   25061,
                   13940,
                   1026,
                   1024,
                   29924,
                   24645,
                   22075,
                   799,
                   13439,
                   14084,
                   14111,
                   30468,
                   30491,
                   3168,
                   21741,
                   1093,
                   1268,
                   3300,
                   18529,
                   25064,
                   8288,
                   72,
                   8289,
                   8256,
                   8257,
                   557,
                   493,
                   6381,
                   29947,
                   6373,
                   6637,
                   6629,
                   64,
                   18498,
                   21755,
                   488,
                   18531,
                   13924,
                   18435,
                   1253,
                   771,
                   4099,
                   18497,
                   4123,
                   4867,
                   4891,
                   571,
                   1652,
                   3316,
                   1632,
                   27,
                   127,
                   3680,
                   99,
                   3188,
                   13428,
                   3684,
                   22061],
       'file': '0728-00061.npy',
       'polynomial': None},
 '6': {'columns': [117248,
                   196648,
                   107462,
                   197754,
                   107475,
                   106694,
                   106707,
                   226928,
                   196666,
                   247272,
                   2099,
                   247283,
                   247848,
                   247859,
                   117267,
                   26880,
                   58356,
                   26886,
                   58323,
                   57460,
                   57427,
                   24768,
                   2560,
                   218420,
                   2310,
                   218390,
                   218740,
                   218710,
                   114880,
                   24774,
                   9302,
                   1298,
                   9298,
                   9494,
                   9490,
                   966,
                   2322,
                   87122,
                   1136,
                   87162,
                   88338,
                   88378,
                   226416,
                   226390,
                   53368,
                   1491,
                   53331,
                   54776,
                   54739,
                   51,
                   1648,
                   135224,
                   1128,
                   135219,
                   136696,
                   136691,
                   197736,
                   2579,
                   151610,
                   1332,
                   151552,
                   153914,
                   153856,
                   226902,
                   2104,
                   118840,
                   1512,
                   118824,
                   120888,
                   120872,
                   1012,
                   1656,
                   12408,
                   114899,
                   12404,
                   13944,
                   13940],
       'file': '0729-00077.npy',
       'polynomial': None},
 '7': {'columns': [1238293,
                   948998,
                   1133958,
                   1644470,
                   1611060,
                   1607360,
                   1607348,
                   759103,
                   1644469,
                   942086,
                   933951,
                   1238325,
                   1643828,
                   1643829,
                   1415094,
                   1008093,
                   133213,
                   1644214,
                   133242,
                   139741,
                   139770,
                   118150,
                   48,
                   1300148,
                   935936,
                   1300149,
                   1300020,
                   1300021,
                   933936,
                   1414837,
                   1414711,
                   1415095,
                   1414709,
                   939957,
                   939959,
                   939732,
                   943413,
                   1873588,
                   935636,
                   1873620,
                   1869492,
                   1869524,
                   1607744,
                   939575,
                   1430906,
                   1008019,
                   1430803,
                   1434106,
                   1434003,
                   1011475,
                   2112,
                   1371968,
                   942080,
                   1371923,
                   1365312,
                   1365267,
                   949085,
                   944789,
                   118192,
                   1611130,
                   753728,
                   764565,
                   764608,
                   939741,
                   1607802,
                   2021040,
                   2048,
                   2021085,
                   2018736,
                   2018781,
                   122886,
                   122928,
                   344064,
                   8256,
                   344128,
                   352256,
                   352320,
                   753727,
                   759061,
                   578880,
                   944831,
                   578879,
                   584384,
                   584383,
                   1001181,
                   1011520,
                   1134045,
                   939568,
                   1644208,
                   1644084,
                   1644080,
                   1001152,
                   1145606,
                   935645,
                   1145693,
                   1234229,
                   936029,
                   8240,
                   1414838,
                   943381,
                   1234197],
       'file': '0730-00101.npy',
       'polynomial': None},
 '8': {'columns': [12157176,
                   1598544,
                   12181688,
                   1799,
                   9011416,
                   8978616,
                   8978648,
                   1310978,
                   14902352,
                   1966339,
                   1595216,
                   1966338,
                   1966083,
                   1966082,
                   14899024,
                   14221314,
                   10435307,
                   16351480,
                   10435128,
                   10474475,
                   10474296,
                   2313963,
                   14275384,
                   11292278,
                   14275330,
                   11292395,
                   11326326,
                   11326443,
                   9011256,
                   14919855,
                   550063,
                   54018,
                   4784312,
                   567471,
                   567395,
                   2323615,
                   1595235,
                   4817080,
                   2308767,
                   6648991,
                   6634040,
                   6634143,
                   4784184,
                   1311233,
                   6707043,
                   1311235,
                   12173496,
                   524801,
                   524803,
                   6749539,
                   6749641,
                   14270520,
                   12124408,
                   14270712,
                   14919836,
                   14221560,
                   9035960,
                   1574656,
                   1792,
                   550104,
                   1573080,
                   14899100,
                   1598680,
                   4193737,
                   1543,
                   16351416,
                   1537,
                   6707145,
                   525831,
                   525825,
                   2323574,
                   2308843,
                   12170862,
                   2313846,
                   29814,
                   12170968,
                   54134,
                   4129436,
                   9035832,
                   9241289,
                   570990,
                   9241244,
                   9263049,
                   9263004,
                   16367800,
                   16367864,
                   6778328,
                   570883,
                   6778115,
                   6797016,
                   6796803,
                   1310979,
                   1311489,
                   1574663,
                   1311490,
                   4816952,
                   769,
                   770,
                   12157144,
                   552302,
                   12976238,
                   552408,
                   12976131,
                   13004142,
                   13004035,
                   209,
                   12124270,
                   6619192,
                   29905,
                   6619345,
                   4193635,
                   6649041,
                   12173368,
                   581475,
                   1572864,
                   581383,
                   12181560,
                   1630051,
                   1629959,
                   4129481,
                   14902447,
                   4171875,
                   4171932],
       'file': '0731-00123.npy',
       'polynomial': 285},
 '9': {'columns': [176801,
                   32972593,
                   36778768,
                   32945127,
                   36778801,
                   36794640,
                   36794673,
                   103364401,
                   117906405,
                   32600525,
                   107268639,
                   32600369,
                   32541133,
                   32540977,
                   32972775,
                   57595107,
                   94669027,
                   14332455,
                   94669261,
                   94819555,
                   94819789,
                   57488144,
                   107251939,
                   11366861,
                   117782501,
                   11366672,
                   11324365,
                   11324176,
                   85158,
                   103489329,
                   121162271,
                   57595152,
                   121162512,
                   121295903,
                   121296144,
                   107393777,
                   107269069,
                   57488099,
                   107252017,
                   43499262,
                   107402701,
                   107402271,
                   32944881,
                   107295473,
                   46187865,
                   18476703,
                   74313375,
                   46341977,
                   103370119,
                   107393779,
                   32846577,
                   8807092,
                   14359283,
                   129274713,
                   17124513,
                   129441625,
                   103461863,
                   134398,
                   99741671,
                   32846641,
                   43499399,
                   99819495,
                   74237087,
                   107296561,
                   17167102,
                   74343092,
                   103335257,
                   56398516,
                   56411295,
                   56411316,
                   129393185,
                   107295459,
                   56576159,
                   103364581,
                   99770913,
                   74224308,
                   99829793,
                   18565279,
                   103411687,
                   103397556,
                   129381409,
                   18565153,
                   103335092,
                   18494497,
                   117907187,
                   7,
                   130117286,
                   17284769,
                   130117127,
                   130034854,
                   130034695,
                   107421427,
                   14359079,
                   80825510,
                   43339143,
                   90273,
                   11271,
                   17124606,
                   80825527,
                   103412615,
                   132992161,
                   117907431,
                   132992183,
                   132997281,
                   132997303,
                   103488039,
                   80834214,
                   51470343,
                   117906163,
                   51470336,
                   51473927,
                   51473920,
                   107421671,
                   117782503,
                   54357687,
                   103418919,
                   54357504,
                   54263991,
                   54263808,
                   90112,
                   17167239,
                   2973703,
                   80834231,
                   2973879,
                   2883591,
                   2883767,
                   127742,
                   103488485,
                   96078887,
                   43339006,
                   96079102,
                   96189991,
                   96190206,
                   107296743,
                   17284999,
                   79606433,
                   14332659,
                   79606311,
                   79675041,
                   79674919,
                   8763572,
                   224422,
                   103509158,
                   103535449,
                   37721,
                   103296166,
                   250713],
       'file': '0732-00147.npy',
       'polynomial': None}}
def toggle(s, xs):
    for x in xs:
        if x:
            if x in s:
                s.remove(x)
            else:
                s.add(x)
    return s

def artifact(m, columns):
    out = {'n': 3 * m}
    if m >= 163:
        out.update(encoding='hex-v1', columns=[f'{x:0{(3 * m + 3) // 4}x}' for x in sorted(columns)])
    else:
        out['columns'] = [f'{x:0{3 * m}b}'[::-1] for x in sorted(columns)]
    return out

def parse(art):
    return [int(x, 16) if art.get('encoding') else int(x[::-1], 2) for x in art['columns']]

def cc(z):
    u, v, w = z
    return [u, v, w, u ^ v, u ^ w, v ^ w, u ^ v ^ w]

def local_paper(m):
    d = LIB[str(m)]
    cols = d['columns']
    p = sum((1 << e for e in F.MODULI[m]))
    q = d['polynomial'] or p
    if p == q:
        return cols.copy()
    root = next((a for a in range(1 << m) if F.evaluate(q, a, p) == 0))
    images = [1]
    for _ in range(1, m):
        images.append(F.gmultiply(images[-1], root, p))
    inputmap = F.Linear(F.invert(F.transpose(images, m)))
    outputmap = F.Linear(images)
    mask = (1 << m) - 1
    return [inputmap.apply(x & mask) ^ inputmap.apply(x >> m & mask) << m ^ outputmap.apply(x >> 2 * m) << 2 * m for x in cols]

def coset_synthesis(gadgets, seed=0, passes=1):
    """Coordinate descent over affine 3-flats, each is an exact CCZ signature.

 Translating its seven nonzero subspace vectors by z and adding z leaves
 the cubic signature unchanged, including all repeated-index entries.
 """
    rng = random.Random(seed)
    order = list(range(len(gadgets)))
    rng.shuffle(order)
    offsets = [0] * len(gadgets)
    s = set()

    def flat(g, z):
        return [x ^ z for x in [0] + cc(g)]
    for i in order:
        toggle(s, cc(gadgets[i]))
    history = [len(s)]
    for it in range(passes):
        rng.shuffle(order)
        changed = 0
        for i in order:
            g = gadgets[i]
            old = offsets[i]
            toggle(s, flat(g, old))
            pivots = sorted([(x.bit_length() - 1, x) for x in g], reverse=True)

            def remainder(x):
                for j, v in pivots:
                    if x >> j & 1:
                        x ^= v
                return x
            counts = collections.Counter((remainder(x) for x in s))
            best = 0
            score = 7 - 2 * counts.get(0, 0)
            for z, c in counts.items():
                cost = 8 - 2 * c
                if cost < score or (cost == score and z < best):
                    best = z
                    score = cost
            offsets[i] = best
            toggle(s, flat(g, best))
            changed += best != old
        history.append(len(s))
        print('COSET', seed, it, len(s), changed, flush=True)
        if not changed:
            break
    return (sorted(s), {'seed': seed, 'passes': passes, 'history': history, 'offsets': offsets})

def translate_blocks(blocks, seed=0, passes=1):
    """TOHPE translation of each pure cubic block; exact, no ancillary wires."""
    rng = random.Random(seed)
    blocks = [sorted(toggle(set(), b)) for b in blocks]
    order = list(range(len(blocks)))
    rng.shuffle(order)
    shifts = [0] * len(blocks)
    s = set()

    def shifted(b, z):
        return [x ^ z for x in b] + ([z] if len(b) % 2 else [])
    for b in blocks:
        toggle(s, b)
    history = [len(s)]
    for it in range(passes):
        rng.shuffle(order)
        changed = 0
        for i in order:
            b = blocks[i]
            old = shifts[i]
            toggle(s, shifted(b, old))
            counts = collections.Counter((x ^ y for x in s for y in b))
            candidates = counts.keys() | s | set(b) | {0, old}
            bs = set(b)
            best = old
            score = None
            for z in candidates:
                cost = len(b) - 2 * counts.get(z, 0) - (z in bs)
                if len(b) % 2 and z:
                    cost += 1 - 2 * (z in s)
                if score is None or cost < score or (cost == score and z < best):
                    best = z
                    score = cost
            shifts[i] = best
            toggle(s, shifted(b, best))
            changed += best != old
        history.append(len(s))
        print('BLOCK', seed, it, len(s), changed, flush=True)
        if not changed:
            break
    return (sorted(s), {'seed': seed, 'history': history, 'shifts': shifts})

def small_truncated(k):
    triples = F.truncated(k)
    cols, meta = coset_synthesis([(u, v << k, w << 2 * k) for u, v, w in triples], 0, 2)
    return cols

def ring4(k):
    cols, _ = coset_synthesis([(u, v << 2 * k, w << 4 * k) for u, v, w in F.ring4_truncated3(k)], 0, 2)
    return cols

def choose_tplaces(m, seed):
    rng = random.Random(seed)
    groups = []
    trunc = {k: small_truncated(k) for k in range(1, 6)}
    rings = {k: ring4(k) for k in range(1, 4)}
    for tag in ['x', 'x1', 'infty']:
        groups.append([(0, 0, None)] + [(k, len(trunc[k]) - 1, (tag, k)) for k in range(1, 6)])
    groups.append([(0, 0, None)] + [(2 * k, len(rings[k]) - 1, ('q2', k)) for k in range(1, 4)])
    for d in range(3, 11):
        polys = F.irreducibles(d)
        if seed:
            rng.shuffle(polys)
        groups += [[(0, 0, None), (d, len(LIB[str(d)]['columns']) - 1, ('field', p))] for p in polys]
    limit = 2 * m + 10
    dp = [10 ** 9] * (limit + 1)
    path = [None] * (limit + 1)
    dp[0] = 0
    for options in groups:
        new = dp.copy()
        np = path.copy()
        for degree, cost in enumerate(dp):
            if cost == 10 ** 9:
                continue
            for size, rank, place in options:
                if size and degree + size <= limit and (cost + rank < new[degree + size]):
                    new[degree + size] = cost + rank
                    np[degree + size] = (path[degree], place)
        dp, path = (new, np)
    degree = min(range(2 * m - 1, limit + 1), key=lambda d: (dp[d], d))
    places = []
    cursor = path[degree]
    while cursor:
        cursor, place = cursor
        places.append(place)
    return (places[::-1], trunc, rings, degree)

def crt_blocks(m, seed=0):
    places, trunc, rings, total = choose_tplaces(m, seed)
    target = sum((1 << e for e in F.MODULI[m]))
    finite = [p for p in places if p[0] != 'infty']
    infty = next((v for tag, v in places if tag == 'infty'), 0)
    modulus = 1
    for p in finite:
        modulus = F.pmul(modulus, F.polynomial_place(p))
    blocks = []
    details = []
    for place in finite:
        tag, val = place
        q = F.polynomial_place(place)
        d = q.bit_length() - 1
        other = F.quotient(modulus, q)
        h = F.inverse_poly(F.reduce_poly(other, q), q)
        outbasis = [F.reduce_poly(F.pmul(other, F.reduce_poly(h << j, q)), target) for j in range(d)]
        residues = []
        v = 1
        for _ in range(m):
            residues.append(v)
            v = F.reduce_poly(v << 1, q)
        inputembed = F.Linear(F.transpose(residues, d))
        outputembed = F.Linear(outbasis)
        triples, images, choice = next(F.basis_variants(place, F.SMALL_LIBRARY))
        if tag == 'field':
            local = LIB[str(d)]['columns']
        elif tag in ['x', 'x1']:
            local = trunc[val]
        else:
            local = rings[val]
        invrows = F.invert(F.transpose(images, d))
        ai = F.Linear(invrows)
        co = F.Linear(images)
        mask = (1 << d) - 1
        b = [inputembed.apply(ai.apply(x & mask)) ^ inputembed.apply(ai.apply(x >> d & mask)) << m ^ outputembed.apply(co.apply(x >> 2 * d)) << 2 * m for x in local]
        blocks.append(b)
        details.append({'place': place, 'degree': d, 'r': len(b), 'basis': choice})
    if infty:
        outputs = [F.reduce_poly(1 << 2 * m - 2 - j ^ F.reduce_poly(1 << 2 * m - 2 - j, modulus), target) for j in range(infty)]
        out = F.Linear(outputs)
        mask = (1 << infty) - 1

        def rev(v):
            return sum((1 << m - 1 - j for j in range(infty) if v >> j & 1))
        b = [rev(x & mask) ^ rev(x >> infty & mask) << m ^ out.apply(x >> 2 * infty) << 2 * m for x in trunc[infty]]
        blocks.append(b)
        details.append({'place': ['infty', infty], 'degree': infty, 'r': len(b)})
    return (blocks, {'m': m, 'seed': seed, 'total_degree': total, 'places': details, 'raw_r': sum(map(len, blocks))})

def toom_blocks(m, seed=0):
    if m not in [16, 32]:
        raise ValueError('supported tower sizes: 16,32')
    rng = random.Random(seed)
    k = m // 4
    count = 2 * k - 1
    p = sum((1 << e for e in F.MODULI[m]))
    q = 19
    for candidate in range(2, 64):
        z = F.gpower(candidate, ((1 << m) - 1) // 15, p)
        if z not in [0, 1] and F.gpower(z, 15, p) == 1 and (F.gpower(z, 5, p) != 1) and (F.gpower(z, 3, p) != 1):
            break
    roots = [F.gpower(z, j, p) for j in range(15) if F.evaluate(q, F.gpower(z, j, p), p) == 0]
    alpha = roots[rng.randrange(len(roots))] if seed else roots[0]
    apow = [1]
    for _ in range(1, 4):
        apow.append(F.gmultiply(apow[-1], alpha, p))
    embed = F.Linear(apow)
    beta = 2 ^ (embed.apply(rng.randrange(16)) if seed else 0)
    images = []
    b = 1
    for _ in range(k):
        images += [F.gmultiply(a, b, p) for a in apow]
        b = F.gmultiply(b, beta, p)
    inputmap = F.Linear(F.invert(F.transpose(images, m)))
    infinity = bool(seed % 2)
    points = list(range(16))
    if seed:
        rng.shuffle(points)
    points = points[:count - int(infinity)]
    contributions = []
    for t in points:
        numer = 1
        denom = 1
        for other in points:
            if other != t:
                numer = F.gmultiply(numer, beta ^ embed.apply(other), p)
                denom = F.gmultiply(denom, t ^ other, q)
        contributions.append(F.gmultiply(numer, embed.apply(F.gpower(denom, 14, q)), p))
    if infinity:
        c = F.gpower(beta, count - 1, p)
        for t, basis in zip(points, contributions):
            c ^= F.gmultiply(embed.apply(F.gpower(t, count - 1, q)), basis, p)
        contributions.append(c)
    labels = points + (['inf'] if infinity else [])
    blocks = []
    for label, basis in zip(labels, contributions):
        if label == 'inf':
            ci = [0] * (k - 1) + [1]
        else:
            ci = [1]
            for _ in range(1, k):
                ci.append(F.gmultiply(ci[-1], label, q))

        def lift(form):
            tower = 0
            for j, coef in enumerate(ci):
                local = sum((((form & F.gmultiply(coef, 1 << a, q)).bit_count() & 1) << a for a in range(4)))
                tower |= local << 4 * j
            return inputmap.apply(tower)
        blocks.append([lift(x & 15) ^ lift(x >> 4 & 15) << m ^ F.gmultiply(embed.apply(x >> 8), basis, p) << 2 * m for x in LIB['4']['columns']])
    return (blocks, {'m': m, 'seed': seed, 'alpha': alpha, 'beta': beta, 'evaluation_points': labels, 'raw_r': sum(map(len, blocks))})
def clean(xs):
    s = set()
    for x in xs:
        if x:
            if x in s:
                s.remove(x)
            else:
                s.add(x)
    return sorted(s)

def apply(cols, z, y):
    return clean([x ^ (z if y >> i & 1 else 0) for i, x in enumerate(cols)] + ([z] if y.bit_count() % 2 else []))

def feature(x, n, pairs):
    out = x
    for bit, a, b in pairs:
        if x >> a & 1 and x >> b & 1:
            out |= bit
    return out

def basis(cols, n, pairs):
    piv = {}
    kernels = []
    for i, x in enumerate(cols):
        a = feature(x, n, pairs)
        y = 1 << i
        while a:
            j = a.bit_length() - 1
            if j not in piv:
                piv[j] = (a, y)
                break
            v, w = piv[j]
            a ^= v
            y ^= w
        if not a:
            kernels.append(y)
    return (piv, kernels)

def tohpe_action(cols, y, rng, limit=0):
    ys = [x for i, x in enumerate(cols) if y >> i & 1]
    ns = [x for i, x in enumerate(cols) if not y >> i & 1]
    if y.bit_count() % 2 and (not ns):
        return None
    scores = collections.Counter((x ^ z for x in ys for z in ns))
    for z in ys if y.bit_count() % 2 == 0 else ns:
        scores[z] += 0
    if not scores:
        return None
    best = None
    bestcost = len(cols)
    sy = set(ys)
    sn = set(ns)
    odd = y.bit_count() % 2
    for z in scores:
        cost = len(cols) - 2 * scores[z] - (z in sy) + (1 - 2 * (z in sn) if odd and z else 0)
        if cost < bestcost or (cost == bestcost and best is not None and (z < best)):
            best = z
            bestcost = cost
    return apply(cols, best, y) if best is not None else None
CONFIG={2: {'method': 'paper'},
 3: {'method': 'paper'},
 4: {'method': 'paper'},
 5: {'method': 'paper'},
 6: {'method': 'paper'},
 7: {'method': 'paper'},
 8: {'method': 'paper'},
 9: {'method': 'paper'},
 10: {'coset_passes': 5,
      'coset_seed': 0,
      'gadgets': [(399, 408576, 231735296),
                  (139, 142336, 911212544),
                  (260, 266240, 998244352),
                  (7, 7168, 145752064),
                  (41, 41984, 176160768),
                  (46, 47104, 36700160),
                  (608, 622592, 1044381696),
                  (234, 239616, 437256192),
                  (650, 665600, 609222656),
                  (531, 543744, 365953024),
                  (226, 231424, 120586240),
                  (753, 771072, 316669952),
                  (27, 27648, 18874368),
                  (581, 594944, 808452096),
                  (606, 620544, 823132160),
                  (398, 407552, 918552576),
                  (307, 314368, 63963136),
                  (189, 193536, 890241024),
                  (290, 296960, 1022361600),
                  (499, 510976, 607125504),
                  (209, 214016, 415236096),
                  (172, 176128, 771751936),
                  (192, 196608, 1059061760),
                  (108, 110592, 287309824),
                  (617, 631808, 385875968),
                  (297, 304128, 529530880),
                  (832, 851968, 143654912),
                  (217, 222208, 679477248),
                  (345, 353280, 631242752),
                  (384, 393216, 220200960),
                  (688, 704512, 849346560),
                  (112, 114688, 313524224),
                  (704, 720896, 537919488)],
      'method': 'coset',
      'tohpe_moves': 7,
      'tohpe_seed': 1},
 16: {'method': 'toom',
      'seed': 0,
      'shifts': [0, 15232, 5870, 0, 5870, 4034, 4034],
      'tohpe_moves': 1,
      'tohpe_seed': 0},
 32: {'method': 'toom',
      'seed': 13,
      'shifts': [0,
                 218781306,
                 201540170,
                 79521491,
                 410156200,
                 410156200,
                 110870346,
                 218781306,
                 421760039,
                 201540170,
                 79521491,
                 204509312,
                 0,
                 110870346,
                 0],
      'tohpe_moves': 2,
      'tohpe_seed': 13},
 163: {'global_translation': 131797514116554212681291190443325578828769544827,
       'method': 'crt',
       'seed': 0,
       'shifts': [0,
                  214178445479468360425507406660578098108554117021,
                  391023939458760587246542321220862440330823919154,
                  47533409581493823283644879326128162241902290881,
                  74017388530678272332402787426419260292307123640,
                  0,
                  661932583743684195783201654876285038071684677220,
                  5651622382081642407010400821227506442396505200,
                  37098684468879342718359219803130905071737701246,
                  1013708438708588791850004918176701869185015866269,
                  0,
                  0,
                  179484822964879575583556433424598122537856944169,
                  214178445479468360425507406660578098108554117021,
                  0,
                  93513259068029420034983819278578052922874171170,
                  37098684468879342718359219803130905071737701246,
                  74219563547579524788632988149195161082908082521,
                  0,
                  63250172069281671701497815949942842522311282117,
                  131797514116554212681291190443325578828769544827,
                  725285636605059221084533474234302051096216923286,
                  80735056931027045534659033400783570191154041930,
                  71597016327487089911298024234585291452171447963,
                  196915466015240702278619612440026497979221306381,
                  391023939458760587246542321220862440330823919154,
                  63250172069281671701497815949942842522311282117,
                  74219563547579524788632988149195161082908082521,
                  0,
                  71597016327487089911298024234585291452171447963,
                  105066250414556086023535800209973328374910548623,
                  0,
                  0,
                  0,
                  284633726210263329159624562264247114740101898532,
                  8,
                  0,
                  0,
                  74017388530678272332402787426419260292307123640,
                  0,
                  105066250414556086023535800209973328374910548623,
                  47533409581493823283644879326128162241902290881,
                  46878623281039700513408530664878411079588554435,
                  284633726210263329159624562264247114740101898532,
                  0,
                  196915466015240702278619612440026497979221306381,
                  46878623281039700513408530664878411079588554435,
                  80735056931027045534659033400783570191154041930,
                  5651622382081642407010400821227506442396505200,
                  144529865334322232542228508088613426797897510631,
                  1013708438708588791850004918176701869185015866269,
                  179484822964879575583556433424598122537856944169]},
 233: {'global_translation': 0,
       'method': 'crt',
       'seed': 0,
       'shifts': [0,
                  133211006320863284330094129893295311420590104706620619307730065647320,
                  133211006320863284330094129893295311420590104706620619307730065647320,
                  85690325260647967750834606144712548348102791990459961764164008803391,
                  600437720478276039746248050316603128999823888010104489885060203788969,
                  0,
                  186422441677923248402404150095269068550664798962043739265532846573496,
                  139782956128611729101756313309692957222941896838860968234739399680983,
                  58985271680593343346782957779947729322329615257690705537116885857307,
                  0,
                  364073028214833932603663886291214076662904619331035988424732321836117,
                  107301877835119722562035037218117272691209467037348419980101631226157,
                  255165289844690886430052057462174928279485092960731777694705530767637,
                  16031102860904625653516693329570902497877171703233767492065783652852,
                  0,
                  52740119073431589701798889323859042059388052695673555772331465180643,
                  0,
                  0,
                  68345087912113670511221289451442714984871440429208536399912178333866,
                  68345087912113670511221289451442714984871440429208536399912178333866,
                  31990915422386990756261133473782290613716392709793942170858805165291,
                  471333775587194229974416425816297061604963824824406024394294627236975,
                  45347989497695415336759583832794515383064045220570584485418448522940,
                  26,
                  0,
                  14188056772661356557885369124938308768135182046325944911745697971219,
                  133853901696806295999119026055443476513523358683465980656892623122646,
                  360577331027917749099768500028585947992175059880120169827428909115991,
                  0,
                  139782956128611729101756313309692957222941896838860968234739399680983,
                  186422441677923248402404150095269068550664798962043739265532846573496,
                  0,
                  364073028214833932603663886291214076662904619331035988424732321836117,
                  0,
                  58985271680593343346782957779947729322329615257690705537116885857307,
                  67170102849012463904367511589287731300579617898048766590379486740316,
                  107301877835119722562035037218117272691209467037348419980101631226157,
                  0,
                  45347989497695415336759583832794515383064045220570584485418448522940,
                  0,
                  471333775587194229974416425816297061604963824824406024394294627236975,
                  0,
                  333193687450824826320363366099258162046226695042717427625001905103989,
                  166163149021634568878422083092982606724689164129272653074457648589168,
                  18657514375922296581390806334126884069851628832189936551768999226388,
                  17306587657459856557496818445288335750312317418372077355048049900638,
                  0,
                  52740119073431589701798889323859042059388052695673555772331465180643,
                  127447148566737317433179605600248793608296377791460210597389376829506,
                  360577331027917749099768500028585947992175059880120169827428909115991,
                  379357235027527638491036695871306921477270960699601359424827943999353,
                  0,
                  127447148566737317433179605600248793608296377791460210597389376829506,
                  42649231267700464659975354212929159936791664859693831473561747245985,
                  0,
                  17306587657459856557496818445288335750312317418372077355048049900638,
                  166163149021634568878422083092982606724689164129272653074457648589168,
                  67170102849012463904367511589287731300579617898048766590379486740316,
                  0,
                  0,
                  0,
                  14188056772661356557885369124938308768135182046325944911745697971219,
                  42649231267700464659975354212929159936791664859693831473561747245985,
                  31990915422386990756261133473782290613716392709793942170858805165291,
                  255165289844690886430052057462174928279485092960731777694705530767637,
                  16031102860904625653516693329570902497877171703233767492065783652852,
                  133853901696806295999119026055443476513523358683465980656892623122646,
                  85690325260647967750834606144712548348102791990459961764164008803391,
                  18657514375922296581390806334126884069851628832189936551768999226388]},
 283: {'global_translation': 722669353822137622271424800418397994129407317363323032553836693903737873374420886760,
       'method': 'crt',
       'seed': 0,
       'shifts': [0,
                  0,
                  0,
                  0,
                  191906657359391882557741886132719375747640920268834857450808111305694999217171502068,
                  455609796966718341003235172929229248116405004218063254762005687715239806964704002527,
                  26434922802747970994383098426576237424088795516213445696585476184747338016450082704,
                  191906657359391882557741886132719375747640920268834857450808111305694999217171502068,
                  74839481907534132620856120478463859358649360279562726567085690694141998382284072637,
                  0,
                  69849384230184828694618955164935665188536650429642873490546994188815994219951686069,
                  41370175950956087693616687522958497812063538084150104353374838429536212814111416272,
                  8,
                  21823716212839470535916731033572868350488255500655101442128737647694523889197891698,
                  26434922802747970994383098426576237424088795516213445696585476184747338016450082704,
                  37183313650400690642502312756679427559316520070655315287704538622615033567047414027,
                  116232168872673082092154640229891488056455126596247604667069733883892669552944652849,
                  131367622331912962941539814451130925900404549195041779928125906816974202398570618721,
                  363511846965116839551588999471004041241294223547662361538899191854494654676591797831,
                  74839481907534132620856120478463859358649360279562726567085690694141998382284072637,
                  0,
                  485834879210847398348735969157251938123395828340919955395991879953141749296000138217,
                  223966661556845242342807610244028032569826810748656490265375502935945709810551635846,
                  6045999833600361098573972687287239390887080933221585665748074553783021671090563621,
                  69849384230184828694618955164935665188536650429642873490546994188815994219951686069,
                  37572355051552435125811335003580563450234256945682234839279745818960766530486564901,
                  37572355051552435125811335003580563450234256945682234839279745818960766530486564901,
                  320242132710502012354101489565683555958241055422720478315403778322343467737905431403,
                  0,
                  26317956873467716032349407358329711497848440180813910946304506809106823751416606636,
                  455609796966718341003235172929229248116405004218063254762005687715239806964704002527,
                  52909632973541661563389162304611845017089074714058209914826948471521977073696019598,
                  0,
                  107907176981777584630499540377961353756580491704098911088736078527136920586622176689,
                  105901759986179011361535257236471310492146782615223475397224571749016977676697032351,
                  52909632973541661563389162304611845017089074714058209914826948471521977073696019598,
                  363511846965116839551588999471004041241294223547662361538899191854494654676591797831,
                  41370175950956087693616687522958497812063538084150104353374838429536212814111416272,
                  0,
                  127013654081528601902637113600372249632706085798372386766750354008732201269695056417,
                  59879985955572277927054312034731502001395061619617997799131337448075191127230623760,
                  722669353822137622271424800418397994129407317363323032553836693903737873374420886760,
                  11917129227388805682278736384525087223318259374776395923508724146477159599149622284,
                  0,
                  0,
                  0,
                  264731492471046174444771220623729462633222951204150394347072811176118170982784665309,
                  0,
                  0,
                  37183313650400690642502312756679427559316520070655315287704538622615033567047414027,
                  107907176981777584630499540377961353756580491704098911088736078527136920586622176689,
                  120886334920635556792930904479870636809022665927685601359628239316223417854027422156,
                  6045999833600361098573972687287239390887080933221585665748074553783021671090563621,
                  127013654081528601902637113600372249632706085798372386766750354008732201269695056417,
                  556721750656125869242161498749619494432399136338999058045907367967420915941343330944,
                  120886334920635556792930904479870636809022665927685601359628239316223417854027422156,
                  128820189959771085591824873455513686224006084659655292587306247987311945048133607666,
                  21823716212839470535916731033572868350488255500655101442128737647694523889197891698,
                  556721750656125869242161498749619494432399136338999058045907367967420915941343330944,
                  0,
                  223966661556845242342807610244028032569826810748656490265375502935945709810551635846,
                  26317956873467716032349407358329711497848440180813910946304506809106823751416606636,
                  0,
                  64755629740857635697315396894117296888080227968404650708393746991296809506840283272,
                  320242132710502012354101489565683555958241055422720478315403778322343467737905431403,
                  264731492471046174444771220623729462633222951204150394347072811176118170982784665309,
                  116232168872673082092154640229891488056455126596247604667069733883892669552944652849,
                  0,
                  0,
                  105901759986179011361535257236471310492146782615223475397224571749016977676697032351,
                  11917129227388805682278736384525087223318259374776395923508724146477159599149622284,
                  0,
                  59879985955572277927054312034731502001395061619617997799131337448075191127230623760,
                  369105429274148995982101261383713301323479787122755164410591268040833527565877677858,
                  0,
                  34095631773452777155132452452153690306900413948450485351374960669003825955878042034,
                  128820189959771085591824873455513686224006084659655292587306247987311945048133607666,
                  34095631773452777155132452452153690306900413948450485351374960669003825955878042034,
                  0,
                  0,
                  64755629740857635697315396894117296888080227968404650708393746991296809506840283272]}}

def fixed_tohpe(cols,n,seed,moves):
    rng=random.Random(seed);cols=clean(cols)
    pairs=[(1<<(n+k),a,b) for k,(a,b) in enumerate(( (a,b) for a in range(n) for b in range(a) ))]
    for _ in range(moves):
        rng.shuffle(cols);piv,kernels=basis(cols,n,pairs);rng.shuffle(kernels);best=None
        for y in kernels[:4]:
            cand=tohpe_action(cols,y,rng)
            if cand is not None and (best is None or len(cand)<len(best)):best=cand
        if best is None:raise ValueError('frozen TOHPE trajectory failed to reproduce')
        cols=best
    return sorted(cols)

def generate(m):
    cfg=CONFIG[m];method=cfg['method']
    if method=='paper':cols=local_paper(m)
    elif method=='coset':cols,_=coset_synthesis(cfg['gadgets'],cfg['coset_seed'],cfg['coset_passes'])
    else:
        blocks,_=(crt_blocks if method=='crt' else toom_blocks)(m,cfg['seed']);s=set()
        for block,z in zip(blocks,cfg['shifts']):
            block=sorted(toggle(set(),block));toggle(s,[x^z for x in block]+([z] if len(block)%2 else []))
        cols=sorted(s)
    if 'tohpe_moves' in cfg:cols=fixed_tohpe(cols,3*m,cfg['tohpe_seed'],cfg['tohpe_moves'])
    z=cfg.get('global_translation',0)
    if z:
        assert len(cols)%2==0 and z in cols
        cols=sorted(x^z for x in cols if x!=z)
    return artifact(m,cols)

def main():
    p=argparse.ArgumentParser();p.add_argument('instance',choices=['mult-'+str(m) for m in sorted(CONFIG)]);p.add_argument('output',type=Path);a=p.parse_args();m=int(a.instance.split('-')[1]);out=generate(m);a.output.write_text(json.dumps(out,separators=(',',':')));print(json.dumps({'r':len(out['columns'])}))
if __name__=='__main__':main()