Algorithm Search⌘K

Techniqueadvanced

Folding transformation

Also called Parhi folding, time-multiplexing transformation.

Maps several operations of a data flow graph onto one hardware unit by time multiplexing and computes the registers each folded edge needs from a folding equation.

Folding is the opposite of unfolding: it runs several operations of a data flow graph on one hardware unit, one after another, so that a design needs fewer adders and multipliers at the price of a faster clock. With folding factor NN, every unit repeats a cycle of NN clock steps, and in each step it runs the operation that the folding set puts there. The folded circuit needs registers to hold each result from the step in which it leaves its unit to the step in which its consumer runs, and switches that route the right value into each unit input at the right step. The folding equation gives the number of registers of each edge in closed form, and when some count comes out negative, a retiming found from a system of difference constraints repairs it or proves that no retiming can. The method is due to Parhi and his students, and Parhi's 1999 textbook gives it in the form used here.

In plain words

A kitchen has one oven but a recipe with three baking steps per batch. The cook bakes the three steps in a fixed rotation, one per hour, so a batch comes out every three hours. Something baked in the first hour may be needed only in the third, so it sits on a shelf in between. Folding works out, for each step of the recipe, how many hours its result must sit on the shelf. If the answer is negative, the result would be needed before it is ready; then some old results are moved around the recipe, without changing what the recipe makes, until every wait is zero or more.

When it applies

  • The graph is a data flow graph as on the iteration bound page, such as a digital filter, and its sample rate is much lower than the clock rate the hardware can reach. Then NN operations can share a unit.
  • The operations come in a few types (adds, multiplies), so a few units can serve many operations.
  • A schedule and binding are given or can be chosen: the folding set, which gives each operation a unit and a step in {0,…,N−1}\{0, \ldots, N - 1\}. This is a modulo schedule with initiation interval NN, written in the language of signal processing.
  • The units may be pipelined: a unit HH with PHP_H stages gives its result PHP_H steps after it starts, and can start a new operation every step.

The template

The input is a data flow graph with edges e=(U,V)e = (U, V) carrying w(e)w(e) delays, the folding factor NN, and a folding set: each operation UU gets a unit HUH_U and a folding order u∈{0,…,N−1}u \in \{0, \ldots, N - 1\}, written in lower case, with no two operations on one unit sharing an order. Iteration ll of UU then runs in clock step Nl+uNl + u on HUH_U, and its result is ready at step Nl+u+PHUNl + u + P_{H_U}, written PUP_U for short.

  1. FOLD(G, N, H, order, P)
  2. 1for each edge e = U → V do D_F(e) ← N · w(e) − P_U + v − u
  3. 2if some D_F(e) < 0 then
  4. 3solve r(U) − r(V) ≤ ⌊D_F(e) / N⌋ for every edge e = U → V, with r ≥ 0
  5. 4if there is no solution then fail: no retiming makes this folding set work
  6. 5for each edge e = U → V do w(e) ← w(e) + r(V) − r(U); recompute D_F(e) by L1
  7. 6for each edge e = U → V do
  8. 7wire the output of H_U through a chain of D_F(e) registers to an input switch of H_V
  9. 8close that switch in the steps Nl + v, l = 0, 1, 2, ...
  10. 9return the folded circuit

The holes are the factor NN, the folding set (which unit and which step for each operation), the pipelining PP of each unit, and the register sharing done after L7 (below, under variations). Line L3 is solved like any system of difference constraints: read each row as r(V)≥r(U)−⌊DF(e)/N⌋r(V) \ge r(U) - \lfloor D_F(e)/N \rfloor, start from r=0r = 0, and raise values as in Bellman-Ford for longest paths until no row is violated. This gives the least solution with r≥0r \ge 0, and if values still rise after ∣V∣|V| passes, a cycle makes the system infeasible. The input node has no incoming edge, so it keeps r=0r = 0.

The folding equation. Iteration ll of UU is ready at step Nl+u+PUNl + u + P_U. Edge ee says that iteration l+w(e)l + w(e) of VV uses it, and that iteration runs at step N(l+w(e))+vN(l + w(e)) + v. The value must wait between the two steps, so it needs

DF(U→V)=N(l+w(e))+v−(Nl+u+PU)=Nw(e)−PU+v−uD_F(U \to V) = N(l + w(e)) + v - (Nl + u + P_U) = N w(e) - P_U + v - u

registers, the same for every ll. A negative count means that VV would need the value before UU has made it.

The retiming condition. After a retiming rr, edge ee has wr(e)=w(e)+r(V)−r(U)w_r(e) = w(e) + r(V) - r(U) delays, as on the retiming page, so its count becomes

DF′(e)=Nwr(e)−PU+v−u=DF(e)+N (r(V)−r(U)).D_F'(e) = N w_r(e) - P_U + v - u = D_F(e) + N\,(r(V) - r(U)).

This is at least 0 exactly when r(U)−r(V)≤DF(e)/Nr(U) - r(V) \le D_F(e)/N, and since the left side is an integer, exactly when r(U)−r(V)≤⌊DF(e)/N⌋r(U) - r(V) \le \lfloor D_F(e)/N \rfloor. These are the rows of L3. A retiming keeps the function of the graph, so the folded circuit of the retimed graph computes the same output stream, with the output of a node VV for sample ll now in iteration l+r(V)l + r(V).

When no retiming exists. The system of L3 has a solution exactly when no cycle of the constraint graph is negative, that is, when every directed cycle CC of the data flow graph has ∑e∈C⌊DF(e)/N⌋≥0\sum_{e \in C} \lfloor D_F(e)/N \rfloor \ge 0. Around a cycle the orders v−uv - u cancel, so

∑e∈CDF(e)=N w(C)−∑U∈CPU.\sum_{e \in C} D_F(e) = N\,w(C) - \sum_{U \in C} P_U.

Since a floor is at most its argument, a folding set can work only if Nw(C)≥∑U∈CPUN w(C) \ge \sum_{U \in C} P_U on every cycle: NN clock steps per iteration must be at least the iteration bound of the graph with the times PUP_U. The floors make the exact test stronger than this bound, and a bad choice of orders can fail it even when the bound holds.

Why the folded circuit is right. By L8, unit HVH_V runs VV at the steps Nl+vNl + v and nothing else in those steps, since the orders on one unit are distinct. By the folding equation, the value of UU that iteration ll of VV needs leaves HUH_U exactly DF′(e)D_F'(e) steps before, so it is at the end of the register chain of L7 at that step. By induction on the steps, each unit computes the value of the retimed graph for the iteration it runs.

Classic examples

A second-order recursive filter on one adder and one multiplier. Take y(n)=x(n)+3y(n−2)+5y(n−3)y(n) = x(n) + 3 y(n - 2) + 5 y(n - 3): an adder AA that sums x(n)x(n) and two products, a multiplier BB by 3 with edges A→BA \to B (0 delays) and B→AB \to A (2 delays), and a multiplier CC by 5 with edges A→CA \to C (1 delay) and C→AC \to A (2 delays). Fold with N=2N = 2 onto one adder and one multiplier, each with P=1P = 1 stage, with orders A:0A: 0, B:0B: 0, C:1C: 1. The input XX is read at order 0 with P=0P = 0.

edge ww DFD_F by L1 after r(B)=1r(B) = 1
X→AX \to A 0 0−0+0−0=00 - 0 + 0 - 0 = 0 0
A→BA \to B 0 0−1+0−0=−10 - 1 + 0 - 0 = -1 1
B→AB \to A 2 4−1+0−0=34 - 1 + 0 - 0 = 3 1
A→CA \to C 1 2−1+1−0=22 - 1 + 1 - 0 = 2 2
C→AC \to A 2 4−1+0−1=24 - 1 + 0 - 1 = 2 2

The edge A→BA \to B is negative: the multiplier would need y(n)y(n) in the same step in which the adder starts it. The rows of L3 are r(A)−r(B)≤−1r(A) - r(B) \le -1 from A→BA \to B and r(B)−r(A)≤1r(B) - r(A) \le 1 from B→AB \to A, and the others allow 0, so the least solution is r(B)=1r(B) = 1 and 0 elsewhere. The retiming moves one delay from B→AB \to A to A→BA \to B, so BB now multiplies y(n−1)y(n - 1) and AA adds that product one sample later, which is the same filter. The cycle sums check the identity: on A→B→AA \to B \to A, −1+3=2⋅2−2-1 + 3 = 2 \cdot 2 - 2, and on A→C→AA \to C \to A, 2+2=2⋅3−22 + 2 = 2 \cdot 3 - 2.

The folded circuit runs the adder on AA in even steps, and the multiplier on BB in even steps and on CC in odd steps. The multiplier input is a two-way switch: in even steps it takes the adder output through 1 register with the constant 3, and in odd steps through 2 registers with the constant 5. The adder takes xx directly, the multiplier output through 1 register (the product of BB) and through 2 registers (the product of CC). The design uses 2 units instead of 3, at twice the clock rate, and the run produces the same output samples as the original filter.

A serial FIR filter. An NN-tap FIR filter folded with factor NN onto one multiplier and one adder is the classic multiply-accumulate loop: each sample takes NN steps, one per tap, and the folding equation gives the delay line that feeds the taps in turn.

Folding after unfolding. Unfolding by JJ followed by folding by NN gives hardware that takes JJ samples every NN steps. This is how a design reaches the iteration bound per sample with a chosen number of units.

High-level synthesis. In the terms of high-level synthesis, the folding set is a modulo schedule with initiation interval NN together with a resource binding, and the folding equation computes the register lifetimes that register binding then packs. The switches and their steps form the controller of a finite state machine with datapath, a counter modulo NN; Parhi, Wang and Brown (1992) synthesize these control circuits for pipelined folded designs.

Variations

  • Register minimization. The registers of L7 are counted per edge. The edges that leave one unit can share one delay line with taps, so a unit needs only as many registers as its longest DFD_F; Parhi's book (Chapters 6.3 and 6.4) goes further with a lifetime analysis that finds the least number of registers for all edges at once, and a forward and backward allocation of the values to them.
  • Choosing the folding set. The template takes the folding set as given. Choosing it is a scheduling and binding problem, NP-hard in general like resource-constrained scheduling, and a bad choice can force more registers or make L3 fail.
  • Multirate folding. Parhi's book (Chapter 6.5) folds graphs with up-samplers and down-samplers, where operations run at different rates.
  • Folding with a lower bound on the delays. If a unit needs its operand one step early, for instance because of a register at its input, the rows become DF′(e)≥1D_F'(e) \ge 1, which shifts each row of L3 by a constant and keeps the same method.

Pitfalls

  • A sign slip in the equation. The count is Nw(e)−PU+v−uN w(e) - P_U + v - u: the pipeline depth of the source unit, not of the target, and the order of the target minus the order of the source. Using PVP_V or u−vu - v gives counts that look plausible but put each operand in the wrong step.
  • Dropping the floor. The row of L3 is r(U)−r(V)≤⌊DF/N⌋r(U) - r(V) \le \lfloor D_F/N \rfloor, not ≤DF/N\le D_F/N rounded to the nearest integer and not ⌈DF/N⌉\lceil D_F/N \rceil. With a ceiling, an edge with DF=−1D_F = -1 and N=2N = 2 gets the row r(U)−r(V)≤0r(U) - r(V) \le 0, which allows r=0r = 0 and leaves the edge at −1-1.
  • Ignoring the cycle condition. If some cycle has Nw(C)<∑PUN w(C) < \sum P_U, no folding set and no retiming will work for that NN; a larger NN or less pipelining is needed. If the condition holds but the floors fail, the folding orders are to blame, not NN.
  • Two operations in one slot. Two operations with the same unit and the same order would need the unit twice in one step. The folding set must be checked before L1.
  • Forgetting the output shift. After the retiming, the value of a node with r(V)>0r(V) > 0 for sample ll appears in iteration l+r(V)l + r(V). Reading the output without this shift gives a stream that is correct but late by r(V)r(V) samples.

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_folding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dsp-folding/. The authors are listed in prov/PNFW75.jsonl.

"""Folding transformation of a data flow graph (Parhi).

A graph has nodes with a kind: "in" (the host, which emits x(k) in
iteration k), "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 registers 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 folding set gives each operation a hardware unit and an order in
{0, ..., N - 1}. Unit h is pipelined with P[h] >= 1 stages. The host is a
unit with order 0 and P = 0.
"""

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, out):
    """Run the graph for len(x) iterations; return the values of node out."""
    nodes, edges, kind, coef = graph["nodes"], graph["edges"], graph["kind"], graph["coef"]
    order = topo_zero_delay(nodes, edges)
    val = {v: [] for v in nodes}
    for k in range(len(x)):
        for v in order:
            if kind[v] == "in":
                val[v].append(x[k] % MOD)
                continue
            ins = [val[u][k - w] if k - w >= 0 else 0 for (u, b, w) in edges if b == v]
            val[v].append(node_value(kind[v], coef.get(v, 1), ins))
    return val[out]


def folding_delays(graph, unit, order, P, N, r=None):
    """D_F(U -> V) = N w_r(e) - P_U + v - u for every edge, in edge order."""
    r = r or {}
    res = []
    for u, v, w in graph["edges"]:
        wr = w + r.get(v, 0) - r.get(u, 0)
        res.append(N * wr - P[unit[u]] + order[v] - order[u])  # @line L1
    return res


def folding_retiming(graph, unit, order, P, N):
    """Least r >= 0 with r(U) - r(V) <= floor(D_F(e) / N) on every edge.

    Each row reads r(V) >= r(U) - c with c = floor(D_F(e) / N). Start from
    r = 0 and raise r(V) to r(U) - c until no row is violated, as in
    Bellman-Ford for longest paths. If a pass still raises a value after
    |V| passes, a cycle has a positive sum of -c, and no retiming exists.
    The host has no input edge, so it keeps r = 0.
    """
    nodes = graph["nodes"]
    r = {v: 0 for v in nodes}
    rows = [(u, v, d // N) for (u, v, w), d in zip(graph["edges"], folding_delays(graph, unit, order, P, N))]
    for _ in range(len(nodes) + 1):
        changed = False
        for u, v, c in rows:  # @line L3
            if r[u] - c > r[v]:
                r[v] = r[u] - c
                changed = True
        if not changed:
            return r
    return None


def fold(graph, unit, order, P, N):
    """Return (r, D) with D the register count of each folded edge, or None."""
    for v in graph["nodes"]:
        if not 0 <= order[v] < N:
            raise ValueError("order out of range")
    slots = set()
    for v in graph["nodes"]:
        key = (unit[v], order[v])
        if key in slots:
            raise ValueError("two operations in one slot of one unit")
        slots.add(key)
    # A retiming of all zeros is returned when no D_F is negative.
    r = folding_retiming(graph, unit, order, P, N)  # @line L2
    if r is None:
        return None  # @line L4
    return r, folding_delays(graph, unit, order, P, N, r)  # @line L5 L9


def simulate_folded(graph, unit, order, P, N, r, D, x, out):
    """Clock-by-clock run of the folded architecture.

    In cycle t, unit h runs the operation whose order is t mod N. Its result
    leaves the unit P[h] cycles later. The input of V along edge e is the
    output of the unit of U as it was D[e] cycles earlier. The host emits
    x(l - r(host)) at cycle N l. Return y(0), ..., y(len(x) - 1) read at
    the output of node out.
    """
    nodes, edges, kind, coef = graph["nodes"], graph["edges"], graph["kind"], graph["coef"]
    host = [v for v in nodes if kind[v] == "in"]
    shift = max(r.values())
    L = len(x) + shift + 2
    T = N * L + max(P.values()) + 1
    emit = {h: {} for h in set(unit.values())}
    by_slot = {}
    for v in nodes:
        if kind[v] != "in":
            by_slot.setdefault((unit[v], order[v]), v)
    ins_of = {v: [(i, e) for i, e in enumerate(edges) if e[1] == v] for v in nodes}
    for t in range(T):
        if t % N == 0:
            for h in host:
                l = t // N - r[h]
                emit[unit[h]][t] = x[l] % MOD if 0 <= l < len(x) else 0
        for hw in emit:
            v = by_slot.get((hw, t % N))  # @line L8
            if v is None:
                continue
            ins = []
            for i, (u, _, _) in ins_of[v]:  # @line L6
                ins.append(emit[unit[u]].get(t - D[i], 0))  # @line L7
            emit[hw][t + P[hw]] = node_value(kind[v], coef.get(v, 1), ins)
    y = []
    for l in range(len(x)):
        y.append(emit[unit[out]].get(N * (l + r[out]) + order[out] + P[unit[out]], 0))
    return y
test_dsp_folding.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dsp-folding/. The authors are listed in prov/PNFW75.jsonl.

import itertools
import random

from dsp_folding import fold, folding_delays, simulate, simulate_folded

# 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_UNIT = {"X": "host", "A": "add", "B": "mul", "C": "mul"}
IIR_ORDER = {"X": 0, "A": 0, "B": 0, "C": 1}
IIR_P = {"host": 0, "add": 1, "mul": 1}


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):
        u = rng.choice(nodes[: i + 1])
        edges.append((u, v, rng.randint(0, 2)))
    for _ in range(rng.randint(1, 3)):
        a, b = rng.randrange(n), rng.randrange(n)
        w = rng.randint(1, 3) 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)
    return {"nodes": nodes, "edges": edges, "kind": kind, "coef": coef}, rng.choice(ops)


def random_folding(rng: random.Random, graph):
    N = rng.randint(2, 3)
    unit, order, P = {"X": "host"}, {"X": 0}, {"host": 0}
    for k in ("add", "mul"):
        ops = [v for v in graph["nodes"] if graph["kind"][v] == k]
        m = -(-len(ops) // N)
        slots = [(f"{k}{j}", o) for j in range(m) for o in range(N)]
        rng.shuffle(slots)
        for v, (h, o) in zip(ops, slots):
            unit[v], order[v] = h, o
            P[h] = rng.randint(1, 2)
    return unit, order, P, N


def simple_cycles(nodes, edges):
    pos = {v: i for i, v in enumerate(nodes)}
    out = []

    def walk(s, v, path, seen):
        for i, (a, b, w) in enumerate(edges):
            if a != v:
                continue
            if b == s:
                out.append(path + [i])
            elif b not in seen and pos[b] > pos[s]:
                walk(s, b, path + [i], seen | {b})

    for s in nodes:
        walk(s, s, [], {s})
    return out


def test_iir_example():
    D0 = folding_delays(IIR, IIR_UNIT, IIR_ORDER, IIR_P, 2)
    assert D0 == [0, -1, 3, 2, 2]
    r, D = fold(IIR, IIR_UNIT, IIR_ORDER, IIR_P, 2)
    assert r == {"X": 0, "A": 0, "B": 1, "C": 0}
    assert D == [0, 1, 1, 2, 2]
    x = [(7 * i + 1) % 50 for i in range(30)]
    assert simulate_folded(IIR, IIR_UNIT, IIR_ORDER, IIR_P, 2, r, D, x, "A") == simulate(IIR, x, "A")


def test_random_graphs_against_unfolded_run():
    rng = random.Random(20260)
    feasible = infeasible = 0
    for _ in range(300):
        g, out = random_graph(rng)
        unit, order, P, N = random_folding(rng, g)
        D0 = folding_delays(g, unit, order, P, N)
        cycles = simple_cycles(g["nodes"], g["edges"])
        # The sum of D_F around a cycle is N w(C) minus the pipeline stages.
        for c in cycles:
            assert sum(D0[i] for i in c) == N * sum(g["edges"][i][2] for i in c) - sum(P[unit[g["edges"][i][0]]] for i in c)
        bad = any(sum(D0[i] // N for i in c) < 0 for c in cycles)
        res = fold(g, unit, order, P, N)
        assert (res is None) == bad
        if res is None:
            infeasible += 1
            continue
        feasible += 1
        r, D = res
        assert all(d >= 0 for d in D)
        # r is the least nonnegative solution of the rows.
        rows = [(u, v, d // N) for (u, v, w), d in zip(g["edges"], D0)]
        names = g["nodes"]
        for cand in itertools.product(range(4), repeat=len(names)):
            rc = dict(zip(names, cand))
            if all(rc[u] - rc[v] <= c for u, v, c in rows):
                assert all(r[v] <= rc[v] for v in names)
        x = [rng.randrange(1000) for _ in range(25)]
        assert simulate_folded(g, unit, order, P, N, r, D, x, out) == simulate(g, x, out)
    assert feasible > 100 and infeasible > 5

Exercises

  1. In the example, change the order of CC to 0 and the order of BB to 1. Compute the five counts DFD_F, the retiming, and the registers of the folded circuit.
  2. Show that if every cycle has Nw(C)−∑PU≥NN w(C) - \sum P_U \ge N times its number of edges, then L3 always has a solution, whatever the orders.
  3. Fold the graph of the example with N=1N = 1 onto three units with P=2P = 2 each. Which cycle fails the condition, and how does this match the iteration bound of the graph with node times 2?
  4. Prove that the least solution of L3 with r≥0r \ge 0 gives r=0r = 0 to every node with no incoming edge.

References

  1. Keshab K. Parhi, VLSI Digital Signal Processing Systems, Design and Implementation, Wiley, 1999, Chapter 6 (6.2 the folding transformation and the folding equation, retiming for folding, 6.3 and 6.4 register minimization, 6.5 multirate folding)
  2. Keshab K. Parhi, Ching-Yi Wang and Andrew P. Brown, Synthesis of control circuits in folded pipelined DSP architectures, IEEE Journal of Solid-State Circuits 27(1), 29 to 43, 1992, the folding of data flow graphs onto pipelined units, the register counts of the folded edges, and the control circuits of the switches
  3. Charles E. Leiserson and James B. Saxe, Retiming synchronous circuitry, Algorithmica 6, 5 to 35, 1991, retiming as a system of difference constraints, used here to make every folded edge nonnegative

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