Data structureresearch
Majority-inverter graph
Also called MIG.
A Boolean network of three-input majority nodes with inverted edges, with an algebra of five axioms for restructuring, from Amaru, Gaillardon and De Micheli.
- Time
- O(N) levelsO(1) expected majO(N 2^n / w) simulate
- Space
- O(N) nodes
- Where
- N = the number of majority nodes; n = the number of primary inputs; w = the number of bits in a machine word
- Model
- Word RAM
- Properties
- not concurrentnot externalpersistent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Luca Amaru, Pierre Emmanuel Gaillardon, Giovanni De Micheli, 2014
A majority-inverter graph, or MIG, is a Boolean network in which every inner node is the majority of three inputs and every edge may carry an inverter. The majority is 1 when at least two of its inputs are 1. With one input fixed to 0 it is AND, and with one input fixed to 1 it is OR, so every and-inverter graph is an MIG with the same number of nodes. Amaru, Gaillardon and De Micheli gave the MIG an algebra of five axioms, and they restructure the graph by applying these axioms, mainly to make it shallower.
In plain words
Build a circuit from one kind of gate that takes three wires and outputs the value that at least two of them carry. A dot on a wire flips its value. If you tie one input of the gate to 0, it becomes an AND gate. If you tie it to 1, it becomes an OR gate. So this gate can do all that an AND gate can do, and often more in one step: one gate gives the carry of an adder.
As with AND gates, keep a dictionary of the gates you have built, keyed by their three input wires, and reuse a gate when you see it again.
A small set of rules says when two drawings of majority gates compute the same thing. Tools apply these rules to move late signals near the output and so make the circuit faster.
The abstract type
An MIG over the inputs stores a set of nodes, each one a Boolean function of the inputs. A literal names a node and a phase, as on the AIG page. The operations are:
- INPUT(i): the literal of .
- MAJ(a, b, c): a literal whose function is . NOT is free. AND(a, b) is MAJ(a, b, 0) and OR(a, b) is MAJ(a, b, 1).
- SIMULATE(o_1, ..., o_k): the truth tables of the given literals.
- LEVELS: the depth of each node, the number of majority nodes on the longest path from an input.
The contract of MAJ is that the function is right, that the result is the same for all six orders of and for the call on with the phase flipped, and that no node is added twice for the same normal form. As in an AIG, two literals with the same function can still differ.
The equalities that the tools use are the axioms of the TCAD 2016 paper. For all functions :
| axiom | identity |
|---|---|
| , commutativity | |
| , majority | and |
| , associativity | |
| , distributivity | |
| , inverter propagation |
The paper also derives three rules from them. Relevance, , says that , where is with every replaced by : the value of matters only where . Complementary associativity, , says that . Substitution, , splits a node on a variable and a second signal . The authors prove that is sound and complete for the functions of majority and complement: two MIGs compute the same function if and only if a finite sequence of axioms turns one into the other. These identities are the laws of the median operation in Knuth's treatment, Section 7.1.1 of Volume 4A.
Representation
A literal is the integer as in the AIG: node 0 is the constant 0, so literal 1 is the constant 1, nodes 1 to are the inputs, and every later node holds three fanin literals of older nodes. A node is stored in a normal form. Its fanins are sorted, lie on three different nodes, and at most one of them is complemented. A hash table maps the triple to . The constant 1 counts as a complemented edge to node 0, so an AND node is stored as and an OR node as .
Operations
MAJ(a, b, c)- 1
sort a, b, c so that a ≤ b ≤ c ▷ Ω.C - 2
if a = b or b = c then return b ▷ Ω.M, ⟨x x z⟩ = x - 3
if a = b xor 1 then return c; if b = c xor 1 then return a ▷ Ω.M, ⟨x x̄ z⟩ = z - 4
if two or more of a, b, c are odd then return MAJ(a xor 1, b xor 1, c xor 1) xor 1 ▷ Ω.I - 5
if T holds the key (a, b, c) then return 2·T[a, b, c] ▷ structural hashing - 6
v ← a new node with fanins (a, b, c); T[a, b, c] ← v; return 2v SIMULATE(o_1, ..., o_k) ▷ truth tables as integers of 2^n bits- 7
val[0] ← 0; val[i] ← the table of x_i for i = 1 to n - 8
for v ← n + 1 to the last node: val[v] ← ⟨lit(a_v) lit(b_v) lit(c_v)⟩ bitwise - 9
return lit(o_1), ..., lit(o_k) ▷ lit(2u + c) = val[u], complemented if c = 1
Line L1 applies , so that the six orders of a call give one key. In sorted order the two literals of one node are next to each other, so lines L2 and L3 find every pair on one node and apply . After them the three fanins lie on three different nodes. Line L4 applies when it lowers the number of complemented fanins, which leaves at most one. The inner call does not reach line L4 again. Line L8 computes the majority of three words with , so all points are simulated at once.
The axioms and are not applied by MAJ. They change the shape of the graph over more than one node, and an optimizer applies them where they lower the depth or the size.
Example
Build a full adder over with the literals 2, 4 and 6. The carry is one majority node, and the sum takes two more.
| step | call | normal form | result | nodes |
|---|---|---|---|---|
| 1 | MAJ(2, 4, 6), the carry | (2, 4, 6) | new node 4, literal 8 | 1 |
| 2 | MAJ(2, 4, 7), the inner node | (2, 4, 7) | new node 5, literal 10 | 2 |
| 3 | MAJ(9, 6, 10), the sum | (6, 9, 10) | new node 6, literal 12 | 3 |
| 4 | MAJ(4, 6, 2), the carry again | (2, 4, 6) | found node 4, literal 8 | 3 |
| 5 | MAJ(3, 5, 7), the complement of the carry | (2, 4, 6) by L4 | literal 9 | 3 |
SIMULATE gives 232 (the bits 11101000) for the carry and 150 (the bits 10010110) for the sum. The MIG has 3 nodes and depth 2, while the AIG of the same adder on the and-inverter graph page has 7 AND nodes and depth 4. No MIG with fewer than 3 nodes computes both outputs, because the sum of three inputs is not the majority of three literals. Steps 4 and 5 show and at work: a permuted call and the call on three complemented literals find node 4 again.
lowers the depth when a late signal sits deep in the graph. Over seven inputs, let , which has depth 3. Then has depth 5, because enters at the bottom. swaps and and gives , which has depth 4 and the same truth table.
Correctness
The full proof shows that every node stays in the normal form: three sorted fanins on three different older nodes, at most one of them complemented, and a table that maps each triple to its node and holds no other key. It then shows that MAJ returns a literal whose function is , since each line uses an axiom that is true for all values, and that MAJ gives the same literal for all orders of its inputs and the complemented literal for complemented inputs. So no two nodes have the same normal form. SIMULATE is right by induction on the node number. The five axioms hold for all 0 and 1 values, which the test file checks on all , and points.
Proof: MAJ keeps the normal form, computes the majority and merges permuted and complemented callsfull
We use the literal code of the page: literal names node with phase , node 0 is the constant 0, and is the function of a literal over the primary inputs, so . Write and .
Invariant (N). Every node has fanins with , with , and distinct and smaller than , and with at most one of odd. The table maps each such triple to its node and holds no other key.
Lemma 1 (pairs on one node). After line L1 sorts , if two of the three literals lie on one node, then line L2 or line L3 returns.
Proof. The two literals of node are and , and no other literal lies between them. If and lie on one node, then or with even, and lines L2 or L3 apply. The same holds for and . If and lie on one node, then , so or , and line L2 applies.
Lemma 2 (the function). MAJ(a, b, c) returns a literal with , and it keeps (N).
Proof. Sorting at line L1 does not change the function, since is symmetric. Line L2 returns when two inputs are equal, and , since at least two of the three values are the value of . Line L3 returns the third input when two inputs are complements, and , since exactly one of is 1. Past line L3, by Lemma 1, the three literals lie on three different nodes. If two or more are odd, line L4 calls MAJ on the three complements. These lie on the same three nodes, and at most one of them is odd, so the inner call passes lines L2 to L4 and reaches line L5. By induction on the depth of the calls, it returns a literal with , and , because complementing all three values of a majority complements the result: two or more ones become two or more zeros. At line L5 the triple is sorted, on three distinct nodes and has at most one odd literal. If holds it, maps it to a node whose fanins are exactly by (N), and that node computes . Otherwise line L6 makes a node with these fanins, which all lie on older nodes, and adds its key, so (N) holds again.
Lemma 3 (permutations and complements). For all literals, MAJ returns the same literal for every order of , and MAJ() MAJ() .
Proof. After line L1 the computation depends only on the sorted triple, which is the same for every order. For the second claim, let be sorted. If two literals lie on one node, complementing all three keeps each pair on its node and keeps the sorted order up to a swap inside a pair, which the tests of lines L2 and L3 do not see. So both calls return at the same test, one with the result or the third literal and the other with its complement. Otherwise the three nodes are distinct, so complementing every literal keeps the order of the nodes and the sorted order. Let be the number of odd literals in , so the complements have . Exactly one of and is at least 2. The call with the larger count goes through line L4 to the call with the smaller count and flips its result, so the two results differ exactly in the phase.
Theorem. Starting from an empty graph, every sequence of INPUT and MAJ calls keeps (N), each call returns a literal with the right function, and no two nodes have the same triple of fanins. SIMULATE returns the truth table of each requested literal.
Proof. The empty graph satisfies (N), and Lemma 2 keeps it and gives the functions. Line L6 adds a key only when does not hold it, so no two nodes share a triple. For SIMULATE, the fanins of node lie on nodes smaller than by (N), so when line L8 reaches the values of its fanins are their truth tables, by induction on , and the bitwise is the majority at each point. Line L9 complements the table of a node for an odd literal.
Complexity
MAJ sorts three numbers, makes at most one inner call and does one hash lookup, so it takes expected time. SIMULATE takes word operations for nodes and inputs. LEVELS is one pass in . The space is three integers for each node and one table entry, .
An MIG never needs more nodes than an AIG of the same function, and never more depth, because each AND node becomes one majority node with a constant input. The full adder shows that it can need fewer. A node costs three fanins in place of two, so the memory per node is higher.
Variants
- Depth optimization. The 2014 and 2016 papers push critical signals up with , and from left to right, then clean up with and from right to left. The papers report depth and size results on benchmark circuits against AIG optimization in ABC. These are measured results, not proved bounds.
- Size optimization. The same axioms, applied to remove nodes, with and from right to left as the main steps.
- Cut rewriting. As in AIG rewriting, a small cut of a node is replaced by a smaller MIG of the same function, which exact synthesis finds for small numbers of inputs.
- XOR-majority graphs. Adding a three-input XOR node gives a graph that suits arithmetic, since the sum of a full adder is then one node.
- Mapping. An MIG can be mapped to cells or to lookup tables by technology mapping over cuts, in the same way as an AIG.
When to use it
Use an MIG when the target logic has majority gates, as in several proposed nanotechnologies, or when you want to restructure for depth with algebraic rules that are stronger than AND and OR rules. Arithmetic circuits gain most, since carries are majorities. Use an AIG when you need the common format of the tool chain, its large set of tested passes, and a node of two fanins. Use a BDD when you need a canonical form.
Pitfalls
- Sorting without looking at pairs. The checks of lines L2 and L3 rely on the sorted order, which puts next to . A check of only misses and keeps a node that is really a wire.
- A normal form with complemented edges on both sides. Without line L4, and get two nodes. The constant 1 must count as a complemented 0, or AND and OR nodes are stored in two forms.
- Reading completeness as an algorithm. Completeness says that a sequence of axioms joins two equal MIGs. It does not say how to find a short sequence, or how to find the smallest MIG. The optimizers that apply the axioms are heuristics.
- Counting depth with constant inputs. An AND node of an MIG has the constant 0 as a fanin. The constant is at level 0 and adds no depth, but a node with a constant input is still a node.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/majority-inverter-graph/. The authors are listed in prov/AVZMQ8.jsonl.
"""A majority-inverter graph with complemented edges, a normal form and hashing.
A literal is 2 * id + c as on the and-inverter-graph page: node 0 is the
constant 0, so literal 1 is the constant 1, and nodes 1 to n are inputs.
Every later node is a majority M(a, b, c) of three literals of older
nodes. MAJ puts each call in a normal form before the hash lookup: the
fanins are sorted, the rules M(x, x, z) = x and M(x, not x, z) = z are
applied, and at most one fanin is complemented, using the axiom
not M(x, y, z) = M(not x, not y, not z). AND is M(a, b, 0) and OR is
M(a, b, 1).
"""
from typing import Iterable
def maj3(x: int, y: int, z: int) -> int:
"""Bitwise majority of three integers."""
return (x & y) | (x & z) | (y & z)
class Mig:
"""A structurally hashed MIG over n primary inputs."""
def __init__(self, n: int) -> None:
self.n = n
self.fanins: list[tuple[int, int, int]] = [(-1, -1, -1)] * (n + 1)
self.table: dict[tuple[int, int, int], int] = {}
def input(self, i: int) -> int:
if not 1 <= i <= self.n:
raise ValueError("no such input")
return 2 * i
def num_nodes(self) -> int:
return len(self.fanins) - self.n - 1
def maj(self, a: int, b: int, c: int) -> int:
"""The literal of M(a, b, c) in normal form."""
a, b, c = sorted((a, b, c)) # @line L1
if a == b or b == c: # @line L2
return b
if a ^ 1 == b: # @line L3
return c
if b ^ 1 == c:
return a
if (a & 1) + (b & 1) + (c & 1) >= 2: # @line L4
return self.maj(a ^ 1, b ^ 1, c ^ 1) ^ 1
node = self.table.get((a, b, c)) # @line L5
if node is not None:
return 2 * node
node = len(self.fanins) # @line L6
self.fanins.append((a, b, c))
self.table[(a, b, c)] = node
return 2 * node
def and_(self, a: int, b: int) -> int:
return self.maj(a, b, 0)
def or_(self, a: int, b: int) -> int:
return self.maj(a, b, 1)
def simulate(self, outputs: Iterable[int]) -> list[int]:
"""Truth tables of the given literals over all 2^n points, x1 the high bit of the point."""
full = (1 << (1 << self.n)) - 1
val = [0] * len(self.fanins) # @line L7
for i in range(1, self.n + 1):
t = 0
for m in range(1 << self.n):
if (m >> (self.n - i)) & 1:
t |= 1 << m
val[i] = t
def lit(x: int) -> int:
return val[x >> 1] ^ (full if x & 1 else 0)
for v in range(self.n + 1, len(self.fanins)): # @line L8
a, b, c = self.fanins[v]
val[v] = maj3(lit(a), lit(b), lit(c))
return [lit(o) for o in outputs] # @line L9
def levels(self) -> list[int]:
lev = [0] * len(self.fanins)
for v in range(self.n + 1, len(self.fanins)):
lev[v] = 1 + max(lev[x >> 1] for x in self.fanins[v])
return lev
def depth(self, outputs: Iterable[int]) -> int:
lev = self.levels()
return max((lev[o >> 1] for o in outputs), default=0)
test_majority_inverter_graph.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/majority-inverter-graph/. The authors are listed in prov/AVZMQ8.jsonl.
import itertools
import random
from majority_inverter_graph import Mig, maj3
def M(x: int, y: int, z: int) -> int:
return 1 if x + y + z >= 2 else 0
def points(k: int):
return itertools.product((0, 1), repeat=k)
def test_axioms_on_all_assignments() -> None:
for x, y, z in points(3):
# commutativity
assert M(x, y, z) == M(y, x, z) == M(z, y, x)
# majority
assert M(x, x, z) == x and M(x, 1 - x, z) == z
# inverter propagation
assert 1 - M(x, y, z) == M(1 - x, 1 - y, 1 - z)
# AND and OR
assert M(x, y, 0) == (x & y) and M(x, y, 1) == (x | y)
for x, y, z, u in points(4):
# associativity
assert M(x, u, M(y, u, z)) == M(z, u, M(y, u, x))
# complementary associativity
assert M(x, u, M(y, 1 - u, z)) == M(x, u, M(y, x, z))
for x, y, z, u, v in points(5):
# distributivity
assert M(x, y, M(u, v, z)) == M(M(x, y, u), M(x, y, v), z)
def test_relevance_for_every_function_of_three_inputs() -> None:
# M(x, y, z) = M(x, y, z with x replaced by not y), for every z(x, y, w)
for table in range(256):
def z(x: int, y: int, w: int) -> int:
return (table >> (4 * x + 2 * y + w)) & 1
for x, y, w in points(3):
assert M(x, y, z(x, y, w)) == M(x, y, z(1 - y, y, w))
def test_substitution_on_random_functions() -> None:
rng = random.Random(3)
for _ in range(500):
tx, ty, tz = (rng.randrange(256) for _ in range(3))
def f(v: int, u: int, w: int) -> int:
def ev(t: int) -> int:
return (t >> (4 * v + 2 * u + w)) & 1
return M(ev(tx), ev(ty), ev(tz))
for v, u, w in points(3):
lhs = f(v, u, w)
rhs = M(v, M(1 - v, f(u, u, w), u), M(1 - v, f(1 - u, u, w), 1 - u))
assert lhs == rhs
def test_normal_form_merges_axiom_sides() -> None:
g = Mig(3)
x, y, z = 2, 4, 6
m = g.maj(x, y, z)
assert g.maj(y, x, z) == g.maj(z, y, x) == m
assert g.maj(x, x, z) == x and g.maj(x, x ^ 1, z) == z
assert g.maj(x ^ 1, y ^ 1, z ^ 1) == m ^ 1
assert g.num_nodes() == 1
for v in range(g.n + 1, len(g.fanins)):
a, b, c = g.fanins[v]
assert a < b < c and (a & 1) + (b & 1) + (c & 1) <= 1
def test_associativity_and_distributivity_as_graphs() -> None:
g = Mig(5)
x, y, z, u, v = (2 * i for i in range(1, 6))
left = g.maj(x, u, g.maj(y, u, z))
right = g.maj(z, u, g.maj(y, u, x))
assert g.simulate([left]) == g.simulate([right])
d1 = g.maj(x, y, g.maj(u, v, z))
d2 = g.maj(g.maj(x, y, u), g.maj(x, y, v), z)
assert g.simulate([d1]) == g.simulate([d2])
def test_full_adder_example() -> None:
g = Mig(3)
a, b, c = 2, 4, 6
carry = g.maj(a, b, c)
s = g.maj(carry ^ 1, c, g.maj(a, b, c ^ 1))
assert g.num_nodes() == 3
assert g.simulate([s, carry]) == [150, 232]
assert g.depth([s, carry]) == 2
def test_depth_example() -> None:
g = Mig(7)
x, u, y, p, q, r, t = (2 * i for i in range(1, 8))
z = g.maj(p, q, g.maj(r, t, g.and_(p, r)))
f = g.maj(x, u, g.maj(y, u, z))
f2 = g.maj(z, u, g.maj(y, u, x))
assert (g.depth([z]), g.depth([f]), g.depth([f2])) == (3, 5, 4)
assert g.simulate([f]) == g.simulate([f2])
def random_formula(rng: random.Random, n: int, depth: int):
if depth == 0 or rng.random() < 0.2:
return ("x", rng.randrange(1, n + 1), rng.randrange(2))
op = rng.choice(["maj", "and", "or"])
k = 3 if op == "maj" else 2
return (op, [random_formula(rng, n, depth - 1) for _ in range(k)], rng.randrange(2))
def evaluate(f, x) -> int:
if f[0] == "x":
return x[f[1] - 1] ^ f[2]
v = [evaluate(h, x) for h in f[1]]
if f[0] == "maj":
r = M(*v)
elif f[0] == "and":
r = v[0] & v[1]
else:
r = v[0] | v[1]
return r ^ f[2]
def build(g: Mig, f) -> int:
if f[0] == "x":
return g.input(f[1]) ^ f[2]
args = [build(g, h) for h in f[1]]
r = g.maj(*args) if f[0] == "maj" else (g.and_(*args) if f[0] == "and" else g.or_(*args))
return r ^ f[2]
def test_random_formulas_against_truth_tables() -> None:
rng = random.Random(17)
for _ in range(600):
n = rng.randrange(1, 6)
g = Mig(n)
forms = [random_formula(rng, n, rng.randrange(1, 5)) for _ in range(3)]
outs = [build(g, f) for f in forms]
for f, t in zip(forms, g.simulate(outs)):
for m, x in enumerate(points(n)):
assert (t >> m) & 1 == evaluate(f, x)
size = g.num_nodes()
assert [build(g, f) for f in forms] == outs and g.num_nodes() == size
keys = list(g.fanins[g.n + 1:])
assert len(keys) == len(set(keys))
def test_bitwise_majority() -> None:
assert maj3(0b1100, 0b1010, 0b0110) == 0b1110
History
The majority function is the heart of threshold logic and of the early work on switching circuits, and the median laws of were studied by Birkhoff and Kiss and later by Knuth. Amaru, Gaillardon and De Micheli (DAC 2014) made the majority node the single gate of a logic network, gave it the axioms and the derived rules , and showed depth optimization by axiom application. Their 2016 paper in IEEE TCAD proved that is sound and complete. Later work added exact synthesis of small MIGs, cut rewriting and XOR-majority graphs, and the EPFL logic synthesis libraries made MIGs one of their main network types.
References
- Luca Amaru, Pierre-Emmanuel Gaillardon and Giovanni De Micheli, Majority-inverter graph, a novel data-structure and algorithms for efficient logic optimization, Proceedings of the 51st Design Automation Conference, 2014, the definition of the MIG, the axioms Omega, and the depth and size optimization by axiom application
- Luca Amaru, Pierre-Emmanuel Gaillardon and Giovanni De Micheli, Majority-inverter graph, a new paradigm for logic optimization, IEEE Transactions on Computer-Aided Design 35(5), 2016, pages 806 to 819, the axioms Omega, the derived rules Psi, the soundness and completeness of Omega, and the optimization algorithms
- Donald E. Knuth, The Art of Computer Programming, Volume 4A, Combinatorial Algorithms, Part 1, Addison-Wesley, 2011, Section 7.1.1, the median operation and its laws
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag AVZMQ8 Edit this page History Report an error Markdown