Techniqueadvanced
Unfolding transformation
Also called loop unfolding of data flow graphs, Parhi-Messerschmitt unfolding.
Parhi and Messerschmitt's transformation that copies a data flow graph J times with redistributed delays so one iteration processes J samples, reaching the iteration bound.
Unfolding turns a data flow graph that handles one sample per iteration into an equivalent graph that handles consecutive samples per iteration. Each node becomes copies , where copy computes what computed for sample , and each edge with delays becomes edges whose delays add up to again. The new graph is a parallel design: it takes inputs and gives outputs per clock. Parhi and Messerschmitt (1991) used it to reach the iteration bound with a clocked circuit when the bound is not an integer, which retiming alone cannot do. It is the hardware form of loop unrolling for loops that carry values from one iteration to the next.
In plain words
Suppose a machine makes one cake per hour, and the slowest part of the recipe is a chain of steps that takes an hour and a half but only has to be redone every second cake. One machine cannot use that slack, because its clock ticks once per cake. Build two machines side by side, one for the even cakes and one for the odd cakes, and let each pass its half-finished batter to the other. Now one tick of 3 hours makes two cakes, so each cake costs an hour and a half, which is the true limit. Unfolding is this trick for a filter: copy the circuit, and rewire each delay so that every copy reads its past values from the right copy.
When it applies
- The graph is a data flow graph in the sense of the iteration bound page: nodes run once per iteration, edges carry delays, and every cycle has a delay.
- The iteration bound is not an integer number of clock cycles, so a clocked one-sample-per-cycle design wastes time on the critical loop. Unfolding by a with an integer removes the rounding.
- The design must take several samples per clock: a block of parallel inputs, as in a parallel filter that runs at a clock times slower than the sample rate.
- A bit-serial design should become digit-serial, or a word-level design should process several words at once.
The template
The input is a graph with nodes , edges and the factor . A host node that reads the input sample in iteration is treated like any other node; its copy reads .
UNFOLD(G, J)- 1
for each node U of G and each i in 0, ..., J − 1: make the node U_i - 2
for each edge U → V of G with w delays, in the order of the input slots of V, do - 3
for i ← 0 to J − 1 do - 4
j ← (i + w) mod J - 5
add the edge U_i → V_j with ⌊(i + w) / J⌋ delays - 6
give each host copy X_i the input x(Jk + i) and each output copy Y_i the output y(Jk + i) - 7
return the new graph G_J
The holes are the factor of L1, the conversion of L6 (a serial-to-parallel converter at the input and a parallel-to-serial converter at the output), and what is done with afterwards: usually a retiming to a clock period equal to its iteration bound, or a folding onto fewer units.
Why L4 and L5 are right. Let copy in iteration of compute in iteration of . In , iteration of reads iteration of . Take and let be the copy of that holds iteration , so , that is . Write . Then
which is iteration of . So must read through exactly delays, which is L5. For each there is exactly one , so each copy gets exactly one copy of each input edge of , and keeping the order of L2 keeps the input slots of non-commutative nodes in order. By induction on the iterations, and inside one iteration on the edges with no delay, every copy computes the value claimed. The delays that start at zero stand for samples before time 0 in both graphs.
Delays are kept. Write with . Then is for the values and for the other values, so the new edges carry delays in total. This is the case of Hermite's identity . So has nodes, edges and the same total number of delays as . An edge with delays has copies with no delay and copies with one delay, and an edge with has at least one delay on every copy.
The iteration bound grows by exactly . Follow a cycle of . Each edge moves the copy index from to and carries delays. Around a closed cycle the terms and cancel, so , where is the closed walk of under , and . So , since a closed walk has no larger ratio than the best cycle. Conversely, lift a cycle of with delays from copy : after one turn the index is , and after turns it is back at . The lift is a cycle with and , so its ratio is . Hence
An iteration of handles samples, so the bound per sample is unchanged: unfolding never makes the bound worse and never makes it better. What it changes is that can be an integer when is not.
Unfolding twice. Unfolding by and then by gives the same graph as unfolding by , up to the names of the copies: copy of copy is copy .
Classic examples
A recursive filter with a fractional bound. Take with an adder of time 1 and multipliers (by 3) and (by 5) of time 2. The edges are (0 delays), (0), (2), (1) and (2). The loops have ratios and , so . The critical path is , of time 3, and retiming brings the clock period down to 2, not to 1.5. Unfolding by gives these edges:
| edge of | copy | copy | |
|---|---|---|---|
| 0 | , 0 | , 0 | |
| 0 | , 0 | , 0 | |
| 2 | , 1 | , 1 | |
| 1 | , 0 | , 1 | |
| 2 | , 1 | , 1 |
The 5 delays of are still 5. The loop has time 3 and 1 delay, and the loop has time 6 and 3 delays, so . The longest path with no delay is 3 (, or ), so the unfolded circuit runs with a clock period of 3 and takes 2 samples per clock: 1.5 time units per sample, the iteration bound, with no retiming at all.
Parallel FIR filters. A FIR filter has no loop, so its iteration bound is 0 and unfolding is used only for throughput: unfolding by gives a block filter with inputs and outputs per clock and times the multipliers. Each delay of the tapped line is shared out among the copies by L5.
Rate-optimal schedules. Parhi and Messerschmitt unfold by a factor that makes the graph perfect rate, in which every loop of the unfolded graph has one delay. For a single loop this happens when divides , since the lift then has turns and . Such a graph can be scheduled to reach its iteration bound, so the original program runs at its bound per sample.
Compilers. Loop unrolling of a loop with a recurrence is the same operation on a program, and software pipelining and SDC modulo scheduling meet the same bound in a different way: they overlap iterations instead of copying them, which needs a fractional initiation interval or unrolling when the recurrence bound is not an integer.
Variations
- Unfolding and retiming. A path of with no delay lies over a path of with at most delays, since each edge it uses has . So the critical path of is the longest such path of , and a retiming of is usually needed to bring it down to . Parhi's book (Chapter 5.4) treats how the two steps combine. On the example above, unfolding alone already reaches the bound.
- Unfolding and folding. The two transformations compose: folding by a factor gives hardware that takes samples every clock cycles, so the ratio sets the throughput and sets how many operations share a unit.
- Multirate graphs. In a synchronous dataflow graph the analogue of unfolding is the expansion with copies of actor , which makes one period of the multirate graph into one iteration of a homogeneous graph.
- Look-ahead pipelining. Rewriting a recursion, such as into , changes the algorithm and so the iteration bound. Unfolding never does that.
Pitfalls
- Wrong copy index. The edge goes from to , not to . With the wrong sign the copy reads a future sample.
- Ceiling instead of floor. The delay count is . With a ceiling the delays no longer add up to and the copies read samples from the wrong iteration.
- Expecting a shorter critical path. Unfolding does not shorten the longest path with no delay; it copies it times. A path of with fewer than delays can even turn into a longer delay-free path of through several copies. The gain is per sample, and usually needs a retiming of .
- A node slower than the target. A node is never split, so the clock period of is at least the largest node time . If , the clock cannot be , and only a larger or a pipelined node helps.
- Cost. has times the units. Unfolding by more than the least that makes an integer buys no speed per sample.
Code
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/dsp-unfolding/. The authors are listed in prov/SNB59C.jsonl.
"""Unfolding transformation of a data flow graph (Parhi and Messerschmitt).
A graph has nodes with a kind: "in" (the host, which emits a sample of x
in each iteration), "add" (sum of the inputs) or "mul" (a constant times
the product of the inputs). Arithmetic is modulo MOD, and every node maps
all zero inputs to zero, so delays that start at zero stand for samples
before time 0. Edges are (u, v, w) with w >= 0 delays, and every cycle has
at least one delay. A host node may carry a phase i and a factor J; it then
emits x(J k + i) in iteration k. A plain host has phase 0 and factor 1.
"""
MOD = 1_000_003
def node_value(kind, coef, inputs):
if kind == "add":
return sum(inputs) % MOD
prod = coef
for a in inputs:
prod = prod * a % MOD
return prod
def topo_zero_delay(nodes, edges):
indeg = {v: 0 for v in nodes}
for u, v, w in edges:
if w == 0:
indeg[v] += 1
order = [v for v in nodes if indeg[v] == 0]
for v in order:
for a, b, w in edges:
if a == v and w == 0:
indeg[b] -= 1
if indeg[b] == 0:
order.append(b)
if len(order) != len(nodes):
raise ValueError("a cycle with no delay")
return order
def simulate(graph, x, iterations):
"""Run the graph for the given number of iterations; return all values."""
nodes, edges, kind, coef = graph["nodes"], graph["edges"], graph["kind"], graph["coef"]
phase = graph.get("phase", {})
order = topo_zero_delay(nodes, edges)
ins_of = {v: [(u, w) for (u, b, w) in edges if b == v] for v in nodes}
val = {v: [] for v in nodes}
for k in range(iterations):
for v in order:
if kind[v] == "in":
i, J = phase.get(v, (0, 1))
n = J * k + i
val[v].append(x[n] % MOD if n < len(x) else 0)
continue
ins = [val[u][k - w] if k - w >= 0 else 0 for (u, w) in ins_of[v]]
val[v].append(node_value(kind[v], coef.get(v, 1), ins))
return val
def unfold(graph, J):
"""The J-unfolded graph.
Node U becomes U_0, ..., U_{J-1}, where U_i in iteration k computes U
in iteration J k + i. Edge U -> V with w delays becomes, for each i,
the edge U_i -> V_{(i + w) mod J} with floor((i + w) / J) delays. The
edges keep the order of the input slots of each node.
"""
if J < 1:
raise ValueError("J must be at least 1")
nodes, edges, kind, coef = graph["nodes"], graph["edges"], graph["kind"], graph["coef"]
name = lambda v, i: f"{v}_{i}"
new_nodes = [name(v, i) for v in nodes for i in range(J)] # @line L1
# Each edge into V gives exactly one edge into each copy V_j, and the
# copies list them in the order of the original edges, so the input
# slots of every node keep their order.
new_edges = []
for u, v, w in edges: # @line L2
for i in range(J): # @line L3
new_edges.append((name(u, i), name(v, (i + w) % J), (i + w) // J)) # @line L4 L5
new_kind = {name(v, i): kind[v] for v in nodes for i in range(J)}
new_coef = {name(v, i): coef[v] for v in nodes for i in range(J) if v in coef}
new_phase = {}
for v in nodes: # @line L6
if kind[v] == "in":
p, K = graph.get("phase", {}).get(v, (0, 1))
for i in range(J):
new_phase[name(v, i)] = (K * i + p, K * J)
return {"nodes": new_nodes, "edges": new_edges, "kind": new_kind, "coef": new_coef, "phase": new_phase} # @line L7
test_dsp_unfolding.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dsp-unfolding/. The authors are listed in prov/SNB59C.jsonl.
import random
from fractions import Fraction
from dsp_unfolding import simulate, unfold
# y(n) = x(n) + 3 y(n - 2) + 5 y(n - 3), the example of the page.
IIR = {
"nodes": ["X", "A", "B", "C"],
"edges": [("X", "A", 0), ("A", "B", 0), ("B", "A", 2), ("A", "C", 1), ("C", "A", 2)],
"kind": {"X": "in", "A": "add", "B": "mul", "C": "mul"},
"coef": {"B": 3, "C": 5},
}
IIR_TIME = {"X": 0, "A": 1, "B": 2, "C": 2}
def max_cycle_ratio(graph, time):
"""Brute force: the largest t(C) / w(C) over all simple cycles."""
nodes, edges = graph["nodes"], graph["edges"]
pos = {v: i for i, v in enumerate(nodes)}
best = Fraction(0)
def walk(s, v, t, w, seen):
nonlocal best
for a, b, d in edges:
if a != v:
continue
if b == s:
assert w + d > 0
best = max(best, Fraction(t, w + d))
elif b not in seen and pos[b] > pos[s]:
walk(s, b, t + time[b], w + d, seen | {b})
for s in nodes:
walk(s, s, time[s], 0, {s})
return best
def critical_path(graph, time):
memo = {}
def longest(v):
if v not in memo:
memo[v] = time[v] + max([longest(a) for a, b, w in graph["edges"] if b == v and w == 0], default=0)
return memo[v]
return max(longest(v) for v in graph["nodes"])
def copy_time(time, J):
return {f"{v}_{i}": t for v, t in time.items() for i in range(J)}
def random_graph(rng: random.Random):
n = rng.randint(2, 4)
ops = [f"v{i}" for i in range(n)]
nodes = ["X"] + ops
edges = []
for i, v in enumerate(ops):
edges.append((rng.choice(nodes[: i + 1]), v, rng.randint(0, 2)))
for _ in range(rng.randint(1, 3)):
a, b = rng.randrange(n), rng.randrange(n)
w = rng.randint(1, 4) if a >= b else rng.randint(0, 2)
edges.append((ops[a], ops[b], w))
kind = {"X": "in"}
coef = {}
for v in ops:
kind[v] = rng.choice(["add", "mul"])
coef[v] = rng.randint(1, 9)
time = {"X": 0}
time.update({v: rng.randint(1, 3) for v in ops})
return {"nodes": nodes, "edges": edges, "kind": kind, "coef": coef}, time, rng.choice(ops)
def same_outputs(g, J, out, x):
u = unfold(g, J)
L = len(x)
ref = simulate(g, x, L)[out]
got = simulate(u, x, -(-L // J))
for n in range(L):
assert got[f"{out}_{n % J}"][n // J] == ref[n]
def test_iir_example():
u = unfold(IIR, 2)
assert u["edges"] == [
("X_0", "A_0", 0), ("X_1", "A_1", 0), ("A_0", "B_0", 0), ("A_1", "B_1", 0),
("B_0", "A_0", 1), ("B_1", "A_1", 1), ("A_0", "C_1", 0), ("A_1", "C_0", 1),
("C_0", "A_0", 1), ("C_1", "A_1", 1),
]
assert max_cycle_ratio(IIR, IIR_TIME) == Fraction(3, 2)
assert critical_path(IIR, IIR_TIME) == 3
assert max_cycle_ratio(u, copy_time(IIR_TIME, 2)) == 3
assert critical_path(u, copy_time(IIR_TIME, 2)) == 3
same_outputs(IIR, 2, "A", [(7 * i + 1) % 50 for i in range(40)])
def test_random_graphs():
rng = random.Random(4242)
for _ in range(150):
g, time, out = random_graph(rng)
J = rng.randint(1, 4)
u = unfold(g, J)
assert len(u["edges"]) == J * len(g["edges"])
assert sum(w for _, _, w in u["edges"]) == sum(w for _, _, w in g["edges"])
if J <= 3:
assert max_cycle_ratio(u, copy_time(time, J)) == J * max_cycle_ratio(g, time)
same_outputs(g, J, out, [rng.randrange(1000) for _ in range(30)])
def test_unfolding_twice_is_unfolding_by_the_product():
rng = random.Random(77)
for _ in range(40):
g, time, out = random_graph(rng)
a, b = rng.randint(1, 3), rng.randint(1, 3)
x = [rng.randrange(1000) for _ in range(36)]
twice = unfold(unfold(g, a), b)
once = unfold(g, a * b)
assert sum(w for _, _, w in twice["edges"]) == sum(w for _, _, w in once["edges"])
L = len(x)
ref = simulate(g, x, L)[out]
got = simulate(twice, x, -(-L // (a * b)))
for n in range(L):
k, j = divmod(n, a * b)
i, m = j % a, j // a
# copy i of the first unfolding, then copy m of the second
assert got[f"{out}_{i}_{m}"][k] == ref[n]
Exercises
- Unfold the filter of the example by . List the edges and check that the delays still add up to 5 and that .
- Show that if every edge of has delays, then every edge of has at least one delay.
- Show that the unfolded graph of a strongly connected graph need not be strongly connected. Hint: take one cycle with 2 delays and .
- Prove that unfolding by and then by gives the graph of unfolding by , with copy of named .
References
- Keshab K. Parhi and David G. Messerschmitt, Static rate-optimal scheduling of iterative data-flow programs via optimum unfolding, IEEE Transactions on Computers 40(2), 1991, the unfolding of a data flow graph, perfect-rate graphs, and rate-optimal schedules after unfolding by the optimum factor
- Keshab K. Parhi, VLSI Digital Signal Processing Systems, Design and Implementation, Wiley, 1999, Chapter 5 (5.2 an algorithm for unfolding, 5.3 properties of unfolding, 5.4 critical path, unfolding and retiming, 5.5 applications)
- Markku Renfors and Yrjö Neuvo, The maximum sampling rate of digital filters under hardware speed constraints, IEEE Transactions on Circuits and Systems CAS-28(3), 196 to 202, 1981, the iteration bound that unfolding lets a clocked design reach
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SNB59C Edit this page History Report an error Markdown