Algorithm Search⌘K

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 JJ consecutive samples per iteration. Each node UU becomes JJ copies U0,…,UJ−1U_0, \ldots, U_{J-1}, where copy UiU_i computes what UU computed for sample Jk+iJk + i, and each edge with ww delays becomes JJ edges whose delays add up to ww again. The new graph is a parallel design: it takes JJ inputs and gives JJ 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 w(e)w(e) delays, and every cycle has a delay.
  • The iteration bound T∞T_\infty 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 JJ with JT∞J T_\infty an integer removes the rounding.
  • The design must take several samples per clock: a block of JJ parallel inputs, as in a parallel filter that runs at a clock JJ 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 GG with nodes VV, edges (U,V,w)(U, V, w) and the factor J≥1J \ge 1. A host node XX that reads the input sample x(k)x(k) in iteration kk is treated like any other node; its copy XiX_i reads x(Jk+i)x(Jk + i).

  1. UNFOLD(G, J)
  2. 1for each node U of G and each i in 0, ..., J − 1: make the node U_i
  3. 2for each edge U → V of G with w delays, in the order of the input slots of V, do
  4. 3for i ← 0 to J − 1 do
  5. 4j ← (i + w) mod J
  6. 5add the edge U_i → V_j with ⌊(i + w) / J⌋ delays
  7. 6give each host copy X_i the input x(Jk + i) and each output copy Y_i the output y(Jk + i)
  8. 7return the new graph G_J

The holes are the factor JJ 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 GJG_J 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 UiU_i in iteration kk of GJG_J compute UU in iteration Jk+iJk + i of GG. In GG, iteration nn of VV reads iteration n−wn - w of UU. Take n=Jk+jn = Jk + j and let ii be the copy of UU that holds iteration n−wn - w, so i≡j−w(modJ)i \equiv j - w \pmod J, that is j=(i+w) mod Jj = (i + w) \bmod J. Write i+w=J⌊(i+w)/J⌋+ji + w = J \lfloor (i + w) / J \rfloor + j. Then

n−w=Jk+j−w=J(k−⌊i+wJ⌋)+i,n - w = Jk + j - w = J\left(k - \left\lfloor \frac{i + w}{J} \right\rfloor\right) + i,

which is iteration k−⌊(i+w)/J⌋k - \lfloor (i + w) / J \rfloor of UiU_i. So VjV_j must read UiU_i through exactly ⌊(i+w)/J⌋\lfloor (i + w)/J \rfloor delays, which is L5. For each jj there is exactly one ii, so each copy VjV_j gets exactly one copy of each input edge of VV, 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 w=aJ+rw = aJ + r with 0≤r<J0 \le r < J. Then ⌊(i+w)/J⌋\lfloor (i + w)/J \rfloor is aa for the J−rJ - r values i<J−ri < J - r and a+1a + 1 for the other rr values, so the JJ new edges carry Ja+r=wJ a + r = w delays in total. This is the case x=w/Jx = w / J of Hermite's identity ∑i=0J−1⌊x+i/J⌋=⌊Jx⌋\sum_{i=0}^{J-1} \lfloor x + i/J \rfloor = \lfloor J x \rfloor. So GJG_J has J∣V∣J |V| nodes, J∣E∣J |E| edges and the same total number of delays as GG. An edge with w<Jw < J delays has J−wJ - w copies with no delay and ww copies with one delay, and an edge with w≥Jw \ge J has at least one delay on every copy.

The iteration bound grows by exactly JJ. Follow a cycle C′C' of GJG_J. Each edge moves the copy index from ii to (i+w) mod J(i + w) \bmod J and carries ⌊(i+w)/J⌋=(i+w−j)/J\lfloor (i + w)/J \rfloor = (i + w - j)/J delays. Around a closed cycle the terms ii and jj cancel, so w(C′)=w(W)/Jw(C') = w(W)/J, where WW is the closed walk of GG under C′C', and t(C′)=t(W)t(C') = t(W). So t(C′)/w(C′)=J t(W)/w(W)≤JT∞t(C')/w(C') = J \, t(W)/w(W) \le J T_\infty, since a closed walk has no larger ratio than the best cycle. Conversely, lift a cycle CC of GG with w(C)w(C) delays from copy ii: after one turn the index is (i+w(C)) mod J(i + w(C)) \bmod J, and after m=J/gcd⁡(J,w(C))m = J / \gcd(J, w(C)) turns it is back at ii. The lift is a cycle C′C' with t(C′)=m t(C)t(C') = m \, t(C) and w(C′)=m w(C)/Jw(C') = m \, w(C) / J, so its ratio is J t(C)/w(C)J \, t(C) / w(C). Hence

T∞(GJ)=J⋅T∞(G).T_\infty(G_J) = J \cdot T_\infty(G).

An iteration of GJG_J handles JJ samples, so the bound per sample is unchanged: unfolding never makes the bound worse and never makes it better. What it changes is that JT∞J T_\infty can be an integer when T∞T_\infty is not.

Unfolding twice. Unfolding by aa and then by bb gives the same graph as unfolding by abab, up to the names of the copies: copy mm of copy ii is copy i+ami + a m.

Classic examples

A recursive filter with a fractional bound. Take y(n)=x(n)+3y(n−2)+5y(n−3)y(n) = x(n) + 3 y(n - 2) + 5 y(n - 3) with an adder AA of time 1 and multipliers BB (by 3) and CC (by 5) of time 2. The edges are X→AX \to A (0 delays), A→BA \to B (0), B→AB \to A (2), A→CA \to C (1) and C→AC \to A (2). The loops have ratios 3/23/2 and 3/33/3, so T∞=3/2T_\infty = 3/2. The critical path is X→A→BX \to A \to B, of time 3, and retiming brings the clock period down to 2, not to 1.5. Unfolding by J=2J = 2 gives these edges:

edge of GG ww copy i=0i = 0 copy i=1i = 1
X→AX \to A 0 X0→A0X_0 \to A_0, 0 X1→A1X_1 \to A_1, 0
A→BA \to B 0 A0→B0A_0 \to B_0, 0 A1→B1A_1 \to B_1, 0
B→AB \to A 2 B0→A0B_0 \to A_0, 1 B1→A1B_1 \to A_1, 1
A→CA \to C 1 A0→C1A_0 \to C_1, 0 A1→C0A_1 \to C_0, 1
C→AC \to A 2 C0→A0C_0 \to A_0, 1 C1→A1C_1 \to A_1, 1

The 5 delays of GG are still 5. The loop A0→B0→A0A_0 \to B_0 \to A_0 has time 3 and 1 delay, and the loop A0→C1→A1→C0→A0A_0 \to C_1 \to A_1 \to C_0 \to A_0 has time 6 and 3 delays, so T∞(G2)=3=2⋅3/2T_\infty(G_2) = 3 = 2 \cdot 3/2. The longest path with no delay is 3 (Xi→Ai→BiX_i \to A_i \to B_i, or A0→C1A_0 \to C_1), 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 JJ gives a block filter with JJ inputs and JJ outputs per clock and JJ 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 CC this happens when w(C)w(C) divides JJ, since the lift then has m=J/w(C)m = J / w(C) turns and w(C′)=1w(C') = 1. 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 GJG_J with no delay lies over a path of GG with at most J−1J - 1 delays, since each edge it uses has i+w<Ji + w < J. So the critical path of GJG_J is the longest such path of GG, and a retiming of GJG_J is usually needed to bring it down to JT∞J T_\infty. 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 GJG_J by a factor NN gives hardware that takes JJ samples every NN clock cycles, so the ratio J/NJ / N sets the throughput and NN sets how many operations share a unit.
  • Multirate graphs. In a synchronous dataflow graph the analogue of unfolding is the expansion with qaq_a copies of actor aa, which makes one period of the multirate graph into one iteration of a homogeneous graph.
  • Look-ahead pipelining. Rewriting a recursion, such as y(n)=ay(n−1)+x(n)y(n) = a y(n-1) + x(n) into y(n)=a2y(n−2)+ax(n−1)+x(n)y(n) = a^2 y(n-2) + a x(n-1) + x(n), changes the algorithm and so the iteration bound. Unfolding never does that.

Pitfalls

  • Wrong copy index. The edge goes from UiU_i to V(i+w) mod JV_{(i + w) \bmod J}, not to V(i−w) mod JV_{(i - w) \bmod J}. With the wrong sign the copy reads a future sample.
  • Ceiling instead of floor. The delay count is ⌊(i+w)/J⌋\lfloor (i + w)/J \rfloor. With a ceiling the delays no longer add up to ww 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 JJ times. A path of GG with fewer than JJ delays can even turn into a longer delay-free path of GJG_J through several copies. The gain is per sample, and usually needs a retiming of GJG_J.
  • A node slower than the target. A node is never split, so the clock period of GJG_J is at least the largest node time tmax⁡t_{\max}. If tmax⁡>JT∞t_{\max} > J T_\infty, the clock cannot be JT∞J T_\infty, and only a larger JJ or a pipelined node helps.
  • Cost. GJG_J has JJ times the units. Unfolding by more than the least JJ that makes JT∞J T_\infty 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.

dsp_unfolding.pyI0RawGitHub
# 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

  1. Unfold the filter of the example by J=3J = 3. List the edges and check that the delays still add up to 5 and that T∞(G3)=9/2T_\infty(G_3) = 9/2.
  2. Show that if every edge of GG has w(e)≥Jw(e) \ge J delays, then every edge of GJG_J has at least one delay.
  3. Show that the unfolded graph of a strongly connected graph need not be strongly connected. Hint: take one cycle with 2 delays and J=2J = 2.
  4. Prove that unfolding by aa and then by bb gives the graph of unfolding by abab, with copy mm of UiU_i named Ui+amU_{i + am}.

References

  1. 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
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples