Algorithm Search⌘K

Algorithmcore

Retiming

Also called Leiserson-Saxe retiming, minimum period retiming.

Leiserson and Saxe's moving of registers across gates without changing behaviour. A minimum clock period retiming is found by binary search and Bellman-Ford.

Time
O(V^3 log V) worst
Space
O(V^2) extra
Where
E = the number of wires; V = the number of gates with the host
Properties
deterministicexactofflineiterative
Origin
Charles E. Leiserson, Flavio M. Rose, James B. Saxe, 1983

Retiming moves the registers of a synchronous circuit across its gates, so that the circuit computes the same output streams with a shorter clock period or with fewer registers. Leiserson and Saxe model the circuit as a graph with a delay on each gate and a register count on each wire, and they describe a retiming by one integer per gate. A retiming with clock period at most cc exists exactly when a system of difference constraints has a solution, so Bellman-Ford tests each cc and a binary search over O(V2)O(V^2) candidate values finds the least period in O(V3log⁡V)O(V^3 \log V) time. This page treats the least period. The least register count is minimum-area retiming.

In plain words

A clocked circuit has blocks of logic with registers between them. The clock must wait for the slowest stretch of logic between two registers. Retiming slides registers forward or backward through the gates. A register that leaves all the outputs of a gate reappears on all of its inputs, and the other way round. The values that come out of the circuit stay the same, but the long stretches can get shorter. The method gives each gate a number: how many registers it pushes from its outputs back to its inputs. Two simple rules on these numbers say that no wire gets a negative count and that no long stretch is left without a register. The rules are of the form "this number minus that number is at most a constant", and a shortest path algorithm solves them.

The problem

The circuit is a graph G=(V,E)G = (V, E). A vertex is a gate with an integer delay d(v)≥0d(v) \ge 0. The host vertex hh stands for the outside world, with d(h)=0d(h) = 0. An edge e=(u,v)e = (u, v) is a wire from the output of uu to an input of vv, and w(e)≥0w(e) \ge 0 is the number of registers on it. Every cycle has at least one register. For a path pp, w(p)w(p) is the sum of the register counts and d(p)d(p) is the sum of the delays of its vertices, ends included. The clock period is

c(G)=max⁡{d(p):w(p)=0}.c(G) = \max \{ d(p) : w(p) = 0 \}.

A retiming is a map r:V→Zr : V \to \mathbb{Z} with r(h)=0r(h) = 0. It gives the new counts wr(e)=w(e)+r(v)−r(u)w_r(e) = w(e) + r(v) - r(u) for e=(u,v)e = (u, v), and it is legal when every wr(e)≥0w_r(e) \ge 0. The output is a legal retiming rr that minimizes c(Gr)c(G_r), and that least period.

Retiming moves registers. The clock still reaches every register at the same time. Clock skew scheduling does the opposite: it keeps the registers where they are and moves the clock arrival time cic_i of each register. Both lead to difference constraints solved by Bellman-Ford, but the variables are different.

The algorithm

Let W(u,v)W(u, v) be the fewest registers on a path from uu to vv, and D(u,v)D(u, v) the largest delay of a path from uu to vv with W(u,v)W(u, v) registers. The empty path gives W(v,v)=0W(v, v) = 0 and D(v,v)=d(v)D(v, v) = d(v).

  1. MIN-PERIOD-RETIMING(G, w, d, h)
  2. 1best(u, v) ← the least sum of the pairs (w(e), -d(tail of e)) over the paths from u to v,
  3. by Floyd-Warshall with lexicographic order, and best(v, v) ← (0, 0)
  4. 2W(u, v) ← the first part of best(u, v); D(u, v) ← d(v) minus the second part
  5. 3let c_1 < c_2 < ... < c_k be the distinct values of D
  6. 4lo ← 1, hi ← k, best_r ← 0
  7. 5while lo < hi do
  8. 6mid ← ⌊(lo + hi) / 2⌋
  9. 7S ← { r(u) - r(v) ≤ w(e) : e = (u, v) ∈ E }
  10. 8∪ { r(u) - r(v) ≤ W(u, v) - 1 : D(u, v) > c_mid }
  11. 9r ← BELLMAN-FORD on S, from a virtual source with a 0 edge to every vertex
  12. 10if a negative cycle is found then lo ← mid + 1
  13. 11else hi ← mid, best_r ← r - r(h)
  14. 12return (c_lo, best_r)

Lines L1 and L2 compute the two matrices with one all-pairs pass. A path is better when it has fewer registers, and among paths with the same count, when it has more delay. So the weight of an edge is the pair (w(e),−d(u))(w(e), -d(u)), and pairs add and compare in lexicographic order. Floyd-Warshall works for this order because it is a total order that addition preserves and no cycle has a negative pair, since every cycle has a register. The constraint r(u)−r(v)≤br(u) - r(v) \le b is the edge v→uv \to u of weight bb in the constraint graph, and the shortest distances from the virtual source are a solution when no negative cycle exists. Line L8 holds the period constraints: a pair (u,v)(u, v) with D(u,v)>cD(u, v) > c needs at least one register on every path from uu to vv after the retiming. When u=vu = v and d(v)>cd(v) > c, line L8 gives 0≤−10 \le -1, a negative self loop, and no retiming works, as it should be.

Example

The correlator of Leiserson and Saxe has a host 00, four comparators 11 to 44 with delay 3 and three adders 55 to 77 with delay 7. Its edges are (0,1,1)(0,1,1), (1,2,1)(1,2,1), (2,3,1)(2,3,1), (3,4,1)(3,4,1), (4,5,0)(4,5,0), (5,6,0)(5,6,0), (6,7,0)(6,7,0), (7,0,0)(7,0,0), (3,5,0)(3,5,0), (2,6,0)(2,6,0) and (1,7,0)(1,7,0), written (u,v,w)(u, v, w). It has 4 registers, all on the chain of comparators. The path 3→5→6→73 \to 5 \to 6 \to 7 has no register and delay 3+7+7+7=243 + 7 + 7 + 7 = 24, so c(G)=24c(G) = 24.

The matrix DD has 20 distinct values: 0, 3, 6, 7, 9, 10, 12, 13, 14, 16, 17, 19, 20, 21, 23, 24, 26, 27, 30 and 33. The binary search probes them as follows.

probe cc Bellman-Ford interval of indices after the probe
1 16 a solution values up to 16
2 9 a negative cycle from 10 to 16
3 13 a solution from 10 to 13
4 12 a negative cycle only 13

The least period is 13. A retiming that reaches it is r=(0,−1,−1,−2,−2,−2,−1,0)r = (0, -1, -1, -2, -2, -2, -1, 0) for the vertices 00 to 77. The new counts put one register on each of the edges (1,2)(1,2), (3,4)(3,4), (5,6)(5,6), (6,7)(6,7) and (1,7)(1,7), and none on the other edges, so the retimed circuit has 5 registers. Its longest path with no register is 2→3→52 \to 3 \to 5, with delay 3+3+7=133 + 3 + 7 = 13. The circuit has 143 legal retimings with r(0)=0r(0) = 0. Four of them have period 13, and none has a smaller period.

Correctness

The key fact is that a retiming changes the register count of a path only through its two ends: wr(p)=w(p)+r(v)−r(u)w_r(p) = w(p) + r(v) - r(u) for a path pp from uu to vv, because the terms of the inner vertices cancel. From this, Leiserson and Saxe prove that rr is legal with c(Gr)≤cc(G_r) \le c exactly when rr satisfies the constraints of lines L7 and L8. A path with D(u,v)>cD(u, v) > c needs a register after the retiming, and it is enough to ask this of the paths with W(u,v)W(u, v) registers, since the other paths from uu to vv have at least one more register to start with and legality keeps their count at least 1. The least period over legal retimings is one of the values D(u,v)D(u, v), and the test is monotone in cc, so the binary search finds it. The largest value ckc_k is at least c(G)c(G), so the retiming r=0r = 0 meets it. The full proof gives the details.

Proof: The binary search with Bellman-Ford returns a least period legal retimingfull

We use the notation of the page. Paths may repeat vertices. For a path pp from uu to vv, w(p)w(p) is the sum of w(e)w(e) over its edges and d(p)d(p) is the sum of d(x)d(x) over its vertices, with uu and vv included. The empty path at vv has w=0w = 0 and d=d(v)d = d(v). Every cycle of GG has w≥1w \ge 1.

Lemma 1 (paths). For every retiming rr and every path pp from uu to vv, wr(p)=w(p)+r(v)−r(u)w_r(p) = w(p) + r(v) - r(u).

Proof. Let p=x0x1⋯xkp = x_0 x_1 \cdots x_k with x0=ux_0 = u and xk=vx_k = v. Then wr(p)=∑i=1k(w(xi−1,xi)+r(xi)−r(xi−1))w_r(p) = \sum_{i=1}^{k} \big(w(x_{i-1}, x_i) + r(x_i) - r(x_{i-1})\big). The sum of the differences telescopes to r(xk)−r(x0)r(x_k) - r(x_0). For the empty path both sides are 0. □\square

A consequence: a retiming does not change w(C)w(C) for a cycle CC, so every cycle of GrG_r still has a register, and c(Gr)c(G_r) is finite.

Lemma 2 (the matrices). Lines L1 and L2 compute W(u,v)=min⁡{w(p)}W(u, v) = \min \{ w(p) \} and D(u,v)=max⁡{d(p):w(p)=W(u,v)}D(u, v) = \max \{ d(p) : w(p) = W(u, v) \} over the paths pp from uu to vv, for every pair with a path.

Proof. Give the edge e=(x,y)e = (x, y) the pair (w(e),−d(x))(w(e), -d(x)). The sum over the edges of a path pp from uu to vv is (w(p),−(d(p)−d(v)))(w(p), -(d(p) - d(v))), since every vertex of pp except vv is the tail of exactly one edge of pp. The empty path gives (0,0)(0, 0), which is also this formula. In lexicographic order, the least sum has the least w(p)w(p) and, among those, the largest d(p)d(p). Pairs with lexicographic order form a totally ordered group, and the sum of a cycle is at least (1,⋅)>(0,0)(1, \cdot) > (0, 0) because every cycle has a register. So no cycle has a negative sum, a least path sum exists and is reached by a simple path, and Floyd-Warshall computes it, by the same proof as for real weights. Line L2 reads off WW and DD. □\square

Lemma 3 (legal). rr is legal exactly when r(u)−r(v)≤w(e)r(u) - r(v) \le w(e) for every edge e=(u,v)e = (u, v).

Proof. This is the definition wr(e)=w(e)+r(v)−r(u)≥0w_r(e) = w(e) + r(v) - r(u) \ge 0. □\square

Theorem 1 (Leiserson and Saxe). Let c≥0c \ge 0. A retiming rr is legal and has c(Gr)≤cc(G_r) \le c exactly when it satisfies (a) r(u)−r(v)≤w(e)r(u) - r(v) \le w(e) for every edge e=(u,v)e = (u, v), and (b) r(u)−r(v)≤W(u,v)−1r(u) - r(v) \le W(u, v) - 1 for every pair (u,v)(u, v) with D(u,v)>cD(u, v) > c.

Proof. Note first that c(Gr)≤cc(G_r) \le c means that every path pp with wr(p)=0w_r(p) = 0 has d(p)≤cd(p) \le c. Retiming does not change delays.

Assume rr is legal with c(Gr)≤cc(G_r) \le c. Then (a) holds by Lemma 3. Let D(u,v)>cD(u, v) > c and let pp be a path from uu to vv with w(p)=W(u,v)w(p) = W(u, v) and d(p)=D(u,v)d(p) = D(u, v). Since d(p)>cd(p) > c, the path has wr(p)≠0w_r(p) \ne 0. It has wr(p)≥0w_r(p) \ge 0 because rr is legal and wr(p)w_r(p) is a sum of wr(e)≥0w_r(e) \ge 0. So wr(p)≥1w_r(p) \ge 1, and Lemma 1 gives W(u,v)+r(v)−r(u)≥1W(u, v) + r(v) - r(u) \ge 1, which is (b).

Assume (a) and (b). Then rr is legal by Lemma 3. Let pp be a path from uu to vv with d(p)>cd(p) > c. We show wr(p)≥1w_r(p) \ge 1. If D(u,v)>cD(u, v) > c, then by Lemma 1 and (b), wr(p)=w(p)+r(v)−r(u)≥W(u,v)+r(v)−r(u)≥1w_r(p) = w(p) + r(v) - r(u) \ge W(u, v) + r(v) - r(u) \ge 1. If D(u,v)≤cD(u, v) \le c, then d(p)>D(u,v)d(p) > D(u, v), so pp is not one of the paths with W(u,v)W(u, v) registers, and w(p)≥W(u,v)+1w(p) \ge W(u, v) + 1. Take a path qq from uu to vv with w(q)=W(u,v)w(q) = W(u, v). Legality gives wr(q)≥0w_r(q) \ge 0, that is r(u)−r(v)≤W(u,v)r(u) - r(v) \le W(u, v) by Lemma 1. So wr(p)=w(p)+r(v)−r(u)≥W(u,v)+1−W(u,v)=1w_r(p) = w(p) + r(v) - r(u) \ge W(u, v) + 1 - W(u, v) = 1. Every path with delay above cc has a register in GrG_r, so c(Gr)≤cc(G_r) \le c. □\square

Lemma 4 (the test). For a given cc, lines L7 to L11 return a legal retiming with r(h)=0r(h) = 0 and c(Gr)≤cc(G_r) \le c if one exists, and report a negative cycle otherwise.

Proof. The system SS of lines L7 and L8 is a system of difference constraints with integer bounds. By the theorem on the difference constraints page, Bellman-Ford from a virtual source finds a solution when the constraint graph has no negative cycle, and the system has no solution when it has one. All bounds are integers, so the distances, and the solution, are integers. Adding a constant to all r(x)r(x) keeps every difference, so r−r(h)r - r(h) is still a solution and has r(h)=0r(h) = 0. By Theorem 1, the integer solutions of SS with r(h)=0r(h) = 0 are exactly the legal retimings with c(Gr)≤cc(G_r) \le c. □\square

Lemma 5 (candidates). Let c∗c^* be the least period over all legal retimings. Then c∗=D(u,v)c^* = D(u, v) for some pair (u,v)(u, v). Moreover the set of cc for which a legal retiming with period at most cc exists is upward closed, and it contains the largest value ckc_k of DD.

Proof. Let rr be legal with c(Gr)=c∗c(G_r) = c^*, and let pp be a path from uu to vv with wr(p)=0w_r(p) = 0 and d(p)=c∗d(p) = c^*. For every path qq from uu to vv, legality gives wr(q)≥0=wr(p)w_r(q) \ge 0 = w_r(p), so by Lemma 1, w(q)≥w(p)w(q) \ge w(p). Hence w(p)=W(u,v)w(p) = W(u, v) and d(p)≤D(u,v)d(p) \le D(u, v). Let qq be a path from uu to vv with w(q)=W(u,v)w(q) = W(u, v) and d(q)=D(u,v)d(q) = D(u, v). By Lemma 1, wr(q)=wr(p)=0w_r(q) = w_r(p) = 0, so d(q)≤c(Gr)=c∗d(q) \le c(G_r) = c^*. So c∗=d(p)≤D(u,v)=d(q)≤c∗c^* = d(p) \le D(u, v) = d(q) \le c^*.

If a retiming has period at most cc, it has period at most every c′≥cc' \ge c, so the set is upward closed. For r=0r = 0, every path pp from uu to vv with w(p)=0w(p) = 0 has W(u,v)=0W(u, v) = 0 and d(p)≤D(u,v)≤ckd(p) \le D(u, v) \le c_k. So c(G)≤ckc(G) \le c_k and r=0r = 0 is a witness for ckc_k. □\square

Theorem 2. MIN-PERIOD-RETIMING returns c∗c^* and a legal retiming rr with r(h)=0r(h) = 0 and c(Gr)=c∗c(G_r) = c^*.

Proof. Let jj be the least index with cjc_j feasible. By Lemma 5, jj exists, cj=c∗c_j = c^* (since c∗c^* is among the values and no smaller value is feasible), and cic_i is feasible exactly when i≥ji \ge j. The loop keeps the invariant lo≤j≤hilo \le j \le hi, and best_r is a legal retiming with r(h)=0r(h) = 0 and period at most chic_{hi}. At the start, lo=1lo = 1, hi=khi = k, and best_r =0= 0 meets ckc_k by Lemma 5. In a probe, Lemma 4 decides whether cmidc_{mid} is feasible. If not, mid<jmid < j and lo←mid+1lo \leftarrow mid + 1 keeps lo≤jlo \le j. If so, j≤midj \le mid, and hi←midhi \leftarrow mid with the new witness keeps the invariant. Each probe shrinks hi−lohi - lo, since lo≤mid<hilo \le mid < hi, so the loop stops with lo=hi=jlo = hi = j. Then best_r is legal with period at most cj=c∗c_j = c^*, and no legal retiming has a smaller period, so its period is exactly c∗c^*. ■\blacksquare

Termination. Floyd-Warshall and Bellman-Ford stop after a fixed number of rounds, and the loop of line L5 runs at most ⌈log⁡2k⌉\lceil \log_2 k \rceil times.

Complexity

Line L1 runs Floyd-Warshall in O(V3)O(V^3) time on pairs of integers. Each probe builds at most E+V2E + V^2 constraints, and Bellman-Ford takes O(V⋅(E+V2))=O(V3)O(V \cdot (E + V^2)) = O(V^3) time on them. There are k≤V2k \le V^2 values, so the search makes O(log⁡V)O(\log V) probes. The total is O(V3log⁡V)O(V^3 \log V) time and O(V2)O(V^2) space for WW, DD and the constraints. Here VV and EE are the numbers of gates and wires of the netlist.

Properties

  • Exact. The result is the least period over all legal retimings of the circuit, with gate delays as given.
  • The function is kept. A retiming changes where the registers are, not what the gates compute. After a start-up phase, the retimed circuit produces the same output streams as the original. See the pitfall on initial states.
  • Integral. The constraints have integer bounds, so Bellman-Ford returns an integer retiming.
  • Registers are not minimized. The retiming that Bellman-Ford returns is one feasible point of the constraints. Another retiming with the same period can use fewer registers.

Variants and improvements

  • OPT2 with FEAS. Leiserson and Saxe also test a period cc with FEAS, which needs no constraint system. Start from r=0r = 0 and repeat V−1V - 1 times: compute the arrival time of each gate in GrG_r by longest paths in the DAG of edges with no register, and add 1 to r(v)r(v) for each gate whose arrival time is more than cc. If a retiming with period at most cc exists, the result has period at most cc. Each test takes O(VE)O(VE) time, so the binary search takes O(VElog⁡V)O(VE \log V) time after WW and DD are known.
  • Least registers. Minimum-area retiming adds a linear objective to the same constraints and solves the dual min-cost flow problem.
  • Fewer constraints. Shenoy and Rudell (1994) keep only the period constraints that matter and do not store WW and DD in full, which makes retiming of large netlists practical.
  • A cycle bound. A retiming does not change the register count w(C)w(C) of a cycle CC, and the w(C)w(C) registers cut the cycle into w(C)w(C) stretches with no register. So every legal retiming has a period of at least d(C)/w(C)d(C) / w(C), for every cycle CC. The largest such ratio is a cycle ratio problem, related to Karp's minimum mean cycle method, and it gives a quick lower bound before the search.

When to use it

Use retiming when the logic of a pipelined or sequential circuit is fixed and the registers are badly placed, for example after a pipeline was added by hand or after logic optimization changed the delays. It needs exact gate delays in the model; with wire delays and setup times, it gives an estimate that static timing analysis must confirm. Use minimum-area retiming when the period is good enough and the register count matters. When the registers must stay where they are, use clock skew scheduling.

Pitfalls

  • Initial states. A retiming keeps the behaviour after a start-up phase, but the new registers need an initial value. For a register moved forward through a gate, the new value is the gate applied to the old values. For a register moved backward, one must find inputs to the gate that give the old value, and such inputs may not exist. Touati and Brayton (1993) compute equivalent initial states and show when none exists.
  • Signs. With wr(e)=w(e)+r(v)−r(u)w_r(e) = w(e) + r(v) - r(u), a positive r(v)r(v) moves registers from the outputs of vv to its inputs. Mixing this with the opposite convention flips every constraint.
  • The host. The host vertex must have r(h)=0r(h) = 0, or the retiming adds registers at the inputs and outputs and changes the latency that the outside world sees.
  • Cycles without registers. A cycle with no register has no finite period. The input must be checked before the search.
  • Fanout. Adding 1 to r(v)r(v) takes one register off each edge out of vv and puts one on each edge into vv. A gate with kk fanout edges has kk edge registers after a forward move, but the hardware can share them as one chain. So the sum of wr(e)w_r(e) is not the hardware count. Minimum-area retiming shows how to count shared registers.

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.

retiming.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/retiming/. The authors are listed in prov/9JAVQE.jsonl.

"""Leiserson-Saxe retiming for the least clock period.

A circuit is a graph with vertices 0 .. n-1. Vertex v is a gate with an
integer delay d[v] >= 0. An edge (u, v, w) is a wire from u to v that
passes through w >= 0 registers. Vertex 0 is the host: it stands for the
outside world, has delay 0 and keeps r(0) = 0. Every cycle must hold at
least one register.

A retiming is an integer map r. The retimed edge weight is
w_r(e) = w(e) + r(v) - r(u). The retiming is legal when every w_r(e) >= 0.
"""

from typing import Optional

Edge = tuple[int, int, int]


def retimed(edges: list[Edge], r: list[int]) -> list[Edge]:
    """The edges after the retiming r."""
    return [(u, v, w + r[v] - r[u]) for (u, v, w) in edges]


def is_legal(edges: list[Edge], r: list[int]) -> bool:
    return all(w + r[v] - r[u] >= 0 for (u, v, w) in edges)


def clock_period(n: int, d: list[int], edges: list[Edge]) -> int:
    """The largest delay of a path with no register, the period of the circuit.

    Raises ValueError if some cycle has no register."""
    succ: list[list[int]] = [[] for _ in range(n)]
    indeg = [0] * n
    for (u, v, w) in edges:
        if w == 0:
            succ[u].append(v)
            indeg[v] += 1
    arrive = list(d)  # arrive[v]: the largest delay of a zero-register path ending at v
    queue = [v for v in range(n) if indeg[v] == 0]
    seen = 0
    while queue:
        u = queue.pop()
        seen += 1
        for v in succ[u]:
            arrive[v] = max(arrive[v], arrive[u] + d[v])
            indeg[v] -= 1
            if indeg[v] == 0:
                queue.append(v)
    if seen < n:
        raise ValueError("a cycle has no register")
    return max(arrive) if n else 0


def wd_matrices(n: int, d: list[int], edges: list[Edge]) -> tuple[list[list[Optional[int]]], list[list[Optional[int]]]]:
    """W[u][v] is the fewest registers on a path from u to v. D[u][v] is the
    largest delay of such a path, counting d[u] and d[v]. None if v is not
    reachable from u.

    Floyd-Warshall on the pairs (w(e), -d(u)), compared in lexicographic
    order. The empty path gives W[v][v] = 0 and D[v][v] = d[v]."""
    inf = None
    best: list[list[Optional[tuple[int, int]]]] = [[inf] * n for _ in range(n)]  # @line L1
    for v in range(n):
        best[v][v] = (0, 0)
    for (u, v, w) in edges:
        cand = (w, -d[u])
        if u != v and (best[u][v] is None or cand < best[u][v]):
            best[u][v] = cand
    for k in range(n):
        bk = best[k]
        for i in range(n):
            bik = best[i][k]
            if bik is None:
                continue
            bi = best[i]
            for j in range(n):
                bkj = bk[j]
                if bkj is None:
                    continue
                cand = (bik[0] + bkj[0], bik[1] + bkj[1])
                if bi[j] is None or cand < bi[j]:
                    bi[j] = cand
    W: list[list[Optional[int]]] = [[None] * n for _ in range(n)]  # @line L2
    D: list[list[Optional[int]]] = [[None] * n for _ in range(n)]
    for u in range(n):
        for v in range(n):
            if best[u][v] is not None:
                W[u][v] = best[u][v][0]
                D[u][v] = d[v] - best[u][v][1]
    return W, D


def solve_difference_constraints(n: int, cons: list[tuple[int, int, int]]) -> Optional[list[int]]:
    """Bellman-Ford for r(u) - r(v) <= b, each given as (u, v, b).

    Returns an integer solution with r[0] = 0, or None if a negative cycle
    makes the system infeasible."""
    dist = [0] * n  # a virtual source with an edge of weight 0 to each vertex
    for _ in range(n):
        changed = False
        for (u, v, b) in cons:  # the constraint is the edge v -> u of weight b
            if dist[v] + b < dist[u]:
                dist[u] = dist[v] + b
                changed = True
        if not changed:
            return [x - dist[0] for x in dist]
    return None


def period_constraints(n: int, edges: list[Edge], W, D, c: int) -> list[tuple[int, int, int]]:
    """The constraints of Leiserson and Saxe for a period of at most c."""
    cons = [(u, v, w) for (u, v, w) in edges]  # @line L7
    for u in range(n):
        for v in range(n):
            if D[u][v] is not None and D[u][v] > c:
                cons.append((u, v, W[u][v] - 1))  # @line L8
    return cons


def min_period_retiming(n: int, d: list[int], edges: list[Edge]) -> tuple[int, list[int]]:
    """OPT1: the least clock period over all legal retimings, and a retiming
    that reaches it. Binary search over the sorted values of D, with one
    Bellman-Ford test per probe."""
    clock_period(n, d, edges)  # checks that every cycle has a register
    W, D = wd_matrices(n, d, edges)
    values = sorted({D[u][v] for u in range(n) for v in range(n) if D[u][v] is not None})  # @line L3
    lo, hi = 0, len(values) - 1  # @line L4: the largest value is met by r = 0
    best = [0] * n
    while lo < hi:  # @line L5
        mid = (lo + hi) // 2  # @line L6
        r = solve_difference_constraints(n, period_constraints(n, edges, W, D, values[mid]))  # @line L9
        if r is None:
            lo = mid + 1  # @line L10
        else:
            hi, best = mid, r  # @line L11
    return values[lo], best  # @line L12


def feas(n: int, d: list[int], edges: list[Edge], c: int) -> Optional[list[int]]:
    """FEAS: a legal retiming with period at most c, or None.

    Repeat n - 1 times: compute the arrival time of each vertex in the
    retimed circuit, and add 1 to r(v) for each v whose arrival time is more
    than c. If the result still has a period above c, no legal retiming
    reaches c, and the function returns None."""
    r = [0] * n
    for _ in range(n - 1):
        arrive = _arrivals(n, d, retimed(edges, r))
        for v in range(n):
            if arrive[v] > c:
                r[v] += 1
    shifted = [x - r[0] for x in r]
    er = retimed(edges, shifted)
    if all(w >= 0 for (_, _, w) in er) and clock_period(n, d, er) <= c:
        return shifted
    return None


def _arrivals(n: int, d: list[int], edges: list[Edge]) -> list[int]:
    succ: list[list[int]] = [[] for _ in range(n)]
    indeg = [0] * n
    for (u, v, w) in edges:
        if w == 0:
            succ[u].append(v)
            indeg[v] += 1
    arrive = list(d)
    queue = [v for v in range(n) if indeg[v] == 0]
    while queue:
        u = queue.pop()
        for v in succ[u]:
            arrive[v] = max(arrive[v], arrive[u] + d[v])
            indeg[v] -= 1
            if indeg[v] == 0:
                queue.append(v)
    return arrive
test_retiming.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/retiming/. The authors are listed in prov/9JAVQE.jsonl.

import itertools
import random

from retiming import (
    clock_period,
    feas,
    is_legal,
    min_period_retiming,
    period_constraints,
    retimed,
    wd_matrices,
)

# The correlator of the page: host 0, comparators 1 to 4 (delay 3), adders 5 to 7 (delay 7).
N = 8
DELAY = [0, 3, 3, 3, 3, 7, 7, 7]
EDGES = [(0, 1, 1), (1, 2, 1), (2, 3, 1), (3, 4, 1), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 0, 0),
         (3, 5, 0), (2, 6, 0), (1, 7, 0)]


def random_circuit(rng: random.Random, n: int):
    """A strongly connected circuit with no cycle free of registers."""
    while True:
        d = [0] + [rng.randint(1, 5) for _ in range(n - 1)]
        edges = [(i, (i + 1) % n, rng.choice([0, 1, 1])) for i in range(n)]
        for _ in range(rng.randint(1, n + 1)):
            u, v = rng.randrange(n), rng.randrange(n)
            if u != v:
                edges.append((u, v, rng.choice([0, 0, 1, 2])))
        try:
            clock_period(n, d, edges)
        except ValueError:
            continue
        if sum(w for (_, _, w) in edges) <= 8:
            return d, edges


def fewest_registers(n: int, edges, src: int) -> list:
    """Brute force: the fewest registers on a path from src to each vertex."""
    best = [None] * n
    best[src] = 0
    for _ in range(n):
        for (u, v, w) in edges:
            if best[u] is not None and (best[v] is None or best[u] + w < best[v]):
                best[v] = best[u] + w
    return best


def all_legal_retimings(n: int, edges):
    """Every legal retiming with r(0) = 0. A legal r has -W(0, v) <= r(v) <= W(v, 0),
    so the box below holds all of them."""
    down = fewest_registers(n, edges, 0)
    up = [fewest_registers(n, edges, v)[0] for v in range(n)]
    ranges = [range(-down[v], up[v] + 1) for v in range(1, n)]
    for t in itertools.product(*ranges):
        r = [0, *t]
        if is_legal(edges, r):
            yield r


def simple_paths(edges, d, u: int) -> list:
    """Every simple path from u, as (last vertex, registers, delay). A path of
    fewest registers is simple, since each cycle has a register."""
    out: list = []

    def walk(x, seen, w, dl):
        out.append((x, w, dl))
        for (a, b, ww) in edges:
            if a == x and b not in seen:
                walk(b, seen | {b}, w + ww, dl + d[b])

    walk(u, {u}, 0, d[u])
    return out


def test_correlator() -> None:
    assert clock_period(N, DELAY, EDGES) == 24
    c, r = min_period_retiming(N, DELAY, EDGES)
    assert c == 13
    assert is_legal(EDGES, r) and r[0] == 0
    assert clock_period(N, DELAY, retimed(EDGES, r)) == 13
    assert feas(N, DELAY, EDGES, 12) is None
    r13 = feas(N, DELAY, EDGES, 13)
    assert r13 is not None and clock_period(N, DELAY, retimed(EDGES, r13)) <= 13


def test_wd_against_paths() -> None:
    rng = random.Random(4101)
    for _ in range(40):
        n = rng.randint(3, 6)
        d, edges = random_circuit(rng, n)
        W, D = wd_matrices(n, d, edges)
        for u in range(n):
            paths = simple_paths(edges, d, u)
            for v in range(n):
                here = [(w, dl) for (x, w, dl) in paths if x == v]
                wmin = min(w for (w, _) in here)
                assert W[u][v] == wmin
                assert D[u][v] == max(dl for (w, dl) in here if w == wmin)


def test_constraints_match_period() -> None:
    """Leiserson and Saxe, Theorem 7: a legal r has period at most c exactly
    when it meets the constraints, for every c."""
    rng = random.Random(4102)
    for _ in range(30):
        n = rng.randint(3, 6)
        d, edges = random_circuit(rng, n)
        W, D = wd_matrices(n, d, edges)
        values = sorted({x for row in D for x in row if x is not None})
        for r in all_legal_retimings(n, edges):
            p = clock_period(n, d, retimed(edges, r))
            for c in values:
                cons = period_constraints(n, edges, W, D, c)
                meets = all(r[u] - r[v] <= b for (u, v, b) in cons)
                assert meets == (p <= c)


def test_min_period_against_bruteforce() -> None:
    rng = random.Random(4103)
    improved = 0
    for _ in range(200):
        n = rng.randint(3, 6)
        d, edges = random_circuit(rng, n)
        improved += min_period_retiming(n, d, edges)[0] < clock_period(n, d, edges)
        periods = {}
        for r in all_legal_retimings(n, edges):
            periods[tuple(r)] = clock_period(n, d, retimed(edges, r))
        best = min(periods.values())
        c, r = min_period_retiming(n, d, edges)
        assert c == best
        assert is_legal(edges, r) and r[0] == 0
        assert clock_period(n, d, retimed(edges, r)) == best
        W, D = wd_matrices(n, d, edges)
        for c in sorted({x for row in D for x in row if x is not None}):
            exists = any(p <= c for p in periods.values())
            got = feas(n, d, edges, c)
            assert (got is not None) == exists
            if got is not None:
                assert is_legal(edges, got) and clock_period(n, d, retimed(edges, got)) <= c
    assert improved >= 50  # the instances are not all trivial


def test_zero_register_cycle_rejected() -> None:
    try:
        min_period_retiming(2, [0, 1], [(0, 1, 0), (1, 0, 0)])
    except ValueError:
        return
    raise AssertionError("a cycle with no register must be rejected")

History

Leiserson, Rose and Saxe presented retiming at the Third Caltech Conference on VLSI in 1983. The journal version by Leiserson and Saxe appeared in Algorithmica in 1991, with the W and D matrices, the characterization of legal retimings of period at most cc, the algorithms OPT1, OPT2 and FEAS, and the reduction of the least register count to a min-cost flow dual. Touati and Brayton (1993) treated the initial states of retimed circuits, and Shenoy and Rudell (1994) made the method practical for large netlists.

References

  1. Charles E. Leiserson and James B. Saxe, Retiming synchronous circuitry, Algorithmica 6(1-6), 5 to 35, 1991, the circuit graph, the W and D matrices, the theorem that characterizes legal retimings of period at most c, and the algorithms OPT1, OPT2 and FEAS
  2. Optimizing synchronous circuitry by retiming, the first statement of retiming and of the minimum period problem (general locator)
  3. Computing the initial states of retimed circuits, equivalent initial states after retiming, and the case where a backward move has no equivalent state
  4. Efficient implementation of retiming, the pruning of the period constraints for large circuits (general locator)
  5. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 9, Sequential Logic Optimization (the sections on retiming)

Where this leads

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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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
  • a scene preset for the example