Add constants more cheaply, 12 bits, 3 spare, controlled, constant 0xc29

Constant addition submission #45

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

Toffoli gates34
Operations135
Ancilla wires3

Verifier report

n
12
controlled
True
toffoli
34
gates
135
ancillas
3
measurements
10
phase refs
15
check
all 8192 inputs: target output, unchanged control, clean workspace, 11 constant phase coefficients
verify seconds
0.05
View raw report
{
 "n": 12,
 "controlled": true,
 "toffoli": 34,
 "gates": 135,
 "ancillas": 3,
 "measurements": 10,
 "phase_refs": 15,
 "check": "all 8192 inputs: target output, unchanged control, clean workspace, 11 constant phase coefficients",
 "verify_seconds": 0.05
}

Submission file

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

sha256 c04a4496ad0635da143395e40cf9dfb44679f74e29b88efc58b31d05227cfda7 · 1,731 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 Constant addition #45, 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 17.9 KB

#!/usr/bin/env python3
"""QArena constant addition: independently implemented streaming/retained carries.
Sources: Craig Gidney, arXiv:2507.23079 (CC BY 4.0), and Haener,
Roetteler and Svore, arXiv:1611.07995 (algorithmic description; arXiv
non-exclusive distribution license). No external source code or accepted
contestant file was used. Endpoint correction, reversible pebbling, and
Pauli-X-frame beam optimization are implemented in this file.
Run: python3 -I solve.py add12-945-a3 output.json
Python >=3.10, standard library only. Deterministic beam width 128, no seed.
"""
import argparse
import json
import re
from collections import deque
from pathlib import Path


class Builder:

    def __init__(self):
        self.ops = []
        self.records = 0

    def gate(self, *op):
        self.ops.append(list(op))

    def measure(self, wire):
        r = self.records
        self.records += 1
        self.gate('MX', wire)
        self.gate('RZ', wire)
        return r

    def carry(self, a, cin, out, bit):
        """Xor carry(a, bit, cin) into out, preserving a and cin."""
        if cin is None:
            if bit:
                self.gate('CX', a, out)
            return
        if bit:
            self.gate('X', a)
            self.gate('X', cin)
        self.gate('CCX', a, cin, out)
        if bit:
            self.gate('X', a)
            self.gate('X', cin)
            self.gate('X', out)

    def carry_xor(self, a, bits, g, cin=None, negate_input=True, negate_cin=False):
        """Dirty g[i] ^= carry into i+1, for the given input bits.

        The reverse ladder cancels dirty values propagated by the forward
        ladder. The recurrence is c_next=(a xor bit)*c xor (bit*a).
        """
        if negate_input:
            for w in a:
                self.gate('X', w)
        if negate_cin:
            self.gate('X', cin)

        def term(i, prev):
            if bits[i]:
                self.gate('X', a[i])
            self.gate('CCX', a[i], prev, g[i])
            if bits[i]:
                self.gate('X', a[i])
        for i in range(len(g) - 1, 0, -1):
            term(i, g[i - 1])
        for i in range(len(g)):
            if i:
                term(i, g[i - 1])
            elif cin is not None:
                term(i, cin)
            if bits[i]:
                self.gate('CX', a[i], g[i])
        if negate_cin:
            self.gate('X', cin)
        if negate_input:
            for w in a:
                self.gate('X', w)

def pebble_schedule(length, capacity, final=None):
    """Shortest reversible path-pebbling schedule, unit cost per nonlinear carry."""
    target = (0 if final is None else 1 << final - 1, (1 << length) - 1)
    start = (0, 0)
    q = deque([start])
    parent = {start: None}
    while q:
        state = q.popleft()
        if state == target:
            out = []
            while parent[state] is not None:
                before, pos = parent[state]
                out.append(pos)
                state = before
            return out[::-1]
        mask, seen = state
        for pos in range(length):
            bit = 1 << pos
            if pos and (not mask & bit >> 1):
                continue
            if not mask & bit and mask.bit_count() == capacity:
                continue
            nxt = (mask ^ bit, seen | bit)
            if nxt not in parent:
                parent[nxt] = (state, pos)
                q.append(nxt)
    return None

def plain_generate(n, c, split=None, linear_endpoint=True, repair='auto'):
    if not c & 1:
        raise ValueError('this implementation expects an odd constant')
    m = split if split is not None else (n - 2) // 2
    if not n - m - 2 <= m <= n // 2:
        raise ValueError('split does not provide enough borrowed wires')
    b = Builder()
    scratch = [n, n + 1]
    boundary = n + 2
    bits = [c >> i & 1 for i in range(n)]
    rec = {}
    cin = None
    for i in range(m):
        out = boundary if i == m - 1 else scratch[i % 2]
        b.carry(i, cin, out, bits[i])
        if bits[i]:
            b.gate('X', i)
        if cin is not None:
            b.gate('CX', cin, i)
            rec[i] = b.measure(cin)
            if linear_endpoint and i == 1:
                b.gate('PZ', 0, [rec[i]], 1)
        cin = out
    upper_rec = []
    upper_targets = []
    for i in range(m, n - 1):
        out = n - 1 if i == n - 2 else scratch[(i - m) % 2]
        b.carry(i, cin, out, bits[i])
        if bits[i]:
            b.gate('X', i)
        b.gate('CX', cin, i)
        if cin != boundary:
            upper_rec.append(b.measure(cin))
        if i < n - 2:
            upper_targets.append(i - m)
            b.gate('CX', out, i - m)
        cin = out
    if bits[-1]:
        b.gate('X', n - 1)
    for w, r in zip(upper_targets, upper_rec):
        b.gate('PZ', w, [r], 1)
    u = len(upper_targets)
    b.carry_xor(list(range(m, m + u)), bits[m:m + u], upper_targets, boundary)
    for w, r in zip(upper_targets, upper_rec):
        b.gate('PZ', w, [r], 1)
    rec[m] = b.measure(boundary)
    if linear_endpoint and repair != 'dirty':

        def clean_toggle(pos, mapping, free):
            i = pos + 2
            old = mapping.get(i - 1, 0)
            fresh = i not in mapping
            target = free.pop() if fresh else mapping[i]
            b.gate('X', i - 1)
            if i == 2:
                b.gate('X', 0)
            b.carry(i - 1, old, target, bits[i - 1])
            if i == 2:
                b.gate('X', 0)
            b.gate('X', i - 1)
            if fresh:
                mapping[i] = target
            else:
                del mapping[i]
                free.append(target)
            return (i, fresh, target)
        schedule = pebble_schedule(m - 1, 3)
        if schedule is not None:
            mapping, free, seen = ({}, [n, n + 1, n + 2], set())
            for pos in schedule:
                i, fresh, target = clean_toggle(pos, mapping, free)
                if fresh and i not in seen:
                    b.gate('PZ', target, [rec[i]], 1)
                    seen.add(i)
            return {'ancillas': 3, 'ops': b.ops}
        checkpoint = 3
        schedule = pebble_schedule(checkpoint - 1, 3, final=checkpoint - 1)
        mapping, free, seen = ({}, [n, n + 1, n + 2], set())
        for pos in schedule:
            i, fresh, target = clean_toggle(pos, mapping, free)
            if fresh and i not in seen:
                b.gate('PZ', target, [rec[i]], 1)
                seen.add(i)
        a = list(range(checkpoint, m))
        targets = list(range(m, m + len(a)))
        records = [rec[i + 1] for i in a]
        for w, r in zip(targets, records):
            b.gate('PZ', w, [r], 1)
        for p in range(2):
            b.carry_xor(a, bits[checkpoint:m], targets, mapping[checkpoint])
            if p == 0:
                for w, r in zip(targets, records):
                    b.gate('PZ', w, [r], 1)
        for pos in reversed(schedule):
            clean_toggle(pos, mapping, free)
        return {'ancillas': 3, 'ops': b.ops}
    start = 1 if linear_endpoint else 0
    lower_targets = list(range(m + start, 2 * m))
    lower_rec = [rec[i + 1] for i in range(start, m)]
    for w, r in zip(lower_targets, lower_rec):
        b.gate('PZ', w, [r], 1)
    for p in range(2):
        b.carry_xor(list(range(start, m)), bits[start:m], lower_targets, 0 if linear_endpoint else None, negate_cin=linear_endpoint)
        if p == 0:
            for w, r in zip(lower_targets, lower_rec):
                b.gate('PZ', w, [r], 1)
    return {'ancillas': 3, 'ops': b.ops}

class MaskedBuilder(Builder):

    def __init__(self, n, controlled):
        super().__init__()
        self.q = n if controlled else None

    def qxor(self, target):
        if self.q is None:
            self.gate('X', target)
        else:
            self.gate('CX', self.q, target)

    def product(self, a, prev, out, bit, delta):
        if prev is None:
            if not delta:
                return
            if self.q is None:
                self.gate('CX', a, out)
                if bit:
                    self.gate('X', out)
            else:
                if bit:
                    self.gate('X', a)
                self.gate('CCX', a, self.q, out)
                if bit:
                    self.gate('X', a)
            return
        if bit:
            self.qxor(a)
        if delta:
            self.qxor(prev)
        self.gate('CCX', a, prev, out)
        if delta:
            self.qxor(prev)
        if bit:
            self.qxor(a)

    def carry_xor_masked(self, indices, bits, targets, cin=None):
        for i in indices:
            self.gate('X', i)
        for j in range(len(targets) - 1, 0, -1):
            i = indices[j]
            self.product(i, targets[j - 1], targets[j], bits[i], 0)
        for j, i in enumerate(indices):
            self.product(i, targets[j - 1] if j else cin, targets[j], bits[i], bits[i] ^ (bits[i - 1] if i else 0))
        for i in indices:
            self.gate('X', i)

def masked_generate(n, c, controlled, split=None):
    if not c & 1:
        raise ValueError('odd constant required')
    m = split if split is not None else (n - 2) // 2
    if not n - m - 2 <= m <= n // 2:
        raise ValueError('invalid split')
    b = MaskedBuilder(n, controlled)
    k = n + int(controlled)
    scratch = [k, k + 1]
    boundary = k + 2
    bits = [c >> i & 1 for i in range(n)]
    records = {}
    cin = None
    for i in range(m):
        out = boundary if i == m - 1 else scratch[i % 2]
        delta = bits[i] ^ (bits[i - 1] if i else 0)
        b.product(i, cin, out, bits[i], delta)
        if delta:
            b.qxor(i)
        if cin is not None:
            b.gate('CX', cin, i)
            records[i] = b.measure(cin)
            if not controlled and i == 1:
                b.gate('PZ', 0, [records[i]], 1)
        cin = out
    upper_rec, upper_targets = ([], [])
    for i in range(m, n - 1):
        out = n - 1 if i == n - 2 else scratch[(i - m) % 2]
        delta = bits[i] ^ bits[i - 1]
        b.product(i, cin, out, bits[i], delta)
        if delta:
            b.qxor(i)
        b.gate('CX', cin, i)
        if cin != boundary:
            upper_rec.append(b.measure(cin))
        if i < n - 2:
            upper_targets.append(i - m)
            b.gate('CX', out, i - m)
        cin = out
    if bits[-1] ^ bits[-2]:
        b.qxor(n - 1)
    for w, r in zip(upper_targets, upper_rec):
        b.gate('PZ', w, [r], 1)
    b.carry_xor_masked(list(range(m, m + len(upper_targets))), bits, upper_targets, boundary)
    for w, r in zip(upper_targets, upper_rec):
        b.gate('PZ', w, [r], 1)
    records[m] = b.measure(boundary)
    first = 1 if controlled else 2
    length = m - first + 1
    full_schedule = pebble_schedule(length, 3)
    checkpoint = 2 if controlled else 3
    prefix_length = checkpoint - first + 1
    prefix_schedule = pebble_schedule(prefix_length, 3, final=prefix_length)
    dirty_cost = 2 * len(prefix_schedule) + 2 * (2 * (m - checkpoint) - 1) if m > checkpoint else 10 ** 6
    use_full = full_schedule is not None and len(full_schedule) <= dirty_cost
    schedule = full_schedule if use_full else prefix_schedule
    mapping, free, seen = ({}, [k, k + 1, k + 2], set())

    def toggle(pos, phase):
        i = pos + first
        prev = mapping.get(i - 1, 0 if not controlled else None)
        fresh = i not in mapping
        target = free.pop() if fresh else mapping[i]
        a = i - 1
        b.gate('X', a)
        b.product(a, prev, target, bits[a], bits[a] ^ (bits[a - 1] if a else 0))
        b.gate('X', a)
        if fresh:
            mapping[i] = target
            if phase and i not in seen:
                b.gate('PZ', target, [records[i]], 1)
                seen.add(i)
        else:
            del mapping[i]
            free.append(target)
    for pos in schedule:
        toggle(pos, True)
    if not use_full:
        indices = list(range(checkpoint, m))
        targets = list(range(m, m + len(indices)))
        for w, i in zip(targets, indices):
            b.gate('PZ', w, [records[i + 1]], 1)
        for repeat in range(2):
            b.carry_xor_masked(indices, bits, targets, mapping[checkpoint])
            if repeat == 0:
                for w, i in zip(targets, indices):
                    b.gate('PZ', w, [records[i + 1]], 1)
        for pos in reversed(schedule):
            toggle(pos, False)
    return {'ancillas': 3, 'ops': b.ops}

def generate_retained(n, c, controlled):
    """Use ten clean wires to keep all nonlinear lower carries coherently."""
    m = (n - 2) // 2
    k = n + int(controlled)
    b = MaskedBuilder(n, controlled)
    bits = [c >> i & 1 for i in range(n)]
    scratch = [k, k + 1]
    wires = {i: k + i for i in range(2, m + 1)}
    cin = None
    for i in range(m):
        out = k if i == 0 else wires[i + 1]
        delta = bits[i] ^ (bits[i - 1] if i else 0)
        b.product(i, cin, out, bits[i], delta)
        if delta:
            b.qxor(i)
        if cin is not None:
            b.gate('CX', cin, i)
        if i == 1:
            b.gate('CCX', n, 0, k) if controlled else b.gate('CX', 0, k)
        cin = out
    upper_rec, upper_targets = ([], [])
    boundary = wires[m]
    for i in range(m, n - 1):
        out = n - 1 if i == n - 2 else scratch[(i - m) % 2]
        b.product(i, cin, out, bits[i], bits[i] ^ bits[i - 1])
        if bits[i] ^ bits[i - 1]:
            b.qxor(i)
        b.gate('CX', cin, i)
        if cin != boundary:
            upper_rec.append(b.measure(cin))
        if i < n - 2:
            upper_targets.append(i - m)
            b.gate('CX', out, i - m)
        cin = out
    if bits[-1] ^ bits[-2]:
        b.qxor(n - 1)
    for w, r in zip(upper_targets, upper_rec):
        b.gate('PZ', w, [r], 1)
    b.carry_xor_masked(list(range(m, m + len(upper_targets))), bits, upper_targets, boundary)
    for w, r in zip(upper_targets, upper_rec):
        b.gate('PZ', w, [r], 1)
    b.gate('CCX', n, 0, k) if controlled else b.gate('CX', 0, k)
    for i in range(m - 1, 0, -1):
        prev = k if i == 1 else wires[i]
        b.gate('X', i)
        b.product(i, prev, wires[i + 1], bits[i], bits[i] ^ bits[i - 1])
        b.gate('X', i)
    b.gate('CCX', n, 0, k) if controlled else b.gate('CX', 0, k)
    return {'ancillas': m + 1, 'ops': b.ops}

def optimize(ops, width=128):
    states = {0: []}
    for op in ops:
        name = op[0]
        nxt = {}
        for frame, emitted in states.items():
            options = []
            if name == 'X':
                options.append((frame ^ 1 << op[1], []))
            elif name == 'CX':
                c, t = op[1:]
                options.append((frame ^ (frame >> c & 1) << t, [op]))
            elif name == 'CCX':
                a, b, t = op[1:]
                neg = [w for w in (a, b) if frame >> w & 1]
                for subset in range(1 << len(neg)):
                    newframe = frame
                    extra = []
                    for j, w in enumerate(neg):
                        if subset >> j & 1:
                            extra.append(['X', w])
                            newframe ^= 1 << w
                    extra.append(op)
                    fa, fb = (newframe >> a & 1, newframe >> b & 1)
                    if fa:
                        extra.append(['CX', b, t])
                    if fb:
                        extra.append(['CX', a, t])
                    if fa and fb:
                        newframe ^= 1 << t
                    options.append((newframe, extra))
            elif name in ('MX', 'RZ'):
                options.append((frame & ~(1 << op[1]), [op]))
            else:
                options.append((frame, [op]))
            for newframe, extra in options:
                candidate = emitted + extra
                if newframe not in nxt or len(candidate) < len(nxt[newframe]):
                    nxt[newframe] = candidate
        if len(nxt) > width:
            nxt = dict(sorted(nxt.items(), key=lambda kv: (len(kv[1]) + 0.25 * kv[0].bit_count(), kv[0]))[:width])
        states = nxt
    frame, result = min(states.items(), key=lambda kv: len(kv[1]) + kv[0].bit_count())
    return result + [['X', w] for w in range(frame.bit_length()) if frame >> w & 1]

def cancel(ops):
    out = []

    def key(op):
        return (op[0], *sorted(op[1:-1]), op[-1])
    for op in ops:
        if op[0] not in ('X', 'CX', 'CCX'):
            out.append(op)
            continue
        for j in range(len(out) - 1, -1, -1):
            prev = out[j]
            if prev[0] in ('X', 'CX', 'CCX'):
                if key(prev) == key(op):
                    del out[j]
                    break
                commute = op[-1] not in prev[1:-1] and prev[-1] not in op[1:-1]
            elif prev[0] == 'PZ':
                commute = op[0] == 'X' or op[-1] != prev[1]
            else:
                commute = prev[1] not in op[1:]
            if not commute:
                out.append(op)
                break
        else:
            out.append(op)
    return out


def solve(instance):
    match = re.fullmatch(r'(c?add)([0-9]+)-([0-9a-f]+)-a([0-9]+)', instance)
    if not match:
        raise ValueError('bad instance name')
    prefix, n, c, limit = match.groups()
    n, c, limit = int(n), int(c,16), int(limit)
    controlled = prefix == 'cadd'
    if limit < 3:
        raise ValueError('one-spare-wire algorithm remains unresolved')
    candidates = [masked_generate(n,c,controlled)]
    if not controlled:
        candidates.append(plain_generate(n,c))
    if limit >= (n-2)//2+1:
        candidates.append(generate_retained(n,c,controlled))
    for art in candidates:
        art['ops'] = cancel(optimize(art['ops'],128))
    return min(candidates,key=lambda a:(sum(op[0]=='CCX' for op in a['ops']),len(a['ops']),a['ancillas']))


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('instance')
    parser.add_argument('output',type=Path)
    args=parser.parse_args()
    art=solve(args.instance)
    args.output.write_text(json.dumps(art,separators=(',',':')))
    print(json.dumps({'instance':args.instance,'toffoli':sum(op[0]=='CCX' for op in art['ops']),'gates':len(art['ops']),'ancillas':art['ancillas']}))


if __name__ == '__main__':
    main()