From 830c0e46079906e5060d1ba80de301f4221145a8 Mon Sep 17 00:00:00 2001 From: lmtlssss <261705307+lmtlssss@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:35:43 -0800 Subject: [PATCH] hardware/epfl-ties: ctrl 25 / 2 on both tables and adder 129 / 126 by size are optimal, with the arguments and checks --- README.md | 2 + hardware/epfl-ties/MANIFEST.sha256 | 6 + hardware/epfl-ties/README.md | 82 +++++++++++ hardware/epfl-ties/adder_step.py | 41 ++++++ hardware/epfl-ties/adder_step.txt | 6 + hardware/epfl-ties/blifkit.py | 218 +++++++++++++++++++++++++++++ hardware/epfl-ties/ctrl_facts.py | 39 ++++++ hardware/epfl-ties/ctrl_facts.txt | 6 + 8 files changed, 400 insertions(+) create mode 100644 hardware/epfl-ties/MANIFEST.sha256 create mode 100644 hardware/epfl-ties/README.md create mode 100644 hardware/epfl-ties/adder_step.py create mode 100644 hardware/epfl-ties/adder_step.txt create mode 100644 hardware/epfl-ties/blifkit.py create mode 100644 hardware/epfl-ties/ctrl_facts.py create mode 100644 hardware/epfl-ties/ctrl_facts.txt diff --git a/README.md b/README.md index a316383..ed14550 100644 --- a/README.md +++ b/README.md @@ -253,6 +253,8 @@ Logic compilers, netlists and proofs are under [`hardware/`](hardware/). [`hardware/epfl-router/`](hardware/epfl-router/) holds `router` for the depth table at 22 LUT-6 and 3 levels, the minimum, where the best published has 25, proved equal to the benchmark by ABC. +[`hardware/epfl-ties/`](hardware/epfl-ties/) proves three published entries optimal, so they cannot be beaten: `ctrl` at 25 LUT-6 and 2 levels on both tables, and `adder` at 129 LUT-6 and 126 levels on the size table. + [`hardware/divider/udiv.v`](hardware/divider/) is a drop-in unsigned divider: 4,889 cells at 64 bits on Lattice ECP5, placed and routed, where the Verilog operators take 12,246. `udivf64.v` in the same directory divides in 181 ns on that device, where the operators take 394 ns. [`hardware/linear/`](hardware/linear/) builds XOR logic: CRC-32 over a 512-bit bus in 701 LUT-6 at 4 levels, where Yosys takes 2,344; with any number of valid bytes, 1,172. diff --git a/hardware/epfl-ties/MANIFEST.sha256 b/hardware/epfl-ties/MANIFEST.sha256 new file mode 100644 index 0000000..d999022 --- /dev/null +++ b/hardware/epfl-ties/MANIFEST.sha256 @@ -0,0 +1,6 @@ +800dc882ed62352eb95c79e00b1d5586c17229ad8ec92236f46df496d4f4dbef README.md +d39e43b32d41dd5b52e6f53a58957fdef1971321ccd465250251f30348b767df adder_step.py +28c236c85ad8ecc9c3243dff6f94694aec1f5c47c48bfb89a064c61ccec95e03 adder_step.txt +ced8a3e68b3e13c6dc0c310fde13e6812c0f9ad462c21e4a0cc5965126a3219b blifkit.py +8f1448cc1e37a18c2f8518e10eb30a5cdeac770a97f2807ef4ad07026d5d93cf ctrl_facts.py +6656e171951aa753d82fd81344364643f12cc8b583a4a2139ad816465d972e97 ctrl_facts.txt diff --git a/hardware/epfl-ties/README.md b/hardware/epfl-ties/README.md new file mode 100644 index 0000000..df873dd --- /dev/null +++ b/hardware/epfl-ties/README.md @@ -0,0 +1,82 @@ +# EPFL ties: three published entries that are optimal + +The [EPFL combinational benchmark suite](https://github.com/lsils/benchmarks) keeps the best known LUT-6 results in two tables, by size and by depth. For three entries the published netlist cannot be beaten: no LUT-6 network does better under that table's order. This page gives the floor for each, the argument in full, and the checks of the facts it rests on. + +| entry | published, LUT-6 / levels | floor | +| --- | --- | --- | +| `ctrl`, size table | 25 / 2 | 25 LUTs; at 25 LUTs, 2 levels | +| `ctrl`, depth table | 25 / 2 | 2 levels; at 2 levels, 25 LUTs | +| `adder`, size table | 129 / 126 | 129 LUTs; at 129 LUTs, 126 levels | + +The tables count LUTs with two or more inputs and the levels over those; constant nodes and single-input nodes (buffers and inverters) are free. [`../epfl-dec/lutcount.py`](../epfl-dec/lutcount.py) gives 25 / 2 for `best_results/size/ctrl_size_2023.blif` and for `best_results/depth/ctrl_depth_2023.blif`, and 129 / 126 for `best_results/size/adder_size_2022.blif`. + +## ctrl: 25 / 2 on both tables + +`ctrl` has 7 inputs and 26 outputs. From its full truth table ([`ctrl_facts.py`](ctrl_facts.py), output in [`ctrl_facts.txt`](ctrl_facts.txt)): + +``` +ctrl: 7 inputs, 26 outputs, 128 truth-table rows +constant outputs: sign = 1 +non-constant outputs: 25; smallest support 3 inputs +outputs on all 7 inputs: alu_op[0], invA, invB +outputs equal to an input or its complement: none +pairs of outputs equal or complementary: none +``` + +**LUTs.** `sign` is constant, which the table counts as free. Each of the other 25 outputs is neither a constant, nor an input, nor an inverted input, so it is the output of a node with two or more inputs, possibly through free inverters. Two outputs driven by the same such node would be equal or complementary, and no two are. So any network for `ctrl` has at least 25 LUTs. + +**Levels.** `alu_op[0]`, `invA` and `invB` each depend on all 7 inputs, and one LUT-6 reads 6. So any network has at least 2 levels. + +The published netlists have 25 LUTs at 2 levels, which meets both floors at once. Under the size table's order (LUTs, then levels) and the depth table's (levels, then LUTs), nothing beats them. + +## adder: 129 / 126 on the size table + +`adder` adds two 128-bit words, `a` and `b`: 256 inputs, the sum bits `f[0]` to `f[127]` (written `s_i` below) and the carry out `cOut`. + +``` +yosys-abc -c "read arithmetic/adder.aig; strash; print_supp" + f[0] : Supp = 2. f[1] : Supp = 4. f[2] : Supp = 6. ... f[127] : Supp = 256. cOut : Supp = 256. +yosys-abc -c "read arithmetic/adder.aig; strash; print_supp -s" +Total func supps = 16768. +Total struct supps = 16768. +``` + +`s_i` depends on exactly `a_0` to `a_i` and `b_0` to `b_i`, 2(i + 1) inputs, and the functional supports equal the structural ones (2 + 4 + ... + 256 + 256 = 16,768). + +**LUTs.** The 128 sum bits have different supports, so no two are equal or complementary. `s_127` and the carry out both read all 256 inputs but differ: with only `a_127` set, `s_127` is 1 and the carry out 0, and with no input set both are 0. None of the 129 outputs is a constant, an input or an inverted input. By the count used for `ctrl`, any network has at least 129 LUTs. + +**Levels at 129 LUTs.** With exactly 129 LUTs, every LUT drives an output, so a LUT reads only inputs and other outputs. Take `s_i` with i >= 3, and suppose its LUT reads no output from `s_(i-1)` up. It must read `a_i` and `b_i`, since no output below `s_(i-1)` depends on them. It must also read `a_(i-1)` and `b_(i-1)`, for the same reason. Its last two wires must then give the carry into column i - 1, `c_(i-1) = maj(a_(i-2), b_(i-2), c_(i-2))`, from inputs and outputs `s_0` to `s_(i-2)`. Two wires cannot: +- `a_(i-2)` and `b_(i-2)` miss `c_(i-2)`, which is not constant for i >= 3, and which decides the carry when `a_(i-2) ≠ b_(i-2)`. +- `s_(i-2)` with a wire that does not read `a_(i-2)` or `b_(i-2)`: the cases (0, 0, c) and (1, 1, c) of `(a_(i-2), b_(i-2), c_(i-2))` agree on both wires, and their carries are 0 and 1. +- `s_(i-2)` with `a_(i-2)`: (0, 0, 0) and (0, 1, 1) agree on both, with carries 0 and 1. With `b_(i-2)` the same holds, by symmetry: (0, 0, 0) and (1, 0, 1). +- Any pair without `s_(i-2)`, `a_(i-2)` or `b_(i-2)` does not depend on column i - 2 at all. + +So `s_i` reads `s_(i-1)` or a higher output, and by the same argument so does the carry out, reading `s_126` or `s_127`. Going through the LUTs in topological order, each `s_i` is at least one level above `s_(i-1)`, or above a higher output, which is itself at level i or more. With `s_2` at level 1 or more, `s_i` is at level i - 1 or more. So `s_127`, and with it the carry out, is at level 126 or more. + +The published netlist has 129 LUTs at 126 levels, so nothing beats it on the size table. + +[`adder_step.py`](adder_step.py) checks the step exhaustively on an 8-bit adder (65,536 rows). No LUT reading `a_i`, `b_i` and any four other wires from the inputs and `s_0` to `s_(i-2)` gives `s_i`, while with `s_(i-1)` among the wires one does. Output in [`adder_step.txt`](adder_step.txt): + +``` +s_3 16 wires to choose from, 1820 sets of four: 0 give it; with s_2: computable +s_4 17 wires to choose from, 2380 sets of four: 0 give it; with s_3: computable +s_5 18 wires to choose from, 3060 sets of four: 0 give it; with s_4: computable +s_6 19 wires to choose from, 3876 sets of four: 0 give it; with s_5: computable +s_7 20 wires to choose from, 4845 sets of four: 0 give it; with s_6: computable +carry out 20 wires to choose from, 4845 sets of four: 0 give it; with s_6: computable +``` + +The argument above is the proof for 128 bits; the 8-bit run checks its step. + +## Commands + +``` +python3 ctrl_facts.py random_control/ctrl.blif +python3 adder_step.py 8 +yosys-abc -c "read arithmetic/adder.aig; strash; print_supp; print_supp -s" +python3 ../epfl-dec/lutcount.py best_results/size/ctrl_size_2023.blif +python3 ../epfl-dec/lutcount.py best_results/depth/ctrl_depth_2023.blif +python3 ../epfl-dec/lutcount.py best_results/size/adder_size_2022.blif +``` + +`ctrl_facts.py` needs Python 3 and reads [`blifkit.py`](blifkit.py); `adder_step.py` needs NumPy. The suite's files are from lsils/benchmarks commit `3e9df8b`. diff --git a/hardware/epfl-ties/adder_step.py b/hardware/epfl-ties/adder_step.py new file mode 100644 index 0000000..6540b94 --- /dev/null +++ b/hardware/epfl-ties/adder_step.py @@ -0,0 +1,41 @@ +"""usage: python3 adder_step.py [N] (default N = 8; needs NumPy) +The step of the adder argument, checked exhaustively on an N-bit adder (2^(2N) rows): for every i from 3 to +N-1, no 6-input LUT that reads a_i, b_i and any four other wires, taken from all the other inputs and the +outputs s_0 .. s_(i-2), computes s_i; and none that reads a_(N-1), b_(N-1) and four wires from the other inputs +and s_0 .. s_(N-3) computes the carry out. Control: with s_(i-1) among the wires, both are computable.""" +import itertools +import sys + +import numpy as np + +N = int(sys.argv[1]) if len(sys.argv) > 1 else 8 +rows = np.arange(1 << (2 * N), dtype=np.int64) +a = [(rows >> i) & 1 for i in range(N)] +b = [(rows >> (N + i)) & 1 for i in range(N)] +S = sum(a[i] << i for i in range(N)) + sum(b[i] << i for i in range(N)) +s = [(S >> i) & 1 for i in range(N)] +cout = (S >> N) & 1 + + +def computable(target, wires): + key = np.zeros_like(rows) + for k, w in enumerate(wires): + key |= w << k + z = np.zeros(1 << len(wires), bool) + o = z.copy() + z[key[target == 0]] = True + o[key[target == 1]] = True + return not (z & o).any() + + +ins = [("a%d" % i, a[i]) for i in range(N)] + [("b%d" % i, b[i]) for i in range(N)] +for i in list(range(3, N)) + ["cout"]: + if i == "cout": + tgt, top, low, name = cout, N - 1, N - 2, "carry out" + else: + tgt, top, low, name = s[i], i, i - 1, "s_%d" % i + pool = [x for x in ins if x[0] not in ("a%d" % top, "b%d" % top)] + [("s%d" % j, s[j]) for j in range(low)] + hits = sum(computable(tgt, [a[top], b[top]] + [w for _, w in c]) for c in itertools.combinations(pool, 4)) + ctrl = computable(tgt, [a[top], b[top], a[top - 1], b[top - 1], s[top - 1]]) + print("%-9s %2d wires to choose from, %5d sets of four: %d give it; with s_%d: %s" + % (name, len(pool), len(list(itertools.combinations(pool, 4))), hits, top - 1, "computable" if ctrl else "not")) diff --git a/hardware/epfl-ties/adder_step.txt b/hardware/epfl-ties/adder_step.txt new file mode 100644 index 0000000..7686fcc --- /dev/null +++ b/hardware/epfl-ties/adder_step.txt @@ -0,0 +1,6 @@ +s_3 16 wires to choose from, 1820 sets of four: 0 give it; with s_2: computable +s_4 17 wires to choose from, 2380 sets of four: 0 give it; with s_3: computable +s_5 18 wires to choose from, 3060 sets of four: 0 give it; with s_4: computable +s_6 19 wires to choose from, 3876 sets of four: 0 give it; with s_5: computable +s_7 20 wires to choose from, 4845 sets of four: 0 give it; with s_6: computable +carry out 20 wires to choose from, 4845 sets of four: 0 give it; with s_6: computable diff --git a/hardware/epfl-ties/blifkit.py b/hardware/epfl-ties/blifkit.py new file mode 100644 index 0000000..ec505b2 --- /dev/null +++ b/hardware/epfl-ties/blifkit.py @@ -0,0 +1,218 @@ +"""Small BLIF toolkit: parse, simulate (bit-parallel on Python ints), levels, LUT netlist writer. + +No third-party code. Used by the generators and checks in this folder. +""" +import random + + +def _lines(path): + buf = "" + with open(path) as fh: + for raw in fh: + line = raw.split("#", 1)[0].rstrip("\n").rstrip() + if line.endswith("\\"): + buf += line[:-1] + " " + continue + buf += line + if buf.strip(): + yield buf.strip() + buf = "" + if buf.strip(): + yield buf.strip() + + +class Blif: + def __init__(self): + self.inputs, self.outputs = [], [] + self.nodes = {} # name -> (fanins, rows, outval) + self.order = [] + + @staticmethod + def read(path): + b = Blif() + cur = None + for ln in _lines(path): + if ln.startswith("."): + tok = ln.split() + cmd = tok[0] + cur = None + if cmd == ".inputs": + b.inputs += tok[1:] + elif cmd == ".outputs": + b.outputs += tok[1:] + elif cmd == ".names": + fan, out = tok[1:-1], tok[-1] + cur = [fan, [], None] + b.nodes[out] = cur + elif cmd in (".model", ".end", ".default_input_arrival", ".default_output_required"): + pass + else: + raise ValueError("unsupported " + cmd) + else: + tok = ln.split() + if len(cur[0]) == 0: + cur[2] = tok[0] + cur[1].append("") + else: + cur[1].append(tok[0]) + cur[2] = tok[1] + b._topo() + return b + + def _topo(self): + seen, order = set(self.inputs), [] + state = {} + for root in list(self.nodes): + if root in seen: + continue + stack = [(root, 0)] + while stack: + n, i = stack.pop() + if n in seen: + continue + fan = self.nodes[n][0] + if i < len(fan): + stack.append((n, i + 1)) + f = fan[i] + if f not in seen: + if f not in self.nodes: + raise ValueError("undriven " + f) + if state.get(f) == 1: + raise ValueError("cycle at " + f) + state[f] = 1 + stack.append((f, 0)) + else: + seen.add(n) + state[n] = 2 + order.append(n) + self.order = order + + def simulate(self, values, width): + """values: dict input -> int of `width` bits. Returns dict of all signals.""" + mask = (1 << width) - 1 + v = dict(values) + for n in self.order: + fan, rows, outv = self.nodes[n] + acc = 0 + for r in rows: + t = mask + for ch, f in zip(r, fan): + if ch == "1": + t &= v[f] + elif ch == "0": + t &= ~v[f] + if not t: + break + acc |= t + if outv == "0": + acc = ~acc + v[n] = acc & mask + return v + + def rename_ports(self, ref): + """Rename primary inputs and outputs by position to those of `ref` (for netlists with nNN names).""" + assert len(ref.inputs) == len(self.inputs) and len(ref.outputs) == len(self.outputs) + m = dict(zip(self.inputs, ref.inputs)) + m.update(zip(self.outputs, ref.outputs)) + clash = set(m.values()) & (set(self.nodes) - set(m)) + assert not clash, clash + nodes = {} + for n, (fan, rows, outv) in self.nodes.items(): + nodes[m.get(n, n)] = ([m.get(f, f) for f in fan], rows, outv) + self.nodes = nodes + self.inputs = list(ref.inputs) + self.outputs = list(ref.outputs) + self._topo() + return self + + def levels(self): + lev = {i: 0 for i in self.inputs} + for n in self.order: + fan = self.nodes[n][0] + lev[n] = 1 + max((lev[f] for f in fan), default=0) if fan else 0 + return lev + + def stats(self): + lev = self.levels() + return len(self.nodes), max(lev[o] for o in self.outputs) + + +def random_inputs(names, width, rng): + return {n: rng.getrandbits(width) for n in names} + + +class LutNet: + """Builder: add LUTs given fanins and a Python function of the fanin bits.""" + + def __init__(self, inputs, k=6): + self.inputs = list(inputs) + self.k = k + self.luts = {} # name -> (fanins, truth table int) + self.order = [] + self.lev = {i: 0 for i in self.inputs} + + def lut(self, name, fanins, fn): + fanins = list(fanins) + assert len(fanins) <= self.k, (name, len(fanins)) + assert name not in self.lev, name + for f in fanins: + assert f in self.lev, (name, f) + tt = 0 + n = len(fanins) + for m in range(1 << n): + bits = [(m >> j) & 1 for j in range(n)] + if fn(*bits) & 1: + tt |= 1 << m + self.luts[name] = (fanins, tt) + self.order.append(name) + self.lev[name] = 1 + max((self.lev[f] for f in fanins), default=0) + return name + + def write(self, path, outputs, model="top"): + live = set() + stack = [o for o in outputs] + while stack: + s = stack.pop() + if s in live or s in self.inputs: + continue + live.add(s) + stack.extend(self.luts[s][0]) + with open(path, "w") as fh: + fh.write(".model %s\n" % model) + fh.write(".inputs " + " ".join(self.inputs) + "\n") + fh.write(".outputs " + " ".join(outputs) + "\n") + for name in self.order: + if name not in live: + continue + fan, tt = self.luts[name] + n = len(fan) + on = [m for m in range(1 << n) if (tt >> m) & 1] + fh.write(".names " + " ".join(fan + [name]) + "\n") + if not fan: + fh.write("1\n" if tt & 1 else "") + continue + use_on = len(on) <= (1 << n) - len(on) + rows = on if use_on else [m for m in range(1 << n) if not (tt >> m) & 1] + for m in rows: + fh.write("".join(str((m >> j) & 1) for j in range(n)) + (" 1\n" if use_on else " 0\n")) + fh.write(".end\n") + return len(live), max(self.lev[o] for o in outputs) + + +def compare(ref, ours, width=2048, rounds=8, seed=1, extra=None): + """Random-vector comparison by output name. extra: list of dict input->int vectors (width bits).""" + rng = random.Random(seed) + bad = 0 + total = 0 + batches = [random_inputs(ref.inputs, width, rng) for _ in range(rounds)] + if extra: + batches += extra + for vals in batches: + a = ref.simulate(vals, width) + b = ours.simulate({k: vals[k] for k in ours.inputs}, width) + for o in ref.outputs: + if a[o] != b[o]: + bad += 1 + break + total += width + return bad, total diff --git a/hardware/epfl-ties/ctrl_facts.py b/hardware/epfl-ties/ctrl_facts.py new file mode 100644 index 0000000..0435e79 --- /dev/null +++ b/hardware/epfl-ties/ctrl_facts.py @@ -0,0 +1,39 @@ +"""usage: python3 ctrl_facts.py random_control/ctrl.blif +The facts the ctrl floor rests on, from the full 128-row truth table: constant outputs, the support of each +other output, whether any output is an input or its complement, and whether any two outputs are equal or +complementary. Reads blifkit.py beside it.""" +import itertools +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from blifkit import Blif + +b = Blif.read(sys.argv[1]) +n = len(b.inputs) +W = 1 << n +M = (1 << W) - 1 +vals = {x: 0 for x in b.inputs} +for r in range(W): + for k, x in enumerate(b.inputs): + if (r >> k) & 1: + vals[x] |= 1 << r +out = b.simulate(vals, W) +tt = {o: out[o] for o in b.outputs} + + +def support(t): + return sum(any(((t >> r) & 1) != ((t >> (r ^ (1 << k))) & 1) for r in range(W)) for k in range(n)) + + +print("ctrl: %d inputs, %d outputs, %d truth-table rows" % (n, len(b.outputs), W)) +const = [o for o in b.outputs if tt[o] in (0, M)] +print("constant outputs:", ", ".join("%s = %d" % (o, 1 if tt[o] == M else 0) for o in const) or "none") +nc = [o for o in b.outputs if o not in const] +sup = {o: support(tt[o]) for o in nc} +print("non-constant outputs: %d; smallest support %d inputs" % (len(nc), min(sup.values()))) +print("outputs on all %d inputs: %s" % (n, ", ".join(sorted(o for o in nc if sup[o] == n)))) +lits = {vals[x] for x in b.inputs} | {M ^ vals[x] for x in b.inputs} +print("outputs equal to an input or its complement:", [o for o in nc if tt[o] in lits] or "none") +pairs = [(p, q) for p, q in itertools.combinations(nc, 2) if tt[p] in (tt[q], M ^ tt[q])] +print("pairs of outputs equal or complementary:", pairs or "none") diff --git a/hardware/epfl-ties/ctrl_facts.txt b/hardware/epfl-ties/ctrl_facts.txt new file mode 100644 index 0000000..f6bf929 --- /dev/null +++ b/hardware/epfl-ties/ctrl_facts.txt @@ -0,0 +1,6 @@ +ctrl: 7 inputs, 26 outputs, 128 truth-table rows +constant outputs: sign = 1 +non-constant outputs: 25; smallest support 3 inputs +outputs on all 7 inputs: alu_op[0], invA, invB +outputs equal to an input or its complement: none +pairs of outputs equal or complementary: none