Algorithmcore
AIG balancing
Also called tree height reduction of AND trees.
Collects the maximal multi-input AND trees of an AIG and rebuilds each one over its distinct leaves, pairing the two lowest leaves first, so no node gets deeper or more numerous.
- Time
- O(N log k) expected worst
- Space
- O(N) extra
- Where
- N = the number of AND nodes of the input AIG; k = the largest number of leaves of one supergate
- Model
- Word RAM
- Properties
- deterministicnot exactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alan Mishchenko, Satrajit Chatterjee, Robert Brayton, 2006
AIG balancing is a fast pass of multi-level logic synthesis that lowers the depth of an and-inverter graph. It cuts the AIG into supergates, maximal trees of AND nodes joined by plain edges, where every inner node has one fanout. Each supergate computes the AND of its leaves, and the order in which the two-input ANDs join the leaves does not change the function. So the algorithm rebuilds each supergate from the bottom up, always joining the two leaves of lowest level first, as Huffman's algorithm joins the two smallest weights. No node of the result is deeper than the node it replaces, and the number of AND nodes does not grow.
In plain words
A long chain of AND gates computes the same thing as a short, bushy tree of AND gates over the same inputs. The chain is slow, because a signal at the bottom goes through every gate. The tree is fast.
So find every place in the circuit where AND gates feed only each other with no inverter between them, and treat the whole group as one big AND gate with many inputs. Throw out repeated inputs. Then build it again from two-input gates, as a tree. Signals that come late should go through few gates, so join the two signals that are ready first, then the next two, and so on. Do this from the inputs up to the outputs, so each group sees the new, earlier times of the groups below it.
The problem
The input is an AIG with outputs . The output is an AIG with the same output functions. The level of an input is 0 and the level of an AND node is one more than the larger level of its two fanins, and the depth is the largest level of an output. The aim is a small depth, with no more AND nodes than before. Balancing only regroups AND trees. It does not use the distributive law or any Boolean identity other than , and the order of the fanins, so it is a heuristic for the depth of the whole circuit.
The algorithm
BALANCE(G, o_1, ..., o_k)- 1
H ← an empty AIG on the inputs of G; memo ← empty - 2
for each output o: the new output is BAL(node(o)), complemented if o is BAL(v) ▷ returns a literal of H with the function of v- 3
if v is an input or the constant then return the literal of v - 4
if memo holds v then return memo[v] - 5
leaves ← the leaf literals of the supergate of v - 6
S ← the set { BAL(node(ℓ)), complemented as ℓ is : ℓ in leaves }, without the constant 1 - 7
if S holds 0, or some x and ¬x, then r ← 0 else- 8
Q ← a priority queue of S keyed by the level in H - 9
while |Q| > 1: take the two lowest x and y out of Q; put AND_H(x, y) into Q - 10
r ← the one literal left in Q, or 1 if Q is empty - 11
memo[v] ← r; return r
The supergate of an AND node is found by a walk from down its fanins. The walk goes down a fanin edge when the edge has no inverter and leads to an AND node with exactly one fanout. Every other fanin is a leaf. The fanout counts are taken over the nodes that the outputs reach, and an output counts as a fanout. A node with two fanouts is never inside a supergate, so its logic is built once and shared.
Line L6 balances each leaf first, so the queue of line L8 knows the new levels of the leaves. As a set, drops leaves that appear twice. Line L7 finds a supergate that is 0 because it holds a literal and its complement. AND_H is the AND of the AIG page, with the trivial rules and structural hashing, so equal pairs in different supergates become one node.
Example
Take the chain , with the literals 2, 4, 6, 8 and 10 for to . It has 4 AND nodes and depth 4. The supergate of the top node has the five leaves to , all at level 0.
| step | queue before (level, literal) | pair taken | new node | level |
|---|---|---|---|---|
| 1 | (0, 2), (0, 4), (0, 6), (0, 8), (0, 10) | , | 12 | 1 |
| 2 | (0, 6), (0, 8), (0, 10), (1, 12) | , | 14 | 1 |
| 3 | (0, 10), (1, 12), (1, 14) | , | 16 | 2 |
| 4 | (1, 14), (2, 16) | , | 18 | 3 |
The result has 4 AND nodes and depth 3, which is .
Levels of leaves matter when a leaf is shared. Let be an output and also a fanin of the second output . The node has two fanouts, so it is a leaf of the supergate of , at level 2. The supergate of has the leaves , at level 0 and at level 2. The queue joins and first, at level 1, and then joins that node with , at level 3. The depth falls from 4 to 3, and both graphs have 5 AND nodes.
Correctness
The full proof shows three facts. First, BAL(v) has the function of : the AND of a set of literals does not depend on the order or the grouping of the two-input ANDs, a repeated literal changes nothing, and a literal with its complement gives 0. Second, the level of BAL(v) in is at most the level of in . Write . Every binary tree over leaves of levels has a root of level at least , since a node of level over subtrees with sums and has . The greedy pairing of line L9 never raises of the queue, which gives a root of level exactly , the greedy argument of Golumbic (1976). The new leaves are fewer and, by induction, not higher than the old ones, so their is not larger, and the old supergate was a tree over the old leaves. Third, each supergate with leaf edges has AND nodes in and gets at most new ones in , and every AND node of that the outputs reach lies in exactly one supergate.
Proof: Balancing keeps the functions and does not raise any level or the node countfull
We use the notation of the and-inverter graph page: is the function of a literal , and and are the levels in the old graph and the new graph . Let be the set of AND nodes of that the outputs reach, with the fanout counts of the algorithm. For , the supergate of is the tree found by line L5. Its inner nodes are and the AND nodes that the walk goes into, and its leaf edges are the fanins where the walk stops. We write for the number of leaf edges.
Lemma 1 (the supergate is a tree). Each node that the walk enters below is entered once, and is the AND of over the leaf literals , with repeats. The supergate has inner nodes.
Proof. The walk enters a node only through a fanin edge of a node already in the supergate, and has exactly one fanout, so it is entered through that edge only, once. So the inner nodes and their fanin edges form a binary tree with root and leaf edges, which has inner nodes. An inner node below is reached by an edge with no inverter, so the tree is a tree of ANDs, and is the AND of its leaf literals.
Lemma 2 (functions). BAL(v) returns a literal of with .
Proof. By induction on the level of in . For an input or the constant, line L3 is right. For an AND node, each leaf comes from a node of smaller level, so by induction BAL(node()) has the function of node(), and the literal put into at line L6 has the function . The AND of a collection of functions does not depend on repeats, and the constant 1 does not change it, so , with the empty AND equal to 1. If holds 0 or both and , this AND is 0, which line L7 returns. Otherwise lines L8 to L10 replace two literals of by a literal of their AND, by the AND page, until one is left, so the AND of stays . The memo of line L4 returns a value that was right when it was stored.
For a finite list of integers with , let and .
Lemma 3 (the lower bound). In any binary tree whose leaves have the levels and whose inner nodes have the level one more than the larger level of their two children, the root has a level of at least .
Proof. We show for every node , where is the sum of over the leaves below . For a leaf it is an equality. For an inner node with children and , . At the root, , so .
Lemma 4 (the greedy). Let line L9 start with a queue whose levels are . The last literal has a level of at most .
Proof. We show that one round of line L9 does not raise of the levels in the queue. Let the two lowest levels be , and let the AND have level . The AND of the AIG page returns either a node of level , or, by a trivial rule, a literal of level at most , so . Let be the sum before the round and the sum after it. If , then . If and , then . If and , all levels other than are at least , so is a multiple of , say with , and . Let be the least power of two with . Then , so is a multiple of and larger than , so . In all cases does not grow. At the end the queue holds one literal of some level , with , so .
Lemma 5 (levels). For every AND node , .
Proof. By induction on . Let the leaf edges of the supergate of be with the old levels . By Lemma 1 the supergate is a binary tree over these leaves, so by Lemma 3, . By induction, the literal that line L6 makes from has a level of at most , and keeps a sub-collection of these literals, one for each distinct value. So the sum is at most , and of the levels of is at most . If line L7 returns 0 or line L10 returns 1, the level is 0. Otherwise Lemma 4 gives .
Lemma 6 (size). The number of AND nodes of is at most .
Proof. Call a root if BAL is called on it. Line L5 enters a node only if has one fanout and is reached by a plain edge, and BAL is called on a node only as an output node or as a leaf, that is, a node reached by a complemented edge, or with two or more fanouts, or as an output. A node with one fanout is either entered through its one fanin edge, or is a leaf of that edge, not both, and an output counts as a fanout. So each node of is a root or an inner node of exactly one supergate, and the supergates of the roots partition , with by Lemma 1. The memo of line L4 runs the body once per root, and lines L8 to L10 for a root with distinct leaves make at most calls of AND, each of which adds at most one node. Only these calls add nodes to .
Theorem. BALANCE returns an AIG with the same output functions as , with of each new output at most of the old one, so no more depth, and with no more AND nodes than the part of that the outputs reach.
Proof. Lemma 2 for the functions, with the output phase put back at line L2, Lemma 5 for the levels and Lemma 6 for the size.
Complexity
The walks of line L5 touch each AND node of once in all, since an inner node of a supergate has one fanout and so belongs to one supergate, and the memo of line L4 runs each supergate once. A supergate with leaves costs for the queue and expected time for the hash lookups of AND_H. The sum of over all supergates is at most the number of edges, , so the time is expected, where is the largest supergate. The extra space is the memo, the fanout counts and the queue, . The recursion of line L6 can be as deep as the AIG, and a long AIG needs an explicit stack.
Properties
What is proved. The functions of the outputs do not change. Every node of that replaces a node of has a level at most the level of , so the depth does not grow. The number of AND nodes that the outputs reach does not grow. For each supergate, the tree that line L9 builds has the least level of any tree of two-input ANDs over the same distinct leaves at the same levels.
What is not proved. The depth of is not the least depth of an AIG for the same functions. Balancing keeps the supergates of , so it cannot move logic across a node with two fanouts or across an inverter, and it never uses the distributive law. A chain of alternating AND and OR gates, , has an inverter on every edge of the AIG, so every supergate has two leaves, and balancing does not change it.
What is measured. On 1000 random AIGs with 8 inputs and 60 calls of AND each (seed 1, with each new node taking the last node as a fanin with probability 0.6 and each fanin complemented with probability 0.2), the code of this page lowered the mean depth from 14.7 to 7.2 and the mean number of reached AND nodes from 26.5 to 16.8, and it lowered the depth of 989 of them. Random AIGs have many repeated leaves and long chains, so these numbers show only that the code works. They are not benchmark results.
Variants and improvements
- Arrival times. In timing-driven balancing the leaves of line L8 are keyed by arrival times from a delay model in place of AIG levels. The same greedy is optimal for any leaf times when each AND adds the same delay.
- Balancing for area. Some versions keep the shape of a supergate when the depth would not fall, which avoids changing nodes that other passes have tuned.
- SOP balancing. A later form of balancing in ABC takes a cut of several AND and OR levels, finds a sum of products for it, and builds a balanced AND-OR tree, which can cross the inverters that stop plain balancing.
- Other operators. The same algorithm balances any associative and commutative operator. For XOR the rules of line L7 change to , so a leaf that appears twice is dropped in pairs. For the majority-inverter graph the associativity axiom plays the role of line L9.
- Compilers. Tree height reduction of sums and products in expression trees is the same idea, and parallel prefix circuits solve the harder case where every prefix of a chain is needed.
When to use it
Use balancing as a cheap first pass that removes the depth left by the source of an AIG, such as long chains from the bit-blasting of wide gates, and between passes of AIG rewriting in scripts such as the resyn scripts of ABC. It is fast enough to run many times. When the depth comes from the logic and not from the grouping of AND gates, use restructuring that changes the function of nodes, such as rewriting with a delay cost or SOP balancing.
Pitfalls
- Going through shared nodes. A node with two fanouts must be a leaf. If the walk of line L5 goes into it, its logic is copied into each supergate that uses it, and the node count grows.
- Going through inverters. The AND of with is not . The walk must stop at a complemented edge.
- Old levels for the leaves. Line L8 must use the levels of the leaves in , after line L6. With the levels of , the queue joins the wrong pairs above leaves that balancing has already made shallower.
- Joining in input order. Joining the leaves in a fixed order, such as the order of the walk, gives a tree that is balanced only when all leaves arrive together. The two lowest leaves must be joined first.
- Expecting a fixed point. A second pass can still lower the depth, since hashing in the first pass can make nodes that a second pass sees as constant or shared.
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/aig-balancing/. The authors are listed in prov/AX6R7V.jsonl.
"""AIG balancing: rebuild every multi-input AND tree of an AIG with the least depth.
An AIG uses the literal code of the and-inverter-graph page: a literal is
2 * id + c, node 0 is the constant 0, nodes 1 to n are inputs, and every
later node is an AND of two literals of older nodes. A supergate of a
node v is the tree of AND nodes reached from v through edges that are not
complemented and lead to AND nodes with exactly one fanout. Balancing
rebuilds each supergate over its distinct leaves and always ANDs the two
leaves of lowest level first.
"""
import heapq
from typing import Iterable
class Aig:
"""A small structurally hashed AIG, as on the and-inverter-graph page."""
def __init__(self, n: int) -> None:
self.n = n
self.fanin0: list[int] = [-1] * (n + 1)
self.fanin1: list[int] = [-1] * (n + 1)
self.level: list[int] = [0] * (n + 1)
self.table: dict[tuple[int, int], int] = {}
def is_and(self, v: int) -> bool:
return v > self.n
def and_(self, a: int, b: int) -> int:
if a > b:
a, b = b, a
if a == 0 or a == b ^ 1:
return 0
if a == 1:
return b
if a == b:
return a
v = self.table.get((a, b))
if v is None:
v = len(self.fanin0)
self.fanin0.append(a)
self.fanin1.append(b)
self.level.append(1 + max(self.level[a >> 1], self.level[b >> 1]))
self.table[(a, b)] = v
return 2 * v
def simulate(self, outputs: Iterable[int]) -> list[int]:
full = (1 << (1 << self.n)) - 1
val = [0] * len(self.fanin0)
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
for v in range(self.n + 1, len(self.fanin0)):
a, b = self.fanin0[v], self.fanin1[v]
val[v] = (val[a >> 1] ^ (full if a & 1 else 0)) & (val[b >> 1] ^ (full if b & 1 else 0))
return [val[o >> 1] ^ (full if o & 1 else 0) for o in outputs]
def cone(self, outputs: Iterable[int]) -> set[int]:
"""The AND nodes that the given literals reach."""
seen: set[int] = set()
stack = [o >> 1 for o in outputs]
while stack:
v = stack.pop()
if v in seen or not self.is_and(v):
continue
seen.add(v)
stack.append(self.fanin0[v] >> 1)
stack.append(self.fanin1[v] >> 1)
return seen
def depth(self, outputs: Iterable[int]) -> int:
return max((self.level[o >> 1] for o in outputs), default=0)
def supergate_leaves(g: Aig, v: int, refs: list[int]) -> list[int]:
"""The leaf literals of the supergate of AND node v, with repeats."""
leaves: list[int] = []
stack = [g.fanin1[v], g.fanin0[v]]
while stack:
lit = stack.pop()
u = lit >> 1
if lit & 1 == 0 and g.is_and(u) and refs[u] == 1:
stack.append(g.fanin1[u])
stack.append(g.fanin0[u])
else:
leaves.append(lit)
return leaves
def balance(g: Aig, outputs: list[int]) -> tuple[Aig, list[int]]:
"""A new AIG with the same functions, no more AND nodes and no more depth."""
live = g.cone(outputs)
refs = [0] * len(g.fanin0)
for v in live:
refs[g.fanin0[v] >> 1] += 1
refs[g.fanin1[v] >> 1] += 1
for o in outputs:
refs[o >> 1] += 1
h = Aig(g.n) # @line L1
memo: dict[int, int] = {}
def bal(v: int) -> int:
if not g.is_and(v): # @line L3
return 2 * v
if v in memo: # @line L4
return memo[v]
leaves = supergate_leaves(g, v, refs) # @line L5
new = {bal(lit >> 1) ^ (lit & 1) for lit in leaves} # @line L6
new.discard(1)
if 0 in new or any(x ^ 1 in new for x in new): # @line L7
r = 0
else:
heap = [(h.level[x >> 1], x) for x in sorted(new)] # @line L8
heapq.heapify(heap)
while len(heap) > 1: # @line L9
_, x = heapq.heappop(heap)
_, y = heapq.heappop(heap)
z = h.and_(x, y)
heapq.heappush(heap, (h.level[z >> 1], z))
r = heap[0][1] if heap else 1 # @line L10
memo[v] = r # @line L11
return r
new_outputs = [bal(o >> 1) ^ (o & 1) for o in outputs] # @line L2
return h, new_outputs
def min_tree_depth(levels: list[int]) -> int:
"""The least depth of a binary tree of ANDs over leaves with these levels: ceil(log2(sum of 2^level))."""
s = sum(1 << a for a in levels)
return (s - 1).bit_length()
test_aig_balancing.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aig-balancing/. The authors are listed in prov/AX6R7V.jsonl.
import heapq
import random
from functools import lru_cache
from aig_balancing import Aig, balance, min_tree_depth, supergate_leaves
def chain(n: int) -> tuple[Aig, int]:
g = Aig(n)
x = 2 * n
for i in range(n - 1, 0, -1):
x = g.and_(2 * i, x)
return g, x
def test_chain_example() -> None:
g, o = chain(5)
assert g.depth([o]) == 4 and len(g.cone([o])) == 4
h, (p,) = balance(g, [o])
assert h.depth([p]) == 3 and len(h.cone([p])) == 4
assert h.simulate([p]) == g.simulate([o])
# the pairs of the example: (a, b), (c, d), (e, ab), (cd, abe)
assert [(h.fanin0[v], h.fanin1[v]) for v in range(6, 10)] == [(2, 4), (6, 8), (10, 12), (14, 16)]
def test_late_leaf_example() -> None:
# o1 = (a & b) & (c & d) is shared; o2 = e & (f & o1) is a chain over a late leaf
g = Aig(6)
s = g.and_(g.and_(2, 4), g.and_(6, 8))
o2 = g.and_(10, g.and_(12, s))
refs_ok = g.depth([s, o2]) == 4
assert refs_ok
h, outs = balance(g, [s, o2])
assert h.simulate(outs) == g.simulate([s, o2])
assert h.depth(outs) == 3
assert len(h.cone(outs)) == len(g.cone([s, o2])) == 5
def test_duplicate_and_opposite_leaves() -> None:
g = Aig(3)
ab = g.and_(2, 4)
# (a & b) & (a & c): the leaf a appears twice
o = g.and_(ab, g.and_(2, 6))
h, (p,) = balance(g, [o])
assert len(h.cone([p])) == 2 and h.simulate([p]) == g.simulate([o])
# (a & b) & (!a & c) is 0
q = g.and_(g.and_(2, 4), g.and_(3, 6))
h2, (r,) = balance(g, [q])
assert r == 0
def test_alternating_and_or_chain_is_unchanged() -> None:
g = Aig(5)
z = g.and_(8 ^ 1, 10 ^ 1) ^ 1 # d | e
z = g.and_(6, z) # c & (d | e)
z = g.and_(4 ^ 1, z ^ 1) ^ 1 # b | ...
o = g.and_(2, z) # a & ...
h, (p,) = balance(g, [o])
assert h.depth([p]) == g.depth([o]) == 4
assert len(h.cone([p])) == 4
@lru_cache(maxsize=None)
def brute_depth(levels: tuple[int, ...]) -> int:
if len(levels) == 1:
return levels[0]
best = None
k = len(levels)
for mask in range(1, (1 << k) - 1):
if mask & 1 == 0:
continue
a = tuple(sorted(levels[i] for i in range(k) if mask >> i & 1))
b = tuple(sorted(levels[i] for i in range(k) if not mask >> i & 1))
d = 1 + max(brute_depth(a), brute_depth(b))
best = d if best is None else min(best, d)
return best
def greedy_depth(levels: list[int]) -> int:
heap = list(levels)
heapq.heapify(heap)
while len(heap) > 1:
x = heapq.heappop(heap)
y = heapq.heappop(heap)
heapq.heappush(heap, 1 + max(x, y))
return heap[0]
def test_greedy_pairing_is_optimal_against_all_trees() -> None:
rng = random.Random(5)
for _ in range(600):
k = rng.randrange(1, 8)
levels = tuple(sorted(rng.randrange(0, 4) for _ in range(k)))
best = brute_depth(levels)
assert greedy_depth(list(levels)) == best == min_tree_depth(list(levels))
def random_aig(rng: random.Random) -> tuple[Aig, list[int]]:
n = rng.randrange(2, 7)
g = Aig(n)
lits = [2 * i for i in range(1, n + 1)]
for _ in range(rng.randrange(3, 40)):
if rng.random() < 0.5 and len(lits) > n:
a = lits[-1]
else:
a = rng.choice(lits)
b = rng.choice(lits)
x = g.and_(a ^ (rng.random() < 0.25), b ^ (rng.random() < 0.25))
if x > 1:
lits.append(x)
outs = [rng.choice(lits[n:] or lits) ^ rng.randrange(2) for _ in range(rng.randrange(1, 4))]
return g, outs
def test_random_aigs_function_size_and_depth() -> None:
rng = random.Random(99)
for _ in range(700):
g, outs = random_aig(rng)
h, new = balance(g, outs)
assert h.simulate(new) == g.simulate(outs)
assert len(h.cone(new)) <= len(g.cone(outs))
for o, p in zip(outs, new):
assert h.level[p >> 1] <= g.level[o >> 1]
# a second pass may find more, never less
h2, new2 = balance(h, new)
assert h2.depth(new2) <= h.depth(new)
assert h2.simulate(new2) == g.simulate(outs)
def test_supergate_stops_at_shared_and_complemented_edges() -> None:
g = Aig(4)
ab = g.and_(2, 4)
cd = g.and_(6, 8)
top = g.and_(ab, cd ^ 1)
refs = [0] * len(g.fanin0)
for v in g.cone([top, ab]):
refs[g.fanin0[v] >> 1] += 1
refs[g.fanin1[v] >> 1] += 1
refs[top >> 1] += 1
refs[ab >> 1] += 1
assert sorted(supergate_leaves(g, top >> 1, refs)) == sorted([ab, cd ^ 1])
History
The reduction of tree height for associative operators comes from parallel compilation in the 1960s and 1970s, and Golumbic (1976) proved that joining the two smallest values first gives the least height for a tree with given leaf values, a minimax analogue of Huffman coding. Logic synthesis systems such as SIS used tree height reduction for timing. Mishchenko, Chatterjee and Brayton (2006) paired AIG balancing, which lowers delay with no gain in area, with DAG-aware AIG rewriting, which lowers area with no gain in delay, and the balance command of ABC became a standard step of synthesis scripts.
References
- Alan Mishchenko, Satrajit Chatterjee and Robert Brayton, DAG-aware AIG rewriting, a fresh look at combinational logic synthesis, Proceedings of the 43rd Design Automation Conference, 2006, pages 532 to 535, the abstract and the experiments, where AIG balancing for delay is used together with rewriting for area
- Martin Charles Golumbic, Combinatorial merging, IEEE Transactions on Computers C-25(11), 1976, pages 1164 to 1167, the merge of the two smallest values with cost max plus one, and its optimality for the least height of a tree with given leaf values
- Robert Brayton and Alan Mishchenko, ABC, an academic industrial-strength verification tool, Computer Aided Verification (CAV 2010), Lecture Notes in Computer Science 6174, Springer, 2010, pages 24 to 40, the synthesis commands of ABC on AIGs, among them balance
- Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 8, Multiple-Level Combinational Logic Optimization (the sections on delay and on restructuring for timing)
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 | W2 basic |
|
Tag AX6R7V Edit this page History Report an error Markdown