Algorithmadvanced
MUSTANG state assignment
Also called MUSTANG, fanin and fanout oriented state assignment.
Devadas, Ma, Newton and Sangiovanni-Vincentelli's encoder that gives close codes to states with common fanin or fanout to help multi-level logic sharing.
- Solves
- State assignment
- Time
- O(R o + n^2 (n + o + R)) worst
- Space
- O(n^2 + R) extra
- Where
- R = the number of rows of the state table; n = the number of states; o = the number of primary outputs
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Srinivas Devadas, Hi Keung Tony Ma, A. Richard Newton, Alberto L. Sangiovanni Vincentelli, 1988
MUSTANG is a method of state assignment for finite state machines whose logic is built as a multilevel network rather than a PLA. Its idea is that two states should get codes at a small Hamming distance when their logic has something to share. In the fanout oriented mode, present states that go to the same next states or assert the same outputs attract each other, so that the product terms for them can merge or share a common factor. In the fanin oriented mode, next states that are reached from the same present states or under the same inputs attract each other. The weights form a graph on the states, and a greedy embedding places the states on the corners of the code cube one at a time, keeping heavy pairs close. Devadas, Ma, Newton and Sangiovanni-Vincentelli published it in 1988. The only thing this page proves is that the codes are valid. The rest is measured, and an exhaustive search over the codes shows that MUSTANG is not optimal for the final logic: on the example, the fanout code gives the most expensive two-level logic of all twelve classes of two-bit codes.
In plain words
A code is a string of bits for each state. Codes that differ in few bits make logic that can share parts. MUSTANG counts, for each pair of states, how much their rows of the table have in common: the same next state, the same output, the same source state or the same input. A large count means the pair should get codes that differ in few bits. It then puts the states on the corners of a cube, one by one. Each time, it takes the state most tied to the states already placed, and puts it on the free corner nearest to them, counting the ties.
The problem
The input is a reduced finite state machine with states, given as a table of rows (input, present state, next state, output), and a code length , by default . The output is an injective code from the states to . The aim is small multilevel logic for the encoded next-state and output functions. That cost depends on the multilevel optimizer, so MUSTANG works on a proxy: for a weight on each pair of states, it tries to make the embedding cost
small, where is the Hamming distance. Minimizing this cost over injective codes is a quadratic assignment problem on the corners of the cube. MUSTANG does not solve it exactly.
The algorithm
This page uses simplified weights. For states , let be the number of rows from present state to next state , the number of rows of that assert output , the number of rows from to , and the number of rows with input that go to . A shared next state counts times because all of its code bits are shared.
MUSTANG(M, mode)- 1
k ← ⌈log2 n⌉ - 2
if mode = fanout then w(s, t) ← k · Σ_u a(s, u) a(t, u) + Σ_j b(s, j) b(t, j) for each pair of states - 3
else w(s, t) ← k · Σ_p c(p, s) c(p, t) + Σ_x d(x, s) d(x, t) for each pair of states - 4
enc ← empty - 5
while some state is not placed do - 6
s ← the unplaced state with the largest total weight to the placed states; ties to the largest total weight to all states, then to the first state - 7
enc(s) ← the free corner c with the least Σ over placed t of w(s, t) · d_H(c, enc(t)); ties to the smallest c - 8
return enc
The weights of the paper are more detailed than lines L2 and L3; they were not checked against the paper here, and the forms above keep only the two ideas, fanout and fanin. The paper also has more than one embedding method. The greedy of lines L5 to L7 is a simple one in the same spirit.
Example
Take the machine of the KISS page, with one input , one output and four states:
| present | ||
|---|---|---|
| / 1 | / 0 | |
| / 0 | / 1 | |
| / 0 | / 1 | |
| / 1 | / 0 |
Fanout weights (). The states and both go to twice, which gives , and both assert once, which gives 1, so . The states and share the next states and once each and once, so . Every other pair shares only and has weight 1.
The greedy starts with , whose total weight 11 ties with , at corner . Then , tied to by 9, goes to . Then goes to (corners and tie at 3), and to . The embedding cost is , which equals the least cost over all 24 codes. So the greedy solves its own problem exactly here.
Fanin weights. The state is never a next state, so all its weights are 0. The pair is reached from and from , which gives , and under each input once, which gives 2, so . The pairs and share only inputs and get weight 4 each. The greedy gives , , , , with embedding cost 18, again the least possible.
The final logic. An exact two-level minimization, with the unused codes as don't cares, gives these costs over the 12 classes of two-bit codes (24 codes up to swapping the bits), in cubes and literals:
| code | cubes | literals |
|---|---|---|
| best of the 12 classes (, , , ) | 4 | 8 |
| MUSTANG, fanin | 6 | 14 |
| MUSTANG, fanout | 7 | 19 |
| worst of the 12 classes | 7 | 19 |
The fanout code, optimal for its embedding cost, gives the worst two-level logic of all. The best code puts and at distance 2, the opposite of what their weight asks. The reason is visible in the table: and share their next state, but they assert under opposite inputs, and the weights do not see which input a shared output belongs to. Two-level cost is only a proxy for the multilevel logic that MUSTANG aims at, and the multilevel cost is not measured here. But the example shows that a small embedding cost does not ensure small logic.
Correctness
The full proof shows that the loop stops after rounds, and that the result is an injective code of bits: each round places one new state on a free corner, and a free corner exists because . That is all that is proved. The weights are a heuristic, the greedy embedding need not minimize the embedding cost, and the embedding cost need not track the logic.
All other claims are measurements. On 100 random machines with 4 states, one input bit and one output bit, every entry specified (seed 1988), the greedy reached the least embedding cost on 84 machines in the fanout mode and on 87 in the fanin mode. The exact two-level logic matched the best two-bit code on 33 machines (fanout), 47 (fanin) and 57 (the better of the two), with 87, 68 and 47 extra cubes in total, and the better of the two lost at most 2 cubes on one machine. On 8 random weight graphs on 5 states with 3 bits (seed 7), the greedy reached the least embedding cost on 6. The two-level cube count is a proxy, chosen because it can be computed exactly on small machines. MUSTANG targets multilevel logic, and the paper measures literal counts after multilevel optimization on benchmark machines.
Proof: Validity of the MUSTANG codesfull
We use the notation of the page. The machine has states, and is the code length, with ; the default (at least 1) has this property. The weights of lines L2 and L3 are finite numbers, and nothing below depends on their values.
Theorem (valid codes)
The loop of lines L5 to L7 stops after exactly rounds, and line L8 returns an injective map from the states to .
Proof. We show by induction on the number of rounds done that the placed states are exactly distinct states, each with its own code, and that no two placed states share a code.
At the start, and nothing is placed. Suppose the claim holds after rounds. Then some state is unplaced, so line L6 has a candidate and picks an unplaced state . The placed states use distinct corners, and , so at least one corner is free, and line L7 picks a free corner . After the round, is placed with code , was not placed before, and no placed state has code . So the claim holds after rounds.
Each round places one new state, so after rounds every state is placed and the loop stops. By the claim, the codes are distinct, so the map is injective.
The choices of lines L6 and L7 are well defined, since the tie rules (the total weight, then the order of the states; the smallest corner) give a single answer. So the result is a function of the machine and the mode.
What is not proved
Nothing here says that the codes minimize the embedding cost . The greedy places each state once and never moves it, and the tests find weight graphs on which it misses the least cost. Nothing here says that a small embedding cost gives small logic: on the example of the page, the fanout code has the least embedding cost and the worst minimum two-level cover of all two-bit codes, found by exhaustive search. Every statement on the page about the quality of the codes is a measurement on small random machines, and it uses the two-level cube count as a proxy for the multilevel cost that MUSTANG aims at.
Complexity
Lines L2 and L3 count the rows in time and then compute pair weights, each in time for fanout and for fanin. In the loop, line L6 takes time per round with running sums or per candidate, and line L7 tries at most corners with work each. Over rounds this is . The total is time and space for the weights and the counts. The multilevel optimization that follows, and that decides the real cost, is not counted.
Properties
- Valid codes. The codes are injective, of the requested length.
- Not optimal. Neither the embedding cost nor the final logic is minimized. On the example the fanout code gives the worst two-level logic of all codes. None of KISS, NOVA and MUSTANG is optimal for the final logic: on the example machines of the three pages, an exhaustive search over all codes finds cheaper logic than each of them gives.
- Two modes. Fanout weights aim at sharing in the logic that reads the present state. Fanin weights aim at sharing in the next-state logic. Running both and keeping the better result costs twice the time, and on the measured machines it matched the best code more often than either mode alone.
- Fast. The method is polynomial, with no two-level minimization in the loop, unlike KISS and NOVA.
- Deterministic. The tie rules fix the result.
Variants and improvements
- Better embeddings. Any heuristic for the quadratic assignment problem on the hypercube, such as local search with swaps of two codes, can replace lines L5 to L7.
- Longer codes. More bits give more room to place heavy pairs at distance 1, at the cost of more flip-flops.
- Two-level targets. For a PLA, KISS and NOVA use face constraints from symbolic minimization, which see the inputs under which rows agree.
- Later encoders. De Micheli's book (Chapter 9) describes encodings for multilevel logic that use symbolic factoring rather than pairwise weights.
When to use it
Use MUSTANG when the controller will be built as multilevel logic and the machine is too large for methods that run a minimizer for each candidate code. Try both modes and keep the better result after multilevel optimization. For small machines, an exhaustive search over codes with the real cost measure is better, and it shows how far the weights are from the logic.
Pitfalls
- Taking the embedding cost as the cost. The example has the least embedding cost and the worst logic.
- Unreduced machines. Equivalent states attract each other strongly, and they waste code space. Reduce the machine first with DFA minimization or incompletely specified FSM minimization.
- Ties. Small machines have many equal weights, so the tie rules decide much of the result.
- Measuring with the wrong cost. MUSTANG aims at multilevel logic. A two-level result after Espresso says little about the multilevel result, and the reverse.
- Input values. The weights of lines L2 and L3 count shared outputs and next states without asking under which inputs they occur, which is how the example goes wrong.
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
# Shared helper of the hs3 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small exact two-level logic for finite state machines.
This module holds no state encoder. It gives the encoders and their tests:
- an exact multiple-valued, multiple-output two-level minimizer for tiny
functions (all cubes, then an exact set cover by branch and bound);
- the symbolic function of a machine (present state as one multiple-valued
input, next state as one output per state) and the encoded function of a
machine under given codes;
- a check that a cover implements the machine;
- an exhaustive search for the best codes of a given length.
A machine is (ni, no, states, rows). A row is (inp, ps, ns, out): inp is a
string over 0, 1 and - of length ni, ps and ns are state names, and out is
a string over 0, 1 and - of length no. Rows of one present state must not
overlap in the input. Input and state pairs that no row covers are don't
cares.
"""
import itertools
# ---------------------------------------------------------------- minimizer
def _minterms(domains):
return list(itertools.product(*[range(d) for d in domains]))
def _literals(cube, domains):
return sum(1 for m, d in zip(cube, domains) if m != (1 << d) - 1)
def minimize(domains, on, dc):
"""Exact minimum cover; return a list of (cube, outputs).
domains[i] is the number of values of variable i (2 for a binary one).
on[j] and dc[j] are sets of points (tuples) for output j. The cover has
the least number of cubes, and among those the least number of input
literals. A cube is a tuple of nonempty value masks.
"""
nout = len(on)
points = _minterms(domains)
npts = len(points)
index = {p: i for i, p in enumerate(points)}
# value masks: the points where variable i takes value v, as bit sets
vmask = [[0] * d for d in domains]
for p, i in index.items():
for var, v in enumerate(p):
vmask[var][v] |= 1 << i
on_m = [sum(1 << index[p] for p in on[j]) for j in range(nout)]
ok_m = [on_m[j] | sum(1 << index[p] for p in dc[j]) for j in range(nout)]
sub = [[sum(vmask[var][v] for v in range(d) if m >> v & 1) for m in range(1 << d)] for var, d in enumerate(domains)]
full = (1 << npts) - 1
cands = []
for cube in itertools.product(*[range(1, 1 << d) for d in domains]):
pm = full
for var, m in enumerate(cube):
pm &= sub[var][m]
outs = [j for j in range(nout) if pm & ~ok_m[j] == 0]
cover = 0
for j in outs:
cover |= (pm & on_m[j]) << (j * npts)
if cover:
cands.append((cube, frozenset(outs), cover, _literals(cube, domains)))
# Keep only terms that no other term dominates. A cube is dropped at
# once if adding one value to one variable covers at least as much,
# since that never adds a literal; the rest are compared in pairs.
by_cube = {c[0]: c[2] for c in cands}
pruned = []
for c in cands:
cube, cov = c[0], c[2]
grown = False
for var, m in enumerate(cube):
for v in range(domains[var]):
if not m >> v & 1:
bigger = cube[:var] + (m | 1 << v,) + cube[var + 1:]
if cov & ~by_cube.get(bigger, 0) == 0:
grown = True
break
if grown:
break
if not grown:
pruned.append(c)
cands = pruned
cands.sort(key=lambda c: (-bin(c[2]).count("1"), c[3]))
terms = []
for c in cands:
if not any(c[2] & ~t[2] == 0 and t[3] <= c[3] for t in terms):
terms.append(c)
need = 0
for j in range(nout):
need |= on_m[j] << (j * npts)
by_elem = {}
for i, t in enumerate(terms):
m = t[2]
while m:
low = m & -m
by_elem.setdefault(low, []).append(i)
m ^= low
order = sorted(by_elem, key=lambda e: len(by_elem[e]))
tmask = {e: sum(1 << i for i in by_elem[e]) for e in by_elem}
best = [None, (len(terms) + 1, 0)]
def lower_bound(left):
lb = 0
used = 0
for e in order:
if left & e and not used & tmask[e]:
lb += 1
used |= tmask[e]
return lb
def search(left, chosen, nlit):
if not left:
if (len(chosen), nlit) < best[1]:
best[0], best[1] = list(chosen), (len(chosen), nlit)
return
if (len(chosen) + lower_bound(left), nlit) >= best[1]:
return
e = next(e for e in order if left & e)
for i in sorted(by_elem[e], key=lambda i: (-bin(terms[i][2] & left).count("1"), terms[i][3])):
chosen.append(i)
search(left & ~terms[i][2], chosen, nlit + terms[i][3])
chosen.pop()
search(need, [], 0)
return [(terms[i][0], terms[i][1]) for i in best[0]]
def cost(cover, domains):
"""(number of cubes, number of input literals) of a cover."""
return len(cover), sum(_literals(c, domains) for c, _ in cover)
# ---------------------------------------------------------------- machines
def _bits_match(cube, bits):
return all(c == "-" or int(c) == b for c, b in zip(cube, bits))
def _lookup(fsm, bits, s):
ni, no, states, rows = fsm
for inp, ps, ns, out in rows:
if ps == s and _bits_match(inp, bits):
return ns, out
return None
def symbolic_function(fsm):
"""Domains, on and dc of the symbolic function.
Variables: the ni inputs, then the present state with len(states)
values. Outputs: one per next state (one-hot), then the no outputs.
"""
ni, no, states, rows = fsm
n = len(states)
domains = [2] * ni + [n]
on = [set() for _ in range(n + no)]
dc = [set() for _ in range(n + no)]
for p in _minterms(domains):
hit = _lookup(fsm, p[:ni], states[p[ni]])
for j in range(n + no):
if hit is None:
dc[j].add(p)
elif j < n:
if states[j] == hit[0]:
on[j].add(p)
else:
c = hit[1][j - n]
if c == "1":
on[j].add(p)
elif c == "-":
dc[j].add(p)
return domains, on, dc
def encoded_function(fsm, codes, k):
"""Domains, on and dc of the machine under codes (state -> int of k bits).
Variables: the ni inputs, then the k state bits, most significant
first. Outputs: the k next state bits, then the no outputs. Codes that
no state uses are don't cares.
"""
ni, no, states, rows = fsm
by_code = {codes[s]: s for s in states}
domains = [2] * (ni + k)
on = [set() for _ in range(k + no)]
dc = [set() for _ in range(k + no)]
for p in _minterms(domains):
code = int("".join(map(str, p[ni:])), 2) if k else 0
s = by_code.get(code)
hit = None if s is None else _lookup(fsm, p[:ni], s)
for j in range(k + no):
if hit is None:
dc[j].add(p)
elif j < k:
if codes[hit[0]] >> (k - 1 - j) & 1:
on[j].add(p)
else:
c = hit[1][j - k]
if c == "1":
on[j].add(p)
elif c == "-":
dc[j].add(p)
return domains, on, dc
def encoded_cost(fsm, codes, k):
domains, on, dc = encoded_function(fsm, codes, k)
return cost(minimize(domains, on, dc), domains)
def implements(fsm, codes, k, cover):
"""Does the two-level cover give the right next state and outputs?
It checks every input and state pair that some row specifies.
"""
ni, no, states, rows = fsm
for s in states:
for bits in itertools.product((0, 1), repeat=ni):
hit = _lookup(fsm, bits, s)
if hit is None:
continue
p = tuple(bits) + tuple(codes[s] >> (k - 1 - b) & 1 for b in range(k))
val = [0] * (k + no)
for cube, outs in cover:
if all(m >> v & 1 for m, v in zip(cube, p)):
for j in outs:
val[j] = 1
if val[:k] != [codes[hit[0]] >> (k - 1 - b) & 1 for b in range(k)]:
return False
for j, c in enumerate(hit[1]):
if c != "-" and val[k + j] != int(c):
return False
return True
_CODES = {}
def all_codes(n, k):
"""Every injective code of n states in k bits, one per class of bit permutations.
Permuting the bits of all codes permutes the state variables and the
next state outputs, so the cost does not change. Complementing a bit
can change it, so those classes stay apart.
"""
if (n, k) not in _CODES:
seen = set()
keep = []
perms = list(itertools.permutations(range(k)))
for codes in itertools.permutations(range(1 << k), n):
key = min(tuple(sum((c >> perm[b] & 1) << b for b in range(k)) for c in codes) for perm in perms)
if key not in seen:
seen.add(key)
keep.append(codes)
_CODES[(n, k)] = keep
return list(_CODES[(n, k)])
def exhaustive_best(fsm, k):
"""Return (best cost, list of cost of every class) over all codes of length k."""
ni, no, states, rows = fsm
costs = []
for codes in all_codes(len(states), k):
costs.append(encoded_cost(fsm, dict(zip(states, codes)), k))
return min(costs), costs
mustang_state_assignment.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mustang-state-assignment/. The authors are listed in prov/R8HB82.jsonl.
"""A MUSTANG-style encoder: attraction weights, then a greedy cube embedding.
The machine format is the one of fsmlogic: (ni, no, states, rows) with rows
(inp, ps, ns, out). The weights follow the two ideas of Devadas, Ma, Newton
and Sangiovanni-Vincentelli. The fanout-oriented weight pulls together
present states that go to the same next state or assert the same output;
the fanin-oriented weight pulls together next states reached from the same
present state or under the same input. The exact weight formulas of the
paper are not copied here; these are simplified forms.
"""
from itertools import combinations
def fanout_weights(fsm, k):
"""w(s, t) = k * sum_u a(s, u) a(t, u) + sum_j b(s, j) b(t, j).
a(s, u) counts the rows from s to u, and b(s, j) counts the rows of s
that assert output j. A shared next state counts k times because its
whole code is shared.
"""
ni, no, states, rows = fsm
a = {s: {} for s in states}
b = {s: [0] * no for s in states}
for inp, ps, ns, out in rows:
a[ps][ns] = a[ps].get(ns, 0) + 1
for j, c in enumerate(out):
if c == "1":
b[ps][j] += 1
w = {}
for s, t in combinations(states, 2):
x = k * sum(a[s][u] * a[t].get(u, 0) for u in a[s])
x += sum(b[s][j] * b[t][j] for j in range(no))
w[(s, t)] = x
return w
def fanin_weights(fsm, k):
"""w(s, t) = k * sum_p c(p, s) c(p, t) + sum_x d(x, s) d(x, t).
c(p, s) counts the rows from p to s, and d(x, s) counts the rows with
input cube x that go to s.
"""
ni, no, states, rows = fsm
c = {p: {} for p in states}
d = {}
for inp, ps, ns, out in rows:
c[ps][ns] = c[ps].get(ns, 0) + 1
d.setdefault(inp, {})
d[inp][ns] = d[inp].get(ns, 0) + 1
w = {}
for s, t in combinations(states, 2):
x = k * sum(c[p].get(s, 0) * c[p].get(t, 0) for p in states)
x += sum(dx.get(s, 0) * dx.get(t, 0) for dx in d.values())
w[(s, t)] = x
return w
def pair_weight(w, s, t):
return w.get((s, t), w.get((t, s), 0))
def embedding_cost(w, codes):
"""sum over pairs of w(s, t) times the Hamming distance of their codes."""
return sum(x * bin(codes[s] ^ codes[t]).count("1") for (s, t), x in w.items())
def greedy_embed(states, w, k):
"""Place the states one by one on the corners of the k-cube.
The next state to place is the one with the largest total weight to
the placed states (the largest total weight overall to start). It goes
to the free corner with the least weighted distance to the placed
states. Ties go to the earlier state and the smaller code.
"""
total = {s: sum(pair_weight(w, s, t) for t in states if t != s) for s in states}
codes = {} # @line L4
left = list(states)
while left: # @line L5
if codes:
s = max(left, key=lambda s: (sum(pair_weight(w, s, t) for t in codes), total[s], -states.index(s))) # @line L6
else:
s = max(left, key=lambda s: (total[s], -states.index(s)))
used = set(codes.values())
best = min( # @line L7
(c for c in range(1 << k) if c not in used),
key=lambda c: (sum(pair_weight(w, s, t) * bin(c ^ codes[t]).count("1") for t in codes), c),
)
codes[s] = best
left.remove(s)
return codes # @line L8
def mustang_encode(fsm, mode="fanout", k=None):
"""Return (k, codes) for mode "fanout" or "fanin"."""
ni, no, states, rows = fsm
if k is None:
k = max(1, (len(states) - 1).bit_length()) # @line L1
w = fanout_weights(fsm, k) if mode == "fanout" else fanin_weights(fsm, k) # @line L2 L3
return k, greedy_embed(states, w, k)
test_mustang_state_assignment.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mustang-state-assignment/. The authors are listed in prov/R8HB82.jsonl.
import itertools
import random
from fsmlogic import encoded_cost, encoded_function, exhaustive_best, implements, minimize
from mustang_state_assignment import embedding_cost, fanin_weights, fanout_weights, greedy_embed, mustang_encode
# The machine of the page (the same one as on the KISS page).
M1 = (1, 1, ["s0", "s1", "s2", "s3"], [
("0", "s0", "s2", "1"), ("1", "s0", "s2", "0"),
("0", "s1", "s2", "0"), ("1", "s1", "s2", "1"),
("0", "s2", "s3", "0"), ("1", "s2", "s1", "1"),
("0", "s3", "s1", "1"), ("1", "s3", "s3", "0"),
])
def random_fsm(rng: random.Random, n, ni, no):
states = [f"s{i}" for i in range(n)]
rows = []
for s in states:
for x in range(1 << ni):
rows.append((format(x, f"0{ni}b"), s, rng.choice(states), "".join(rng.choice("01") for _ in range(no))))
return (ni, no, states, rows)
def best_embedding(states, w, k):
"""Brute force: the least weighted Hamming cost over all injective codes."""
return min(embedding_cost(w, dict(zip(states, cs))) for cs in itertools.permutations(range(1 << k), len(states)))
def test_page_example():
states = M1[2]
wo = fanout_weights(M1, 2)
assert wo == {("s0", "s1"): 9, ("s0", "s2"): 1, ("s0", "s3"): 1, ("s1", "s2"): 1, ("s1", "s3"): 1, ("s2", "s3"): 5}
k, co = mustang_encode(M1, "fanout")
assert co == {"s0": 0, "s1": 1, "s2": 2, "s3": 3}
assert embedding_cost(wo, co) == best_embedding(states, wo, 2) == 20
assert encoded_cost(M1, co, 2) == (7, 19)
wi = fanin_weights(M1, 2)
assert wi == {("s0", "s1"): 0, ("s0", "s2"): 0, ("s0", "s3"): 0, ("s1", "s2"): 4, ("s1", "s3"): 6, ("s2", "s3"): 4}
k, ci = mustang_encode(M1, "fanin")
assert ci == {"s1": 0, "s3": 1, "s2": 2, "s0": 3}
assert embedding_cost(wi, ci) == best_embedding(states, wi, 2) == 18
assert encoded_cost(M1, ci, 2) == (6, 14)
assert exhaustive_best(M1, 2)[0] == (4, 8)
def test_random_machines():
rng = random.Random(1988)
emb_opt = {"fanout": 0, "fanin": 0}
hits = {"fanout": 0, "fanin": 0, "both": 0}
excess = {"fanout": 0, "fanin": 0, "both": 0}
worst = 0
for _ in range(100):
fsm = random_fsm(rng, 4, 1, 1)
states = fsm[2]
best = exhaustive_best(fsm, 2)[0][0]
got = {}
for mode in ("fanout", "fanin"):
k, codes = mustang_encode(fsm, mode)
assert k == 2 and len(set(codes.values())) == 4
w = fanout_weights(fsm, k) if mode == "fanout" else fanin_weights(fsm, k)
e, b = embedding_cost(w, codes), best_embedding(states, w, k)
assert e >= b
emb_opt[mode] += e == b
domains, on, dc = encoded_function(fsm, codes, k)
exact = minimize(domains, on, dc)
assert implements(fsm, codes, k, exact)
got[mode] = len(exact)
got["both"] = min(got.values())
for key, g in got.items():
assert g >= best
hits[key] += g == best
excess[key] += g - best
worst = max(worst, got["both"] - best)
assert (emb_opt, hits, excess, worst) == MEASURED
# 100 machines: the greedy embedding reaches the least weighted distance on
# 84 (fanout) and 87 (fanin) machines; the final logic meets the best 2-bit
# code on 33, 47 and 57 machines (fanout, fanin, better of the two), with
# 87, 68 and 47 extra cubes in total; the better of the two loses at most 2.
MEASURED = (
{"fanout": 84, "fanin": 87},
{"fanout": 33, "fanin": 47, "both": 57},
{"fanout": 87, "fanin": 68, "both": 47},
2,
)
def test_greedy_embedding_on_five_states():
rng = random.Random(7)
opt = 0
for _ in range(8):
states = [f"s{i}" for i in range(5)]
w = {(s, t): rng.randint(0, 6) for s, t in itertools.combinations(states, 2)}
codes = greedy_embed(states, w, 3)
assert len(set(codes.values())) == 5
e, b = embedding_cost(w, codes), best_embedding(states, w, 3)
assert e >= b
opt += e == b
assert opt == MEASURED_FIVE
# 8 random weight sets on 5 states in 3 bits: the greedy is optimal on 6.
MEASURED_FIVE = 6
History
De Micheli, Brayton and Sangiovanni-Vincentelli (1985) gave KISS for two-level logic. Devadas, Ma, Newton and Sangiovanni-Vincentelli (1988) gave MUSTANG for multilevel logic, with fanout and fanin oriented weight graphs and an embedding into the code cube, and reported literal counts after multilevel optimization on a set of benchmark machines, a measurement rather than a bound. Villa and Sangiovanni-Vincentelli (1990) returned to the two-level case with NOVA. De Micheli's 1994 textbook surveys the two-level and multilevel encoders together.
References
- Srinivas Devadas, Hi-Keung Tony Ma, A. Richard Newton and Alberto L. Sangiovanni-Vincentelli, MUSTANG, state assignment of finite state machines targeting multilevel logic implementations, IEEE Transactions on Computer-Aided Design 7(12), 1290 to 1300, 1988, the fanout and fanin oriented weight graphs, the embedding algorithm, and the literal counts measured on benchmark machines
- Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 9 (state encoding for multiple-level circuits)
- Giovanni De Micheli, Robert K. Brayton and Alberto L. Sangiovanni-Vincentelli, Optimal state assignment for finite state machines, IEEE Transactions on Computer-Aided Design CAD-4(3), 269 to 285, 1985, the two-level encoding method (KISS) that MUSTANG compares with
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 R8HB82 Edit this page History Report an error Markdown