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 , every unit repeats a cycle of 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 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 . This is a modulo schedule with initiation interval , written in the language of signal processing.
- The units may be pipelined: a unit with stages gives its result steps after it starts, and can start a new operation every step.
The template
The input is a data flow graph with edges carrying delays, the folding factor , and a folding set: each operation gets a unit and a folding order , written in lower case, with no two operations on one unit sharing an order. Iteration of then runs in clock step on , and its result is ready at step , written for short.
FOLD(G, N, H, order, P)- 1
for each edge e = U → V do D_F(e) ← N · w(e) − P_U + v − u - 2
if some D_F(e) < 0 then - 3
solve r(U) − r(V) ≤ ⌊D_F(e) / N⌋ for every edge e = U → V, with r ≥ 0 - 4
if there is no solution then fail: no retiming makes this folding set work - 5
for each edge e = U → V do w(e) ← w(e) + r(V) − r(U); recompute D_F(e) by L1 - 6
for each edge e = U → V do - 7
wire the output of H_U through a chain of D_F(e) registers to an input switch of H_V - 8
close that switch in the steps Nl + v, l = 0, 1, 2, ... - 9
return the folded circuit
The holes are the factor , the folding set (which unit and which step for each operation), the pipelining 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 , start from , and raise values as in Bellman-Ford for longest paths until no row is violated. This gives the least solution with , and if values still rise after passes, a cycle makes the system infeasible. The input node has no incoming edge, so it keeps .
The folding equation. Iteration of is ready at step . Edge says that iteration of uses it, and that iteration runs at step . The value must wait between the two steps, so it needs
registers, the same for every . A negative count means that would need the value before has made it.
The retiming condition. After a retiming , edge has delays, as on the retiming page, so its count becomes
This is at least 0 exactly when , and since the left side is an integer, exactly when . 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 for sample now in iteration .
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 of the data flow graph has . Around a cycle the orders cancel, so
Since a floor is at most its argument, a folding set can work only if on every cycle: clock steps per iteration must be at least the iteration bound of the graph with the times . 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 runs at the steps and nothing else in those steps, since the orders on one unit are distinct. By the folding equation, the value of that iteration of needs leaves exactly 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 : an adder that sums and two products, a multiplier by 3 with edges (0 delays) and (2 delays), and a multiplier by 5 with edges (1 delay) and (2 delays). Fold with onto one adder and one multiplier, each with stage, with orders , , . The input is read at order 0 with .
| edge | by L1 | after | |
|---|---|---|---|
| 0 | 0 | ||
| 0 | 1 | ||
| 2 | 1 | ||
| 1 | 2 | ||
| 2 | 2 |
The edge is negative: the multiplier would need in the same step in which the adder starts it. The rows of L3 are from and from , and the others allow 0, so the least solution is and 0 elsewhere. The retiming moves one delay from to , so now multiplies and adds that product one sample later, which is the same filter. The cycle sums check the identity: on , , and on , .
The folded circuit runs the adder on in even steps, and the multiplier on in even steps and on 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 directly, the multiplier output through 1 register (the product of ) and through 2 registers (the product of ). 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 -tap FIR filter folded with factor onto one multiplier and one adder is the classic multiply-accumulate loop: each sample takes steps, one per tap, and the folding equation gives the delay line that feeds the taps in turn.
Folding after unfolding. Unfolding by followed by folding by gives hardware that takes samples every 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 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 ; 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 ; 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 , which shifts each row of L3 by a constant and keeps the same method.
Pitfalls
- A sign slip in the equation. The count is : the pipeline depth of the source unit, not of the target, and the order of the target minus the order of the source. Using or gives counts that look plausible but put each operand in the wrong step.
- Dropping the floor. The row of L3 is , not rounded to the nearest integer and not . With a ceiling, an edge with and gets the row , which allows and leaves the edge at .
- Ignoring the cycle condition. If some cycle has , no folding set and no retiming will work for that ; a larger or less pipelining is needed. If the condition holds but the floors fail, the folding orders are to blame, not .
- 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 for sample appears in iteration . Reading the output without this shift gives a stream that is correct but late by 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.
# 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
- In the example, change the order of to 0 and the order of to 1. Compute the five counts , the retiming, and the registers of the folded circuit.
- Show that if every cycle has times its number of edges, then L3 always has a solution, whatever the orders.
- Fold the graph of the example with onto three units with each. Which cycle fails the condition, and how does this match the iteration bound of the graph with node times 2?
- Prove that the least solution of L3 with gives to every node with no incoming edge.
References
- 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)
- 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
- 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.
| 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 PNFW75 Edit this page History Report an error Markdown