| |
| |
| |
| |
| """Claim 1 (paper Table 2): performance-aware leaf-cell layout representation. |
| |
| Re-implements the GenLeaf representation stack of Section 3.1: |
| |
| * placement heterogeneous graph (PHG) with cell and net vertices, cell-net |
| and cell-cell adjacency edges, features of Table 1; |
| * GraphSAGE processing exactly as Algorithm 1 (linear projection, K SAGEConv |
| layers with neighbourhood sampling + mean aggregation, BatchNorm, dropout, |
| residual connections, mean+max pooling, MLP); |
| * routing image with net / track / blank regions, discrete Laplacian |
| sharpening (Eq. 2-3) and a CNN encoder; |
| * multi-head-attention fusion of the two branches; |
| * performance-aware supervised loss (Eq. 4) plus the downstream head that |
| predicts the (track, wirelength, via) vector. |
| |
| Baselines: a CircuitGNN-style topological+geometric GNN (no routing branch, no |
| performance-aware embedding loss) and a DeepLayout-style masked self-supervised |
| encoder with a linear probe. Reported metrics are MSE / MAE of the three-metric |
| prediction on a held-out split, on z-scored targets (as in the paper, where the |
| errors are ~1.0). |
| """ |
| from __future__ import annotations |
|
|
| import argparse, json, math, os, random, sys, time |
|
|
| import numpy as np |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
|
|
| MAX_TRACKS, MAX_COLS, N_LAYERS = 14, 56, 2 |
| EMB = 128 |
|
|
|
|
| |
| def build_sample(case, order, flip, leafpnr): |
| pins, row_w = leafpnr.place(case, order, flip) |
| spans = leafpnr._spans(pins) |
| assign, n_tracks, layers = leafpnr.channel_route(spans) |
| n = case.n |
| nets = case.nets |
| nc, nn_ = n, len(nets) |
|
|
| |
| xs = [] |
| pos = {} |
| x = 0 |
| for slot, ci in enumerate(order): |
| pos[ci] = x |
| x += case.cells[ci].width |
| for ci, c in enumerate(case.cells): |
| oh = [0.0] * 8 |
| oh[min(c.width, 7)] = 1.0 |
| px = [p[1] for p in c.pins] |
| xs.append(oh + [c.height / 4.0, c.n_pins / 6.0, |
| pos[ci] / max(row_w, 1), |
| (np.mean(px) if px else 0) / max(c.width, 1), |
| 1.0 if flip[order.index(ci)] == "MY" else 0.0, |
| 1.0, 0.0]) |
| npins = case.net_pins() |
| for net in nets: |
| ps = pins[net] |
| sx = (max(p[0] for p in ps) - min(p[0] for p in ps)) if ps else 0 |
| sy = (max(p[1] for p in ps) - min(p[1] for p in ps)) if ps else 0 |
| xs.append([0.0] * 8 + [0.0, npins[net] / 6.0, 0.0, 0.0, 0.0, 0.0, 1.0] |
| if False else |
| [0.0] * 8 + [0.0, npins[net] / 6.0, sx / max(row_w, 1), |
| sy / 4.0, 0.0, 0.0, 1.0]) |
| V = np.array(xs, dtype=np.float32) |
|
|
| |
| A = np.zeros((nc + nn_, nc + nn_), dtype=np.float32) |
| for ci, c in enumerate(case.cells): |
| for (net, _, _) in c.pins: |
| j = nc + nets.index(net) |
| A[ci, j] = A[j, ci] = 1.0 |
| for a in range(n): |
| for b in range(n): |
| if a != b and abs(pos[a] - pos[b]) <= 4: |
| A[a, b] = 1.0 |
|
|
| |
| img = np.zeros((N_LAYERS, MAX_TRACKS, MAX_COLS), dtype=np.float32) |
| ytr = {} |
| idx = 0 |
| for l in range(N_LAYERS): |
| for k in range(len(layers[l])): |
| ytr[(l, k)] = idx |
| idx += 1 |
| for l in range(N_LAYERS): |
| for k in range(len(layers[l])): |
| r = ytr[(l, k)] |
| if r < MAX_TRACKS: |
| img[l, r, :min(row_w, MAX_COLS)] = 0.25 |
| for i, net in enumerate(spans): |
| l, k = assign[net] |
| r = ytr[(l, k)] |
| x0, x1 = spans[net] |
| if r < MAX_TRACKS: |
| img[l, r, min(x0, MAX_COLS - 1):min(x1 + 1, MAX_COLS)] = \ |
| 0.5 + 0.5 * ((i % 7) + 1) / 8.0 |
| m = leafpnr.evaluate(case, order, flip) |
| return V, A, img, np.array([m["track"], m["wl"], m["via"]], dtype=np.float32) |
|
|
|
|
| def laplacian_sharpen(img, c=0.5): |
| """Eq. (2)-(3): g = f - c * laplacian(f), discrete 4-neighbour operator.""" |
| k = torch.tensor([[0., 1., 0.], [1., -4., 1.], [0., 1., 0.]], |
| device=img.device).view(1, 1, 3, 3).repeat(img.shape[1], 1, 1, 1) |
| lap = F.conv2d(img, k, padding=1, groups=img.shape[1]) |
| return img - c * lap |
|
|
|
|
| |
| class SAGE(nn.Module): |
| """Algorithm 1: GraphSAGE-based PHG processing.""" |
|
|
| def __init__(self, fin, hid=EMB, K=3, dropout=0.1, sample=8): |
| super().__init__() |
| self.lin = nn.Linear(fin, hid) |
| self.self_w = nn.ModuleList(nn.Linear(hid, hid) for _ in range(K)) |
| self.nb_w = nn.ModuleList(nn.Linear(hid, hid) for _ in range(K)) |
| self.bn = nn.ModuleList(nn.BatchNorm1d(hid) for _ in range(K)) |
| self.K, self.drop, self.sample = K, nn.Dropout(dropout), sample |
| self.out = nn.Sequential(nn.Linear(2 * hid, hid), nn.ReLU(), nn.Linear(hid, hid)) |
|
|
| def forward(self, V, A, mask): |
| h = self.lin(V) |
| deg = A.sum(-1, keepdim=True).clamp(min=1) |
| for k in range(self.K): |
| if self.training and self.sample: |
| keep = (torch.rand_like(A) < (self.sample / deg).clamp(max=1.0)).float() |
| Ak = A * keep |
| else: |
| Ak = A |
| agg = torch.bmm(Ak, h) / Ak.sum(-1, keepdim=True).clamp(min=1) |
| hn = self.self_w[k](h) + self.nb_w[k](agg) |
| B, N, D = hn.shape |
| hn = self.bn[k](hn.reshape(B * N, D)).reshape(B, N, D) |
| hn = self.drop(F.relu(hn)) |
| h = hn + h if k > 0 else hn |
| m = mask.unsqueeze(-1) |
| mean = (h * m).sum(1) / m.sum(1).clamp(min=1) |
| mx = (h + (m - 1) * 1e9).max(1).values |
| return self.out(torch.cat([mean, mx], -1)) |
|
|
|
|
| class RoutingCNN(nn.Module): |
| def __init__(self, hid=EMB): |
| super().__init__() |
| self.net = nn.Sequential( |
| nn.Conv2d(N_LAYERS, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), |
| nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), |
| nn.Conv2d(64, hid, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1)) |
|
|
| def forward(self, img): |
| return self.net(laplacian_sharpen(img)).flatten(1) |
|
|
|
|
| class GenLeafRepr(nn.Module): |
| """GraphSAGE + routing CNN + attention fusion + prediction head.""" |
|
|
| def __init__(self, fin, use_routing=True, hid=EMB): |
| super().__init__() |
| self.sage = SAGE(fin, hid) |
| self.use_routing = use_routing |
| if use_routing: |
| self.cnn = RoutingCNN(hid) |
| self.attn = nn.MultiheadAttention(hid, 4, batch_first=True) |
| self.proj = nn.Linear(hid, hid) |
| self.head = nn.Sequential(nn.Linear(hid, hid), nn.ReLU(), nn.Linear(hid, 3)) |
|
|
| def embed(self, V, A, mask, img): |
| g = self.sage(V, A, mask) |
| if not self.use_routing: |
| return g |
| r = self.cnn(img) |
| toks = torch.stack([g, r], 1) |
| a, _ = self.attn(toks, toks, toks) |
| return self.proj(a.mean(1) + toks.mean(1)) |
|
|
| def forward(self, V, A, mask, img): |
| e = self.embed(V, A, mask, img) |
| return e, self.head(e) |
|
|
|
|
| class DeepLayoutProxy(nn.Module): |
| """Mask-strategy self-supervised encoder (DeepLayout-style) + linear probe.""" |
|
|
| def __init__(self, fin, hid=EMB): |
| super().__init__() |
| self.sage = SAGE(fin, hid) |
| self.recon = nn.Linear(hid, fin) |
| self.probe = nn.Linear(hid, 3) |
|
|
| def forward(self, V, A, mask, img=None): |
| e = self.sage(V, A, mask) |
| return e, self.probe(e) |
|
|
|
|
| |
| def collate(samples, device): |
| N = max(s[0].shape[0] for s in samples) |
| fin = samples[0][0].shape[1] |
| B = len(samples) |
| V = np.zeros((B, N, fin), np.float32) |
| A = np.zeros((B, N, N), np.float32) |
| M = np.zeros((B, N), np.float32) |
| I = np.zeros((B, N_LAYERS, MAX_TRACKS, MAX_COLS), np.float32) |
| Y = np.zeros((B, 3), np.float32) |
| for i, (v, a, img, y) in enumerate(samples): |
| k = v.shape[0] |
| V[i, :k] = v |
| A[i, :k, :k] = a |
| M[i, :k] = 1 |
| I[i] = img |
| Y[i] = y |
| t = lambda x: torch.tensor(x, device=device) |
| return t(V), t(A), t(M), t(I), t(Y) |
|
|
|
|
| def pairwise_loss(e, y): |
| """Eq. (4): (sim(e_i,e_j) - sim(m_i,m_j))^2 over all pairs in the batch.""" |
| en = F.normalize(e, dim=-1) |
| yn = F.normalize(y, dim=-1) |
| return ((en @ en.T - yn @ yn.T) ** 2).mean() |
|
|
|
|
| def run(model, data, device, epochs, lr, pair_w, ssl=False, bs=32, log=print): |
| opt = torch.optim.AdamW(model.parameters(), lr=lr) |
| tr, va = data |
| for ep in range(epochs): |
| model.train() |
| random.shuffle(tr) |
| tot = 0.0 |
| for i in range(0, len(tr), bs): |
| batch = tr[i:i + bs] |
| if len(batch) < 2: |
| continue |
| V, A, M, I, Y = collate(batch, device) |
| if ssl and ep < epochs // 2: |
| Vm = V * (torch.rand_like(V[..., :1]) > 0.3).float() |
| e = model.sage(Vm, A, M) |
| loss = F.mse_loss(model.recon(e).unsqueeze(1).expand_as(V) * M.unsqueeze(-1), |
| V * M.unsqueeze(-1)) |
| else: |
| e, p = model(V, A, M, I) |
| loss = F.mse_loss(p, Y) + pair_w * pairwise_loss(e, Y) |
| opt.zero_grad() |
| loss.backward() |
| opt.step() |
| tot += float(loss) * len(batch) |
| if (ep + 1) % 5 == 0: |
| log(f" epoch {ep+1}/{epochs} train_loss={tot/len(tr):.4f}") |
| model.eval() |
| se, ae, k = 0.0, 0.0, 0 |
| with torch.no_grad(): |
| for i in range(0, len(va), bs): |
| batch = va[i:i + bs] |
| V, A, M, I, Y = collate(batch, device) |
| _, p = model(V, A, M, I) |
| se += float(((p - Y) ** 2).sum()) |
| ae += float((p - Y).abs().sum()) |
| k += Y.numel() |
| return se / k, ae / k |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--data", default="data") |
| ap.add_argument("--epochs", type=int, default=40) |
| ap.add_argument("--lr", type=float, default=1e-3) |
| ap.add_argument("--layouts-per-case", type=int, default=5) |
| ap.add_argument("--seed", type=int, default=0) |
| ap.add_argument("--out", default="repr_results.json") |
| ap.add_argument("--repo", default="", help="optional HF dataset repo to pull data from") |
| args = ap.parse_args() |
|
|
| if args.repo: |
| from huggingface_hub import snapshot_download |
| args.data = snapshot_download(args.repo, repo_type="dataset") |
| sys.path.insert(0, args.data) |
| sys.path.insert(0, os.path.join(args.data, "scripts")) |
| import leafpnr |
|
|
| torch.manual_seed(args.seed); random.seed(args.seed); np.random.seed(args.seed) |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| print("device:", device, torch.cuda.get_device_name(0) if device == "cuda" else "") |
|
|
| cases = leafpnr.load_cases(os.path.join(args.data, "cases_repr.json")) |
| rng = random.Random(args.seed) |
| samples = [] |
| for c in cases: |
| o, f = leafpnr.expert_designer(c) |
| samples.append(build_sample(c, o, f, leafpnr)) |
| for _ in range(args.layouts_per_case - 1): |
| oo = list(range(c.n)); rng.shuffle(oo) |
| ff = [rng.choice(["R0", "MY"]) for _ in range(c.n)] |
| samples.append(build_sample(c, oo, ff, leafpnr)) |
| print(f"{len(samples)} layouts from {len(cases)} cases") |
|
|
| Y = np.stack([s[3] for s in samples]) |
| mu, sd = Y.mean(0), Y.std(0) + 1e-9 |
| samples = [(v, a, i, (y - mu) / sd) for (v, a, i, y) in samples] |
| rng.shuffle(samples) |
| cut = int(0.8 * len(samples)) |
| data = (samples[:cut], samples[cut:]) |
| fin = samples[0][0].shape[1] |
|
|
| results = {} |
| configs = [ |
| ("GenLeaf (ours)", lambda: GenLeafRepr(fin, True), dict(pair_w=1.0, ssl=False)), |
| ("CircuitGNN (proxy)", lambda: GenLeafRepr(fin, False), dict(pair_w=0.0, ssl=False)), |
| ("DeepLayout (proxy)", lambda: DeepLayoutProxy(fin), dict(pair_w=0.0, ssl=True)), |
| ] |
| for name, ctor, kw in configs: |
| t0 = time.time() |
| torch.manual_seed(args.seed) |
| model = ctor().to(device) |
| print(f"[{name}] params={sum(p.numel() for p in model.parameters())}") |
| mse, mae = run(model, data, device, args.epochs, args.lr, **kw) |
| results[name] = {"MSE": round(mse, 4), "MAE": round(mae, 4), |
| "seconds": round(time.time() - t0, 1)} |
| print(f"[{name}] MSE={mse:.4f} MAE={mae:.4f} ({time.time()-t0:.0f}s)", flush=True) |
|
|
| g = results["GenLeaf (ours)"] |
| for b in ("CircuitGNN (proxy)", "DeepLayout (proxy)"): |
| results[b]["genleaf_mse_reduction_pct"] = round( |
| 100 * (results[b]["MSE"] - g["MSE"]) / results[b]["MSE"], 1) |
| results[b]["genleaf_mae_reduction_pct"] = round( |
| 100 * (results[b]["MAE"] - g["MAE"]) / results[b]["MAE"], 1) |
| results["_meta"] = {"n_layouts": len(samples), "epochs": args.epochs, |
| "device": device, "seed": args.seed, |
| "paper_table2": {"GenLeaf": [0.849, 0.722], |
| "CircuitGNN": [1.287, 0.815], |
| "DeepLayout": [1.324, 0.969]}} |
| print(json.dumps(results, indent=1)) |
| json.dump(results, open(args.out, "w", encoding="utf-8"), indent=1) |
| print("wrote", args.out) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|