Algorithm Search⌘K

Algorithmresearch

Thermal-driven 3D floorplanning

Also called Cong-Wei-Zhang 3D floorplanning.

Cong, Wei and Zhang's 3D floorplanner that anneals the CBA representation, a TCG per layer plus buckets, with a cost that includes the peak temperature from a thermal model.

Time
O(M (n^2 + p + g^2 L + n g^2)) annealingO(n^2 + p + g^2 L + n g^2) one move with the closed-form model
Space
O(n^2 + p + g^2 L) total
Where
L = the number of device layers; M = the number of moves of the annealing; g = the number of tiles on each side of the thermal grid; n = the number of blocks; p = the number of pins
Properties
randomizednot exactiterative
Origin
Jason Cong, Jie Wei, Yan Zhang, 2004

Thermal-driven 3D floorplanning is the method of Cong, Wei and Zhang (ICCAD 2004) for placing the blocks of a block-level 3D IC, a topic of 3D integration in EDA. Each block gets a device layer and a place in that layer. The goal is a small footprint, short wires and few interlayer vias, with the peak temperature kept low. The method is simulated annealing over a representation called CBA, combined bucket and 2D array: a 2D floorplan for each layer, written as a transitive closure graph (TCG), and a grid of buckets over the stack that records which blocks of different layers lie above one another. The buckets make z-neighbor moves possible, which move a block to a nearby place in another layer. The cost includes the peak temperature from a thermal model. A closed-form model, CBA-T-Fast, gives each layer a weight that grows with its distance from the heat sink, so the search puts hot blocks next to the sink.

In plain words

You have a set of rectangular blocks and a few stacked layers of silicon, with the heat sink under the bottom layer. You want to place every block on some layer, with no two blocks of one layer overlapping, so that the stack is small, connected blocks are close, few connections go between layers, and nothing gets too hot.

Heat leaves through the bottom. A hot block on the top layer must push its heat through every layer below it, so it gets much hotter than the same block on the bottom layer. The method tries many small changes to the floorplan, such as swapping two blocks or moving one to a nearby spot in another layer, and keeps changes that make a mix of size, wires, vias and temperature better, plus some worse ones early on so it does not get stuck.

The problem

Input. A set of nn rectangular blocks, block bib_i with width wiw_i, height hih_i and a fixed power density qiq_i; each block may rotate. A set of nets over the blocks. A number of device layers LL (the paper uses 4), with layer 1 next to the heat sink.

Output. For each block a layer lil_i and a lower-left corner (xi,yi)(x_i, y_i), with no two blocks of one layer overlapping.

Goal. The paper minimizes chip area, wirelength and the number of interlayer vias, under a limit T0T_0 on the peak temperature. The chip area is the largest area among the layers. An interlayer via goes through a device layer, and at that time its pitch was about 25 µm, against below 0.5 µm for a via between metal layers, so vias are costly. The bottom of the stack is held at room temperature, 27 °C, and the sides and top are insulated. The problem contains 2D floorplanning, which is NP-hard, so the method is a heuristic.

The algorithm

The cost of a floorplan FF (Equation 1 of the paper) is

cost(F)=α⋅nwl+β⋅narea+γ⋅nvc+δ⋅CT,\mathrm{cost}(F) = \alpha \cdot \mathrm{nwl} + \beta \cdot \mathrm{narea} + \gamma \cdot \mathrm{nvc} + \delta \cdot C_T,

where nwl, narea and nvc are the wirelength, the chip area and the number of interlayer vias, each normalized, and CTC_T is a cost of the peak temperature TT. In the paper, CTC_T is a function of TT in three tiers that rises steeply past the limit T0T_0.

  1. THERMAL-3D-FLOORPLAN(blocks, nets, L, weights)
  2. 1put the blocks on the layers, build a 2D floorplan of each layer, and pack it
  3. 2compute the cost of the floorplan, with the temperature from the thermal model
  4. 3for each temperature τ of the annealing schedule:
  5. 4repeat a fixed number of times:
  6. 5perturb: rotation, swap, reverse, move, interlayer swap, z-neighbor swap or z-neighbor move; global moves more often while τ is high, local moves as τ falls
  7. 6pack the changed layers, update the buckets, and compute the new cost
  8. 7accept the new floorplan if its cost is lower, or else with probability exp(−Δ/τ)
  9. 8keep the best floorplan seen
  10. 9return the best floorplan

CBA. Each layer is a 2D floorplan in its own TCG, and a packing gives the places in that layer. Over the stack lies a grid of buckets. Bucket ii holds the set IB(i)IB(i) of blocks of any layer that meet it, and block jj holds the set IBT(j)IBT(j) of buckets it meets. After every move only the moved blocks are updated, and every 20 moves or so all buckets are built again, since the buckets only point to blocks that are likely close.

The seven moves. Rotation, swap (two blocks of one layer), reverse (the relation of two blocks in one layer) and move (a block from one side of another to a different side) are the moves of TCG, inside one layer. Interlayer swap exchanges two random blocks of different layers. The z-axis neighbor of block jj is the block kk of another layer, among the blocks that share a bucket with jj, of least cost α∣Ak−Aj∣+β(∣xk−xj∣+∣yk−yj∣)\alpha |A_k - A_j| + \beta (|x_k - x_j| + |y_k - y_j|): close and of similar area. Z-neighbor swap exchanges jj with it. Z-neighbor move takes jj out of its layer and puts it next to kk, to its right or above it, in kk's layer. Rotation, swap and interlayer swap are global and are used more at high temperature; the others change the floorplan locally and are used more as it cools.

Thermal models. The stack is cut into a grid of tiles, 10×1010 \times 10 in the paper, and the power of a tile in a layer is the sum of the power densities times the overlap areas of the blocks that meet it.

  • CBA-T uses a compact resistive thermal model: one node per tile per layer, lateral resistors between neighbor tiles in a layer, a vertical resistor RiR_i per layer and RbR_b for the bottom, with values from finite-element simulation. The tile powers are current sources, and the temperatures are the node voltages. The matrix does not change between floorplans, so its LU factors are reused. To save time, the temperature is computed only after moves that change it much: global moves and moves between layers.
  • CBA-T-Fast looks at each tile stack alone and uses only vertical heat flow. With the sink at room temperature TsT_s, the top node of a stack has
Ttop=Ts+Rb∑i=1LPi+∑i=1LPi∑j=1iRj,T_{\mathrm{top}} = T_s + R_b \sum_{i=1}^{L} P_i + \sum_{i=1}^{L} P_i \sum_{j=1}^{i} R_j,

which is Equation 3 of the paper written with the layers counted from the sink. The power of layer ii is multiplied by the resistances of all layers up to ii, so a block costs more the farther it is from the sink. The peak is the largest TtopT_{\mathrm{top}} over the tile stacks. For the spread within a layer, the paper adds the largest difference of temperature among the tiles of each layer, normalized, as a weight on the peak.

  • CBA-T-Hybrid uses the closed form during the annealing and the resistive network 20 times at each annealing temperature.

After the annealing. White space is added around each block for the interlayer vias, in proportion to its number of connections, and more around hot blocks for thermal vias; then the layers are packed again with the TCG relations kept.

The code. The implementation is a small model of the method. It uses a sequence pair for each layer in place of a TCG, which the paper allows ("any 2D floorplan representation can be used"); swap, reverse and move are the sequence pair versions. It builds the buckets again after every move, on a 3×33 \times 3 grid. When a z-neighbor move finds no near block in another layer, for example because the other layers are empty, it moves the block to a random place on another layer; without this, a layer that becomes empty can never be filled again. With two layers, every z-neighbor move then takes the block to the other layer. The area is that of the bounding box of all layers, the via count of a net is its largest layer minus its smallest, and each term is divided by its value at the start. The thermal model is a toy: it is CBA-T-Fast with the same area-specific resistances in every tile, the tile power taken as a mean power density, no lateral flow, no temperature spread term, and resistances that are not calibrated to any process. The cost uses the peak rise itself, not the three-tier function.

Example

Take two blocks of 2×22 \times 2, one hot with power density 5 and one cool with power density 1, two layers, and the toy model with Rb=0.5R_b = 0.5 and R1=R2=1R_1 = R_2 = 1 per unit area.

floorplan area peak rise above the sink
stacked, hot block on layer 1 (next to the sink) 4 0.5⋅6+1⋅6+1⋅1=100.5 \cdot 6 + 1 \cdot 6 + 1 \cdot 1 = 10
stacked, hot block on layer 2 4 0.5⋅6+1⋅6+1⋅5=140.5 \cdot 6 + 1 \cdot 6 + 1 \cdot 5 = 14
side by side on layer 1 8 (0.5+1)⋅5=7.5(0.5 + 1) \cdot 5 = 7.5

Stacking halves the area. With the blocks stacked, the hot block next to the sink is 4 units cooler, because its power passes through RbR_b and R1R_1 only, while the power of the top layer passes through R2R_2 as well. Spreading the blocks side by side is cooler still, but doubles the area. The weights β\beta and δ\delta decide which floorplan wins. The test file checks the first two rows.

Correctness

There is no optimality claim to prove: the method is a heuristic for an NP-hard problem, and Cong, Wei and Zhang give none. The proof file proves what the method does guarantee. Every move keeps each block on exactly one layer and in both orders of that layer's pair, and every packing of a sequence pair has no overlap, so every floorplan seen is legal. The returned floorplan is the best one seen, so its cost is at most the cost of the start. The closed form of CBA-T-Fast is exactly the top temperature of a chain of resistors with the tile powers as sources, and in a chain the top node is the hottest one. With two layers and the empty-layer rule of the code, every floorplan can be reached from every other one by moves, so the move set does not shut the search out of the optimum. That is not a promise that a finite run finds it.

Proof: What thermal-driven 3D floorplanning guaranteesfull

The method is a heuristic, and there is no claim that it finds an optimal floorplan. This file proves the guarantees it does have, for the code of this page: every floorplan it sees is legal, its result is no worse than its start, the closed-form thermal model is exact for the model it stands for, and, with two layers, its moves can reach every floorplan. A floorplan is a list of layers, each with a sequence pair (Γ+,Γ−)(\Gamma_+, \Gamma_-) of the blocks on it, and a rotation flag per block. It is well formed if each block is in exactly one layer and the two orders of each layer hold the same blocks.

Lemma 1 (moves keep a floorplan well formed). If FF is well formed, so is every floorplan that PERTURB returns.

Proof. Look at each move. Rotation changes only a flag. Swap and interlayer swap exchange the names aa and bb in every sequence; a bijection on names keeps each block in exactly one layer, and each layer's two orders still hold the same set, with aa and bb exchanged in both. Reverse exchanges two entries of Γ+\Gamma_+ only, which does not change the set it holds. Move removes bb from both orders of its layer and inserts it again into both. Z-neighbor swap is a swap. Z-neighbor move removes bb from both orders of its layer and inserts it into both orders of one other layer: next to zz, or, when there is no zz, at random places of a random other layer. In every case, each block is in exactly one layer and both orders of each layer hold the same set. ∎

Lemma 2 (packing has no overlap). For a well-formed layer, the corners that PACK-LAYER computes give no two blocks of the layer a common interior point.

Proof. Take two blocks a≠ba \ne b of the layer. Exactly one of these holds: aa is before bb in both orders, bb is before aa in both, aa is before bb in Γ−\Gamma_- only, or bb is before aa in Γ−\Gamma_- only. In the first case PACK-LAYER takes the maximum over all a′a' before bb in both orders, so xb≥xa+wax_b \ge x_a + w_a and aa is left of bb, with no common interior point; the second case is the same with the names exchanged. If aa is before bb in Γ−\Gamma_- and after bb in Γ+\Gamma_+, then aa is among the blocks before bb in Γ−\Gamma_- that come after bb in Γ+\Gamma_+, so yb≥ya+hay_b \ge y_a + h_a and aa is below bb; the last case is the same with the names exchanged. The loops visit blocks in the order of Γ+\Gamma_+ for xx and of Γ−\Gamma_- for yy, so xax_a and yay_a are final when they are used. ∎

Theorem 3 (every floorplan seen is legal). Every floorplan that the annealing builds has each block on one layer and no overlap within a layer.

Proof. Line L1 puts each block in one layer and copies each Γ+\Gamma_+ into Γ−\Gamma_- before shuffling, so the start is well formed. By Lemma 1 and induction on the moves, so is every floorplan after it, and by Lemma 2 none has an overlap. ∎

Lemma 4 (the result is no worse than the start). THERMAL-3D-FLOORPLAN returns a floorplan whose cost is at most the cost of the start, and the returned cost is the cost of the returned floorplan.

Proof. Line L2 sets the best floorplan to the start and the best cost to its cost. Line L8 replaces both only by a floorplan and its own cost, and only when that cost is lower. So the best cost never rises and always belongs to the best floorplan. ∎

Lemma 5 (the closed form). Take one tile stack with nodes 1,…,L1, \dots, L from the sink up, joined by a chain of resistors: RbR_b from the sink to a base node, R1R_1 from the base node to node 1, and RjR_j from node j−1j-1 to node jj for j≥2j \ge 2. Put a heat source Pi≥0P_i \ge 0 at node ii, the sink at TsT_s, and no other path for heat. Then in steady state the top node has

TL=Ts+Rb∑i=1LPi+∑i=1LPi∑j=1iRj,T_L = T_s + R_b \sum_{i=1}^{L} P_i + \sum_{i=1}^{L} P_i \sum_{j=1}^{i} R_j,

and TLT_L is the largest temperature in the stack.

Proof. In steady state the heat that enters a node equals the heat that leaves it. The only path to the sink goes down the chain, so the heat that flows through RjR_j is the heat made at node jj and above, ∑i≥jPi\sum_{i \ge j} P_i, and the heat through RbR_b is ∑iPi\sum_i P_i. Each resistor raises the temperature by its resistance times the heat through it. Summing from the sink up,

TL=Ts+Rb∑iPi+∑j=1LRj∑i≥jPi.T_L = T_s + R_b \sum_{i} P_i + \sum_{j=1}^{L} R_j \sum_{i \ge j} P_i.

Exchanging the order of the double sum, the pair (i,j)(i, j) with j≤ij \le i appears once on each side, which gives the formula. Every term added on the way up is a resistance times a sum of powers, which is not negative, so the temperature does not fall from one node to the next and the top node is the hottest. ∎

Lemma 5 is what STACK-TOP-TEMPERATURE computes, with resistances per unit area and the mean power density of the tile, so the code computes the peak of the model exactly. It says nothing about how close the model is to a real chip: it leaves out lateral flow, which spreads heat from a hot tile to its cooler neighbors, so it overstates the peak of small hot blocks.

Corollary 6 (hot blocks belong next to the sink). In one tile stack, exchanging the powers PiP_i and PkP_k of two layers i<ki < k changes TLT_L by (Pi−Pk)∑j=i+1kRj(P_i - P_k) \sum_{j=i+1}^{k} R_j. So putting the larger power on the lower layer never raises the peak of that stack.

Proof. Write Si=∑j≤iRjS_i = \sum_{j \le i} R_j. In Lemma 5 the power of layer ii has the weight SiS_i, and the other terms do not change. Before the exchange the two layers add PiSi+PkSkP_i S_i + P_k S_k; after it they add PkSi+PiSkP_k S_i + P_i S_k. The change is PkSi+PiSk−PiSi−PkSk=(Pi−Pk)(Sk−Si)=(Pi−Pk)∑j=i+1kRjP_k S_i + P_i S_k - P_i S_i - P_k S_k = (P_i - P_k)(S_k - S_i) = (P_i - P_k) \sum_{j=i+1}^{k} R_j. If the larger power was on top, Pk≥PiP_k \ge P_i, this is at most 0, which is the claim. ∎

In the example of the page, P=5P = 5 and 11, R2=1R_2 = 1, so the hot block next to the sink is cooler by (5−1)⋅1=4(5 - 1) \cdot 1 = 4.

Lemma 7 (reachability with two layers). With two layers, from any well-formed floorplan the moves of the code can reach any other well-formed floorplan with the same blocks.

Proof. Let FF be the current floorplan and GG the target. First fix the layers. For each block whose layer differs in FF and GG, take a z-neighbor move of that block. If it has a z-neighbor zz, the move puts it in the layer of zz, which is not its own and so is the other layer; if it has none, the move puts it on a random other layer, which with two layers is again the other one. So each such move changes the layer of one block, and after these moves every block is on its layer in GG. Next fix the orders of each layer with m≥2m \ge 2 blocks (with one block there is only one sequence pair). A move of block bb removes it from both orders and inserts it at any place in each, chosen independently; inserting it at its old place in one order changes only the other. So a move can put any block at any place of Γ+\Gamma_+ alone, or of Γ−\Gamma_- alone. Take the blocks in reverse order of GG's Γ+\Gamma_+ and move each to the front of Γ+\Gamma_+, keeping its place in Γ−\Gamma_-; then Γ+\Gamma_+ is GG's. Do the same for Γ−\Gamma_-, keeping the places in Γ+\Gamma_+. Last, rotate each block whose flag differs. Each step is a move the code can choose with positive probability. ∎

With three or more layers the lemma can fail: a z-neighbor move puts a block on the layer of its z-neighbor, so an empty layer is filled only when some block has no near block on any other layer. The tests use two layers.

What is not proved. Nothing here bounds how far the result is from an optimal floorplan, or how many moves the annealing needs. The test file measures the gap against an exhaustive search on tiny instances, and the page reports the numbers under "What is measured".

Complexity

Packing one layer with mm blocks takes O(m2)O(m^2) for a sequence pair or TCG by longest paths (O(mlog⁡m)O(m \log m) with the weighted longest common subsequence). The wirelength and via count take O(p)O(p) for pp pins. The closed-form thermal model spreads each block over the tiles it meets, O(ng2)O(n g^2) at most, and sums each of the g2g^2 stacks in O(L)O(L). So a move costs O(n2+p+g2L+ng2)O(n^2 + p + g^2 L + n g^2), and the annealing with MM moves costs MM times that. CBA-T solves the resistive network of g2Lg^2 L nodes; with a reused LU factorization of a dense matrix, each solve is O(g4L2)O(g^4 L^2), which is why the paper computes it only after some moves. The paper reports that its 25 by 25 by 4 network takes a few milliseconds per solve.

Properties

What is proved. Every floorplan seen is legal (no overlap within a layer, each block on one layer), the result is no worse than the start, the closed form is exact for a vertical chain of resistors and its top node is the hottest, and with two layers the moves of the code can reach every floorplan.

What is cited. Cong, Wei and Zhang (2004, Section 5) test on MCNC and GSRC benchmarks with four layers, and give each block a random power density in a fixed range of W/m². Without the thermal term, CBA gives 29% less wirelength and 7% less area than the multi-layer floorplanner of Shiu, Ravichandran, Easwar and Lim (2004), and 3% less wirelength and 5% less area than an array of TCGs without the z-neighbor moves (on GSRC, 5.5% less wirelength). CBA-T lowers the peak temperature by 56% on average, at 21% more area, about the same wirelength and via count, and 9 times the run time. CBA-T-Fast lowers it by 40% at 2 times the run time, and CBA-T-Hybrid by 50% at 3 times. A finite-element check of ami33 gives a peak of 587.2 K without the thermal term and 425.1 K with it.

What is measured. The tests use the code and its toy model, with two layers and a 4×44 \times 4 tile grid. On 15 random instances of 3 blocks (seed 3) and 2 of 4 blocks (seed 4), the annealing reaches the cost of an exhaustive search over every layer assignment, sequence pair and rotation, on all of them; a longer run with 30 and 6 instances gave the same. On 10 random instances of 8 blocks (seed 8), a thermal weight of 3 against 0 lowers the mean peak rise from 12.98 to 5.94 (54%) and raises the mean area from 13.3 to 18.3 (38%). These numbers come from a toy model on random blocks; they show the trend, not the values of a real chip.

Variants and improvements

  • Other representations. The layers can use a sequence pair, a B*-tree or any 2D representation, as the paper says. "True 3D" representations such as the 3D TCG or the sequence triple add the third axis but, as the paper argues, carry more information than a few discrete layers need.
  • Thermal vias. Later work inserts thermal vias in white space to lower the vertical resistance of hot stacks, either after floorplanning or inside it.
  • TSV-aware floorplanning. With TSVs, the vias take area and need keep-out zones, so later floorplanners place the TSVs and count their area, not only their number.
  • Gate-level 3D. For monolithic 3D, the layer of each cell is set by tier partitioning, as in Shrunk-2D, not by a block floorplanner.
  • Fast thermal analysis. Better compact models and model order reduction give accurate temperatures at a cost close to the closed form.

When to use it

Use it for block-level 3D integration with a few layers and tens to a few hundred blocks, when heat matters and the power of each block is known. Use the closed form or a hybrid inside the annealing and an accurate model at the end. For millions of cells, use a placer and a partitioner instead.

Pitfalls

  • Hot blocks on top. Without a thermal term, the search places blocks for area and wires only, and a hot block on the top layer can be far hotter than the same block next to the sink.
  • Area against heat. Lowering the peak usually spreads hot blocks apart and raises the area; the paper reports 21% more area for a 56% lower peak. The weights must reflect what the design can afford.
  • A closed form without lateral flow. It ignores heat that spreads within a layer, so it misjudges small hot blocks next to cool ones. Check the final floorplan with an accurate model.
  • Empty layers. If the only moves between layers are swaps and moves to a neighbor in another layer, a layer that becomes empty can never be filled again.
  • Kelvin and Celsius. The finite-element results of the paper are in kelvin, while its tables are in degrees Celsius. A percentage of a temperature depends on the scale, so compare temperature rises.

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.

thermal_driven_3d_floorplanning.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/thermal-driven-3d-floorplanning/. The authors are listed in prov/RF40PK.jsonl.

"""Thermal-driven 3D floorplanning by simulated annealing, after Cong, Wei and Zhang.

A block is (w, h, q): width, height and power density. Blocks may rotate.
A net is a list of block indices. Layer 0 is next to the heat sink.

A floorplan keeps, for each layer, a sequence pair of the blocks on it, plus
a rotation flag per block. Cong, Wei and Zhang use a transitive closure
graph (TCG) for each layer and add a bucket structure over the stack; this
code uses a sequence pair for each layer, which the paper allows, and builds
the buckets again after every move instead of every 20 moves.

The cost is a * wl + b * area + c * vias + d * tmax, each term divided by
its value at the start. The thermal model is a TOY: the closed-form vertical
model of CBA-T-Fast on a g x g grid of tiles, with the same resistances in
every tile and no lateral heat flow. It is not a calibrated model.
"""

import math

SINK = 27.0


# ---------- sequence pair packing ----------

def pack_layer(gp, gm, dims):
    """Lower-left corners of the blocks of one sequence pair.

    a is left of b if a is before b in both orders, and a is below b if b
    is before a in gp and a is before b in gm.
    """
    pos_p = {b: i for i, b in enumerate(gp)}
    pos_m = {b: i for i, b in enumerate(gm)}
    x, y = {}, {}
    for b in gp:
        x[b] = 0.0
        for a in gp[:pos_p[b]]:
            if pos_m[a] < pos_m[b]:
                x[b] = max(x[b], x[a] + dims[a][0])
    for b in gm:
        y[b] = 0.0
        for a in gm[:pos_m[b]]:
            if pos_p[a] > pos_p[b]:
                y[b] = max(y[b], y[a] + dims[a][1])
    return x, y


class Floorplan:
    def __init__(self, layers, rot):
        self.layers = layers  # list of (gp, gm)
        self.rot = rot

    def copy(self):
        return Floorplan([(list(p), list(m)) for p, m in self.layers], list(self.rot))


def dims_of(blocks, rot):
    return [(h, w) if r else (w, h) for (w, h, _), r in zip(blocks, rot)]


def realize(blocks, fp):
    """Return x, y, layer and dims of every block."""
    dims = dims_of(blocks, fp.rot)
    n = len(blocks)
    x, y, lay = [0.0] * n, [0.0] * n, [0] * n
    for k, (gp, gm) in enumerate(fp.layers):
        px, py = pack_layer(gp, gm, dims)
        for b in gp:
            x[b], y[b], lay[b] = px[b], py[b], k
    return x, y, lay, dims


# ---------- the terms of the cost ----------

def footprint(x, y, dims):
    return max(x[i] + dims[i][0] for i in range(len(x))), max(y[i] + dims[i][1] for i in range(len(y)))


def wirelength(x, y, dims, nets):
    total = 0.0
    for net in nets:
        cx = [x[i] + dims[i][0] / 2 for i in net]
        cy = [y[i] + dims[i][1] / 2 for i in net]
        total += max(cx) - min(cx) + max(cy) - min(cy)
    return total


def via_count(lay, nets):
    """Device layers crossed by the nets: max layer minus min layer, summed."""
    return sum(max(lay[i] for i in net) - min(lay[i] for i in net) for net in nets)


def tile_powers(blocks, x, y, lay, dims, n_layers, g):
    """Mean power density of each tile (layer, i, j).

    It is the sum over blocks of power density times overlap area, divided
    by the tile area. With resistances given per unit area (K area / W),
    the temperatures then do not depend on the size of the tiles.
    """
    W, H = footprint(x, y, dims)
    tw, th = W / g, H / g
    p = [[[0.0] * g for _ in range(g)] for _ in range(n_layers)]
    for b, (_, _, q) in enumerate(blocks):
        x0, x1, y0, y1 = x[b], x[b] + dims[b][0], y[b], y[b] + dims[b][1]
        for i in range(max(0, int(x0 / tw)), min(g, int(math.ceil(x1 / tw)))):
            ox = min(x1, (i + 1) * tw) - max(x0, i * tw)
            if ox <= 0:
                continue
            for j in range(max(0, int(y0 / th)), min(g, int(math.ceil(y1 / th)))):
                oy = min(y1, (j + 1) * th) - max(y0, j * th)
                if oy > 0:
                    p[lay[b]][i][j] += q * ox * oy / (tw * th)
    return p


def stack_top_temperature(powers, r_layers, r_base):
    """Closed form of one tile stack: Tsink + Rb * sum P + sum_i P_i * sum_{j <= i} R_j.

    Layer 0 is next to the sink. This is the top node of a chain of
    resistors, where resistor j carries the power of layers j and above.
    """
    t = SINK + r_base * sum(powers)
    acc = 0.0
    for p_i, r_i in zip(powers, r_layers):
        acc += r_i
        t += p_i * acc
    return t


def max_temperature(blocks, x, y, lay, dims, n_layers, g, r_layers, r_base):
    p = tile_powers(blocks, x, y, lay, dims, n_layers, g)
    return max(stack_top_temperature([p[k][i][j] for k in range(n_layers)], r_layers, r_base)
               for i in range(g) for j in range(g))


def terms(blocks, nets, fp, model):
    x, y, lay, dims = realize(blocks, fp)
    W, H = footprint(x, y, dims)
    t = max_temperature(blocks, x, y, lay, dims, len(fp.layers), *model)
    return W * H, wirelength(x, y, dims, nets), float(via_count(lay, nets)), t - SINK


def cost(blocks, nets, fp, model, weights, norm):
    vals = terms(blocks, nets, fp, model)
    return sum(w * v / max(nv, 1e-12) for w, v, nv in zip(weights, vals, norm))


# ---------- moves ----------

def z_neighbor(blocks, fp, j, alpha=1.0, beta=1.0, buckets=3):
    """Block on another layer that shares a bucket with j, of least cost
    alpha * |A_k - A_j| + beta * (|x_k - x_j| + |y_k - y_j|)."""
    x, y, lay, dims = realize(blocks, fp)
    W, H = footprint(x, y, dims)
    bw, bh = W / buckets, H / buckets

    def cells(b):
        i0, i1 = int(x[b] / bw), min(buckets - 1, int((x[b] + dims[b][0]) / bw - 1e-9))
        j0, j1 = int(y[b] / bh), min(buckets - 1, int((y[b] + dims[b][1]) / bh - 1e-9))
        return {(i, k) for i in range(i0, i1 + 1) for k in range(j0, j1 + 1)}

    mine = cells(j)
    best, best_c = None, None
    for k in range(len(blocks)):
        if lay[k] == lay[j] or not (cells(k) & mine):
            continue
        c = alpha * abs(dims[k][0] * dims[k][1] - dims[j][0] * dims[j][1]) + beta * (abs(x[k] - x[j]) + abs(y[k] - y[j]))
        if best_c is None or c < best_c:
            best, best_c = k, c
    return best


def layer_of(fp, b):
    for k, (gp, _) in enumerate(fp.layers):
        if b in gp:
            return k
    raise ValueError(b)


def swap_blocks(fp, a, b):
    for gp, gm in fp.layers:
        for seq in (gp, gm):
            for i, v in enumerate(seq):
                if v == a:
                    seq[i] = b
                elif v == b:
                    seq[i] = a


def perturb(blocks, fp, rng, p_global):
    """Return a new floorplan after one of the seven moves, and its name."""
    fp = fp.copy()
    n = len(blocks)
    if rng.random() < p_global:
        kind = rng.choice(["rotation", "swap", "interlayer swap"])
    else:
        kind = rng.choice(["reverse", "move", "z-neighbor swap", "z-neighbor move"])
    b = rng.randrange(n)
    k = layer_of(fp, b)
    gp, gm = fp.layers[k]
    if kind == "rotation":
        fp.rot[b] = not fp.rot[b]
    elif kind in ("swap", "reverse"):
        if len(gp) < 2:
            return fp, None
        a = rng.choice([v for v in gp if v != b])
        if kind == "swap":
            swap_blocks(fp, a, b)
        else:  # exchange the two blocks in gp only, which flips their relation
            i, j = gp.index(a), gp.index(b)
            gp[i], gp[j] = gp[j], gp[i]
    elif kind == "move":
        if len(gp) < 2:
            return fp, None
        for seq in (gp, gm):
            seq.remove(b)
            seq.insert(rng.randrange(len(seq) + 1), b)
    elif kind == "interlayer swap":
        others = [v for v in range(n) if layer_of(fp, v) != k]
        if not others:
            return fp, None
        swap_blocks(fp, b, rng.choice(others))
    else:
        z = z_neighbor(blocks, fp, b)
        if z is None and kind == "z-neighbor move" and len(fp.layers) > 1:
            # No block of another layer is near b, for example because the
            # other layers are empty: put b at a random place on another
            # layer, so that an empty layer can be filled again.
            k2 = rng.choice([i for i in range(len(fp.layers)) if i != k])
            gp.remove(b)
            gm.remove(b)
            for seq in fp.layers[k2]:
                seq.insert(rng.randrange(len(seq) + 1), b)
            return fp, kind
        if z is None:
            return fp, None
        if kind == "z-neighbor swap":
            swap_blocks(fp, b, z)
        else:  # z-neighbor move: put b next to z on z's layer, to its right or above it
            gp.remove(b)
            gm.remove(b)
            zp, zm = fp.layers[layer_of(fp, z)]
            if rng.random() < 0.5:
                zp.insert(zp.index(z) + 1, b)
                zm.insert(zm.index(z) + 1, b)
            else:
                zp.insert(zp.index(z), b)
                zm.insert(zm.index(z) + 1, b)
    return fp, kind


# ---------- the annealing ----------

def thermal_floorplan(blocks, nets, n_layers=2, weights=(1.0, 1.0, 1.0, 1.0),
                      model=(10, (1.0, 1.0), 0.5), seed=0, t0=None, t_stop=1e-3,
                      cooling=0.9, moves_per_t=None, norm=None):
    """Return the best floorplan, its cost and the four values that divide the terms."""
    import random
    rng = random.Random(seed)
    n = len(blocks)
    layers = [([], []) for _ in range(n_layers)]
    order = list(range(n))
    rng.shuffle(order)
    for i, b in enumerate(order):  # @line L1
        layers[i % n_layers][0].append(b)
    for gp, gm in layers:
        gm.extend(gp)
        rng.shuffle(gm)
    fp = Floorplan(layers, [False] * n)
    if norm is None:
        norm = terms(blocks, nets, fp, model)
    cur = cost(blocks, nets, fp, model, weights, norm)  # @line L2
    best, best_cost = fp, cur
    moves = moves_per_t or 20 * n
    if t0 is None:  # accept an average uphill move with probability 0.9 at the start
        ups = []
        for _ in range(40):
            new, kind = perturb(blocks, fp, rng, 0.5)
            if kind is not None:
                d = cost(blocks, nets, new, model, weights, norm) - cur
                if d > 0:
                    ups.append(d)
        t0 = (sum(ups) / len(ups) if ups else 1.0) / -math.log(0.9)
    t = t0
    while t > t_stop * t0:  # @line L3
        for _ in range(moves):  # @line L4
            new, kind = perturb(blocks, fp, rng, p_global=0.3 + 0.4 * t / t0)  # @line L5
            if kind is None:
                continue
            c = cost(blocks, nets, new, model, weights, norm)  # @line L6
            if c <= cur or rng.random() < math.exp(-(c - cur) / t):  # @line L7
                fp, cur = new, c
                if c < best_cost:  # @line L8
                    best, best_cost = new, c
        t *= cooling
    return best, best_cost, norm  # @line L9
test_thermal_driven_3d_floorplanning.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/thermal-driven-3d-floorplanning/. The authors are listed in prov/RF40PK.jsonl.

import itertools
import math
import random

from thermal_driven_3d_floorplanning import (
    SINK,
    Floorplan,
    cost,
    perturb,
    realize,
    stack_top_temperature,
    terms,
    thermal_floorplan,
)

MODEL = (4, (1.0, 1.0), 0.5)  # 4 x 4 tiles, r_1 = r_2 = 1, r_b = 0.5


def all_floorplans(n, n_layers):
    for assign in itertools.product(range(n_layers), repeat=n):
        groups = [[b for b in range(n) if assign[b] == k] for k in range(n_layers)]
        pairs = [[(list(p), list(m)) for p in itertools.permutations(g) for m in itertools.permutations(g)]
                 for g in groups]
        for combo in itertools.product(*pairs):
            for rot in itertools.product([False, True], repeat=n):
                yield Floorplan([(list(p), list(m)) for p, m in combo], list(rot))


def random_instance(rng, n):
    blocks = [(rng.choice([1.0, 2.0, 3.0]), rng.choice([1.0, 2.0]), rng.choice([0.1, 1.0, 5.0])) for _ in range(n)]
    nets = [rng.sample(range(n), 2) for _ in range(n)]
    return blocks, nets


def valid(blocks, fp):
    seen = []
    for gp, gm in fp.layers:
        assert sorted(gp) == sorted(gm)
        seen += gp
    assert sorted(seen) == list(range(len(blocks)))
    x, y, lay, dims = realize(blocks, fp)
    for a, b in itertools.combinations(range(len(blocks)), 2):
        if lay[a] == lay[b]:
            apart = (x[a] + dims[a][0] <= x[b] + 1e-9 or x[b] + dims[b][0] <= x[a] + 1e-9
                     or y[a] + dims[a][1] <= y[b] + 1e-9 or y[b] + dims[b][1] <= y[a] + 1e-9)
            assert apart
    return True


def test_closed_form_is_the_resistor_chain():
    rng = random.Random(11)
    for _ in range(200):
        L = rng.randint(1, 5)
        p = [rng.uniform(0, 3) for _ in range(L)]
        r = [rng.uniform(0.1, 2) for _ in range(L)]
        rb = rng.uniform(0.1, 1)
        t = SINK + rb * sum(p)  # the base carries all the power
        for i in range(L):
            t += r[i] * sum(p[i:])  # resistor i carries the power of layers i and above
        assert math.isclose(stack_top_temperature(p, r, rb), t)


def test_hot_block_next_to_the_sink_is_cooler():
    blocks = [(2.0, 2.0, 5.0), (2.0, 2.0, 1.0)]  # same size, one hot and one cool
    hot_low = Floorplan([([0], [0]), ([1], [1])], [False, False])
    hot_high = Floorplan([([1], [1]), ([0], [0])], [False, False])
    _, _, _, t_low = terms(blocks, [[0, 1]], hot_low, MODEL)
    _, _, _, t_high = terms(blocks, [[0, 1]], hot_high, MODEL)
    # rise = r_b (q_0 + q_1) + r_1 (q_0 + q_1) + r_2 q_top
    assert math.isclose(t_low, 0.5 * 6 + 1.0 * 6 + 1.0 * 1)
    assert math.isclose(t_high, 0.5 * 6 + 1.0 * 6 + 1.0 * 5)


def test_moves_keep_a_valid_floorplan():
    rng = random.Random(5)
    for _ in range(20):
        blocks, _ = random_instance(rng, rng.randint(2, 7))
        fp = Floorplan([(list(range(len(blocks))), list(range(len(blocks)))), ([], [])], [False] * len(blocks))
        for _ in range(100):
            new, kind = perturb(blocks, fp, rng, 0.5)
            if kind is not None:
                assert valid(blocks, new)
                fp = new


def test_annealing_against_exhaustive_optimum():
    rng = random.Random(3)
    hits3 = 0
    for _ in range(15):
        blocks, nets = random_instance(rng, 3)
        fp, c, norm = thermal_floorplan(blocks, nets, 2, (1, 1, 1, 1), MODEL, seed=1)
        assert valid(blocks, fp)
        assert math.isclose(c, cost(blocks, nets, fp, MODEL, (1, 1, 1, 1), norm))
        opt = min(cost(blocks, nets, f, MODEL, (1, 1, 1, 1), norm) for f in all_floorplans(3, 2))
        assert c >= opt - 1e-9
        hits3 += c <= opt + 1e-9
    assert hits3 == 15
    rng = random.Random(4)
    hits4 = 0
    for _ in range(2):
        blocks, nets = random_instance(rng, 4)
        fp, c, norm = thermal_floorplan(blocks, nets, 2, (1, 1, 1, 1), MODEL, seed=1)
        opt = min(cost(blocks, nets, f, MODEL, (1, 1, 1, 1), norm) for f in all_floorplans(4, 2))
        assert c >= opt - 1e-9
        hits4 += c <= opt + 1e-9
    assert hits4 == 2


def test_thermal_weight_lowers_the_peak():
    rng = random.Random(8)
    lower = 0
    for _ in range(3):
        blocks, nets = random_instance(rng, 5)
        a, _, _ = thermal_floorplan(blocks, nets, 2, (1, 1, 1, 0), MODEL, seed=2)
        b, _, _ = thermal_floorplan(blocks, nets, 2, (1, 1, 1, 3), MODEL, seed=2)
        lower += terms(blocks, nets, b, MODEL)[3] <= terms(blocks, nets, a, MODEL)[3] + 1e-9
    assert lower == 3

History

Floorplanning by annealing over a representation began with slicing trees and the sequence pair (1995), and TCG (Lin and Chang, DAC 2001) was one of several non-slicing representations. Thermal placement for 2D chips was studied in the late 1990s and early 2000s. Earlier 3D floorplanners either used a "true 3D" representation or one 2D representation per layer with few moves between layers. In 2004, Cong, Wei and Zhang combined a TCG per layer with buckets to get local moves between layers, and put a thermal model into the cost. This was, as they wrote, the first thermal-driven floorplanner for 3D ICs, and later 3D floorplanners added thermal vias and TSV planning.

References

  1. Jason Cong, Jie Wei and Yan Zhang, A thermal-driven floorplanning algorithm for 3D ICs, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design (ICCAD 2004), pages 306 to 313, Section 2 (the problem, room temperature 27 C at the sink), Section 3.1 (CBA, a TCG per layer and a bucket structure), Section 3.2 (the seven moves, the z-axis neighbor cost), Section 3.3 (Equation 1, the weighted cost), Section 4 (10 x 10 tiles; 4.1 CBA-T, the resistive network; 4.2 CBA-T-Fast, Equations 2 and 3; 4.3 CBA-T-Hybrid; 4.4 white space), Section 5 (MCNC and GSRC benchmarks, four layers, Tables 1 to 3)
  2. Jai-Ming Lin and Yao-Wen Chang, TCG, a transitive closure graph-based representation for non-slicing floorplans, Proceedings of the 38th Design Automation Conference (DAC 2001), pages 764 to 769, the transitive closure graph of each layer and its moves rotation, swap, reverse and move (general locator)

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.annealing
  • a full proof of time.one move with the closed-form model
  • a full proof of space.total
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
  • at least three sources
  • a scene preset for the example