Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ Logic compilers, netlists and proofs are under [`hardware/`](hardware/).
| `dec`, depth | 2 levels, 264 LUT-6 | 2 levels, 260 LUT-6 |
| `bar`, size | 512 LUT-6 | 486 LUT-6 |
| `bar`, depth | 4 levels, 512 LUT-6 | 4 levels, 486 LUT-6 |
| `router`, depth | 3 levels, 25 LUT-6 | 3 levels, 22 LUT-6 |
| `sixteen`, size | 3282958 LUT-6 | 12691 LUT-6 |
| `twenty`, size | 4166467 LUT-6 | 12719 LUT-6 |
| `twentythree`, size | 470892 LUT-6 | 12744 LUT-6 |
Expand All @@ -250,6 +251,8 @@ Logic compilers, netlists and proofs are under [`hardware/`](hardware/).

[`hardware/epfl-max/`](hardware/epfl-max/) holds `max` for the size table at 510 LUT-6 where the best published has 511, proved equal to the benchmark by ABC.

[`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/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.
Expand Down
4 changes: 4 additions & 0 deletions hardware/epfl-router/MANIFEST.sha256
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
02fc412d7c5f0e3ec57404fb9e5ed79194b4c84aebc013678327f3911526889c README.md
ced8a3e68b3e13c6dc0c310fde13e6812c0f9ad462c21e4a0cc5965126a3219b blifkit.py
1c555a911beb7169ebb0a4dfc02c19d00a91c65605d2300527ac2ddc18f66e4c check.py
9011aed4cb53144dadf63209b9d4d5597a6318302a94bd5629ea11cffecd422f router_depth_2027.blif
37 changes: 37 additions & 0 deletions hardware/epfl-router/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# EPFL router, depth

`router` is the lookahead XY router of the [EPFL combinational benchmark suite](https://github.com/lsils/benchmarks), random/control half: 60 inputs, 30 outputs. This page is its entry for the depth table.

| | LUT-6 | Levels |
| --- | --- | --- |
| Best published, depth table (T. Besson, `router_depth_2022.blif`) | 25 | 3 |
| [`router_depth_2027.blif`](router_depth_2027.blif) | 22 | 3 |

Three levels is the minimum: `outport[1]` and `outport[2]` each depend on all 60 inputs, and two levels of LUT-6 read at most 36. So the depth entry is decided by LUTs at 3 levels.

The table counts LUTs with two or more inputs and the levels over those, [`../epfl-dec/lutcount.py`](../epfl-dec/lutcount.py): 22 / 3 for this netlist and 25 / 3 for `best_results/depth/router_depth_2022.blif`. ABC's `nd` is 49 because it also counts 27 constant nodes, `outport[29:3]`, which the benchmark holds at 0.

## Check

[`check.py`](check.py) compares the netlist with the suite's `random_control/router.blif` on 36,864 vectors, every output by name: 16 x 2,048 random vectors plus the all-zero and all-one vectors. It then counts the netlist with ABC and runs ABC `cec` against the benchmark. It needs Python 3 and reads [`blifkit.py`](blifkit.py); ABC is `yosys-abc`, or set `ABC`.

```
python3 check.py random_control/router.blif router_depth_2027.blif --cec-seconds 50
```

```
simulation: 36864 vectors, 0 batches with a mismatch
print_stats: i/o = 60/ 30 lat = 0 nd = 49 edge = 124 cube = 170 lev = 3
cec: ['Networks are equivalent. Time = 0.01 sec']
```

Against the AIG as well:

```
yosys-abc -c "read_blif router_depth_2027.blif; strash; cec -n random_control/router.aig"
Networks are equivalent. Time = 0.01 sec
```

`yosys-abc -c "read random_control/router.aig; strash; print_supp"` gives 30, 60 and 60 inputs for `outport[0]` to `outport[2]`, and `print_supp -s` finds the functional supports equal to the structural ones (150 in all).

The suite's files are from lsils/benchmarks commit `3e9df8b`.
218 changes: 218 additions & 0 deletions hardware/epfl-router/blifkit.py
Original file line number Diff line number Diff line change
@@ -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
42 changes: 42 additions & 0 deletions hardware/epfl-router/check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""Check a netlist against the suite's reference circuit and count it.

usage: python -I check.py REF.blif OURS.blif [--cec-seconds N]

1. Simulation: 16 x 2048 random vectors plus the all-zero and all-one vectors, every output compared by name.
2. ABC: read_blif OURS; print_stats (the count used on the table).
3. ABC: cec REF OURS (ports matched by name).
"""
import os
import random
import subprocess
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from blifkit import Blif, compare # noqa: E402

ABC = os.environ.get("ABC", "yosys-abc")


def main():
ref_path, ours_path = sys.argv[1], sys.argv[2]
secs = 120
if "--cec-seconds" in sys.argv:
secs = int(sys.argv[sys.argv.index("--cec-seconds") + 1])
ref = Blif.read(ref_path)
ours = Blif.read(ours_path)
assert sorted(ref.inputs) == sorted(ours.inputs), "input names differ"
assert sorted(ref.outputs) == sorted(ours.outputs), "output names differ"
W = 2048
mask = (1 << W) - 1
extra = [{n: 0 for n in ref.inputs}, {n: mask for n in ref.inputs}]
bad, total = compare(ref, ours, width=W, rounds=16, seed=11, extra=extra)
print("simulation: %d vectors, %d batches with a mismatch" % (total, bad))
out = subprocess.run([ABC, "-c", "read_blif %s; print_stats" % ours_path], capture_output=True, text=True).stdout
line = [l for l in out.splitlines() if "nd =" in l][-1]
print("print_stats:", " ".join(line.split(":", 1)[1].split()))
out = subprocess.run([ABC, "-c", "cec -T %d %s %s" % (secs, ref_path, ours_path)], capture_output=True, text=True).stdout
print("cec:", [l for l in out.splitlines() if "equivalent" in l or "Networks" in l or "UNDECIDED" in l.upper()] or out[-400:])


if __name__ == "__main__":
main()
Loading
Loading