diff --git "a/metadata/working_tree.patch" "b/metadata/working_tree.patch" new file mode 100644--- /dev/null +++ "b/metadata/working_tree.patch" @@ -0,0 +1,3428 @@ +diff --git a/README.md b/README.md +index 9b744af..5b1420a 100644 +--- a/README.md ++++ b/README.md +@@ -14,28 +14,61 @@ PPAPlace trains a differentiable dual-stream predictor (GAT + CNN) on post-globa + pip install -e . + ``` + +-**Dependencies:** PyTorch >= 2.0, NumPy, SciPy. ++**Dependencies:** PyTorch >= 2.0, NumPy, SciPy, and OR-Tools (macro legalization). + +-**External tools** (for data generation and evaluation): +-- [DREAMPlace](https://github.com/limbo018/DREAMPlace) — see [docs/SETUP_DREAMPLACE.md](docs/SETUP_DREAMPLACE.md) +-- [ChiPBench](https://github.com/TILOS-AI-Institute/ChiPBench) — see [docs/SETUP_CHIPBENCH.md](docs/SETUP_CHIPBENCH.md) ++**External tools** (for data generation and evaluation): ++- [DREAMPlace](https://github.com/limbo018/DREAMPlace) — see [docs/SETUP_DREAMPLACE.md](docs/SETUP_DREAMPLACE.md) ++- [ChiPBench](https://github.com/TILOS-AI-Institute/ChiPBench) — see [docs/SETUP_CHIPBENCH.md](docs/SETUP_CHIPBENCH.md) ++ ++For the native Linux workflow (no WSL or Docker), see ++[docs/SERVER_NATIVE_WORKFLOW.md](docs/SERVER_NATIVE_WORKFLOW.md). + + ## Data Preparation + + ### 1. Generate Training Placements + + ```bash +-python scripts/generate_data.py \ +- --circuit bp_fe \ +- --dreamplace_dir /path/to/DREAMPlace/install \ +- --n_configs 1000 --n_target 500 +-``` +- +-Repeat for each training circuit. This runs the 3-stage DREAMPlace pipeline (mixed-size GP, legalization, std-cell GP) with randomized hyperparameters. ++python scripts/generate_data.py \ ++ --circuit bp_fe \ ++ --dreamplace_dir /path/to/DREAMPlace/install \ ++ --n_configs 1000 --n_target 0 --jobs 4 ++``` ++ ++Repeat for each training circuit. This runs the 3-stage DREAMPlace pipeline (mixed-size GP, legalization, std-cell GP) with randomized hyperparameters. ++`--n_target 0` evaluates all 1,000 sampled configurations; after post-GRT, ++`scripts/select_training_data.py` retains the first 500 configurations with ++both a valid final DEF and valid WNS/TNS/power/area labels, skipping any ++repeated position-only macro identity. The production loader then parses the ++complete candidate DEF: orientation-aware macro features feed the graph ++branch, while exact standard-cell density, full-net pin concentration, macro ++occupancy, full-net RUDY, and full-net bounding-box density feed the five ++64x64 CNN channels. Final content audits require unique combined model inputs, ++unique standard-cell-density grids, non-collapsed content in every spatial ++channel, and movement by every individual macro. Position identity is ++tolerance-aware in normalized coordinates (`1e-3`): all 500 retained model ++inputs must remain distinct, and every macro must have at least a 0.25 ++distinct-position fraction and 0.05 normalized span. ++ ++The final DEF intentionally marks each legalized macro `FIXED` only during ++the third, standard-cell-only DREAMPlace pass. This preserves that sample's ++macro solution while standard cells move; it does not fix macro coordinates ++across samples. Dataset audits distinguish the DEF constraint token from ++coordinate collapse and require every macro to occupy multiple positions with ++a material span across the selected corpus. ++`--jobs 4` runs four independent configurations concurrently and is supported ++with `--n_target 0`; the sampled configuration list remains deterministic. + + ### 2. Evaluate Through Post-GRT Flow + +-Copy output DEFs into the ChiPBench Docker container and run: ++Run natively on the configured Linux server: ++ ++```bash ++source ~/bin/chipbench-env.sh ++NUM_CORES=8 STAGE_TIMEOUT=7200 bash scripts/grt_eval.sh \ ++ bp_fe /data/defs /data/grt_jsons 4 ++``` ++ ++The Docker-compatible invocation remains available when needed: + + ```bash + docker exec chipbench bash /scripts/grt_eval.sh bp_fe /data/defs /data/grt_jsons 8 +@@ -119,12 +152,14 @@ PPAPlace/ + │ ├── evaluate.py # Ranking evaluation on held-out circuits + │ ├── refine.py # End-to-end PPAPlace-Refine + │ ├── generate_data.py # DREAMPlace training data generation +-│ └── grt_eval.sh # ChiPBench post-GRT evaluation (Docker) ++│ ├── grt_eval.sh # ChiPBench post-GRT evaluation (native/Docker) ++│ └── server/ # Native Linux launchers and verifier + ├── configs/ + │ └── default.yaml # Default hyperparameters + ├── docs/ +-│ ├── SETUP_DREAMPLACE.md # DREAMPlace build & benchmark setup +-│ └── SETUP_CHIPBENCH.md # ChiPBench Docker setup & evaluation workflow ++│ ├── SETUP_DREAMPLACE.md # DREAMPlace build & benchmark setup ++│ ├── SETUP_CHIPBENCH.md # ChiPBench Docker setup & evaluation workflow ++│ └── SERVER_NATIVE_WORKFLOW.md # Native server workflow + ├── requirements.txt + └── setup.py + ``` +diff --git a/configs/default.yaml b/configs/default.yaml +index 4aa7925..65e8ade 100644 +--- a/configs/default.yaml ++++ b/configs/default.yaml +@@ -15,14 +15,16 @@ training: + epochs: 200 + learning_rate: 5.0e-4 + weight_decay: 1.0e-5 +- batch_size: 64 +- lambda_rank: 0.1 ++ batch_size: 32 ++ lambda_rank: 0.5 + scheduler: cosine + + # Data generation + data: + n_configs: 1000 +- n_target: 500 ++ # Evaluate all sampled configurations; retain labels only after post-GRT. ++ n_target: 0 ++ label_target: 500 + master_seed: 42 + grid_size: 64 + +diff --git a/ppaplace.egg-info/PKG-INFO b/ppaplace.egg-info/PKG-INFO +index 9d5d3ce..6cf5a1f 100644 +--- a/ppaplace.egg-info/PKG-INFO ++++ b/ppaplace.egg-info/PKG-INFO +@@ -1,10 +1,11 @@ +-Metadata-Version: 2.4 +-Name: ppaplace +-Version: 1.0.0 +-Requires-Python: >=3.8 +-Requires-Dist: torch>=2.0 +-Requires-Dist: numpy>=1.24 +-Requires-Dist: scipy>=1.10 +-Requires-Dist: ortools>=9.7 +-Dynamic: requires-dist +-Dynamic: requires-python ++Metadata-Version: 2.4 ++Name: ppaplace ++Version: 1.0.0 ++Requires-Python: >=3.8 ++Requires-Dist: torch>=2.0 ++Requires-Dist: numpy<1.24,>=1.23 ++Requires-Dist: scipy>=1.10 ++Requires-Dist: ortools==9.10.4067 ++Requires-Dist: pandas==2.0.3 ++Dynamic: requires-dist ++Dynamic: requires-python +diff --git a/ppaplace.egg-info/requires.txt b/ppaplace.egg-info/requires.txt +index 14f84e5..f3e2071 100644 +--- a/ppaplace.egg-info/requires.txt ++++ b/ppaplace.egg-info/requires.txt +@@ -1,4 +1,5 @@ + torch>=2.0 +-numpy>=1.24 ++numpy<1.24,>=1.23 + scipy>=1.10 +-ortools>=9.7 ++ortools==9.10.4067 ++pandas==2.0.3 +diff --git a/ppaplace/__init__.py b/ppaplace/__init__.py +index a911621..e964603 100644 +--- a/ppaplace/__init__.py ++++ b/ppaplace/__init__.py +@@ -1,5 +1,15 @@ + from .model import PPAPredictor, GATLayer +-from .features import compute_spatial_grid, compute_node_features ++from .features import ( ++ MIXED_SIZE_SPATIAL_CHANNELS, ++ MIXED_SIZE_SPATIAL_REPRESENTATION, ++ compute_spatial_grid, ++ compute_mixed_size_spatial_grid, ++ compute_node_features, ++) + from .features import DiffSpatialGrid, DiffNodeFeatures + from .loss import PPALoss +-from .data import load_chipbench_circuit, write_placement_def ++from .data import ( ++ load_chipbench_circuit, ++ parse_placement_state, ++ write_placement_def, ++) +diff --git a/ppaplace/coopt.py b/ppaplace/coopt.py +index e49b468..b6439cf 100644 +--- a/ppaplace/coopt.py ++++ b/ppaplace/coopt.py +@@ -39,6 +39,9 @@ class PPACoObjective: + self.edge_index = torch.tensor( + circuit_data['edge_index'], dtype=torch.long, + ).to(device) ++ self.edge_weight = torch.tensor( ++ circuit_data['edge_weights'], dtype=torch.float32, ++ ).to(device) + self.nets = circuit_data['nets'] + + # Pre-compute static features +@@ -105,6 +108,7 @@ class PPACoObjective: + + pred = self.model( + node_feat.unsqueeze(0), self.edge_index, spatial.unsqueeze(0), ++ self.edge_weight, + ) + ppa_loss = pred[0, 0] + pred[0, 1] # WNS + TNS + ppa_loss.backward() +diff --git a/ppaplace/data.py b/ppaplace/data.py +index 5408d51..c1f7c1d 100644 +--- a/ppaplace/data.py ++++ b/ppaplace/data.py +@@ -1,377 +1,755 @@ +-"""DEF/LEF parsing, circuit loading, and DEF writing.""" +- +-import os +-import re +-import json +-import numpy as np +-from typing import Dict, List, Tuple, Optional +- +- +-# --------------------------------------------------------------------------- +-# LEF Parsing +-# --------------------------------------------------------------------------- +- +-def parse_lef_macros(lef_paths: List[str]) -> Dict[str, dict]: +- """Parse LEF files to extract macro definitions and pin locations.""" +- macros = {} +- +- for lef_path in lef_paths: +- with open(lef_path, 'r') as f: +- text = f.read() +- +- parts = text.split('MACRO ') +- for part in parts[1:]: +- lines = part.split('\n') +- name = lines[0].strip().rstrip(';').strip() +- +- is_macro = False +- size = (0.0, 0.0) +- pins = {} +- +- for line in lines: +- line_s = line.strip() +- if line_s.startswith('CLASS BLOCK'): +- is_macro = True +- size_match = re.match(r'SIZE\s+([\d.]+)\s+BY\s+([\d.]+)', line_s) +- if size_match: +- size = (float(size_match.group(1)), float(size_match.group(2))) +- +- pin_sections = part.split('PIN ') +- for pin_sec in pin_sections[1:]: +- pin_name = pin_sec.split('\n')[0].strip() +- if pin_name in ('VPWR', 'VPB', 'VNB', 'VGND', 'VSSD', 'VSSA', 'VDD', 'VSS'): +- continue +- rect_match = re.search( +- r'RECT\s+([\d.e\-]+)\s+([\d.e\-]+)\s+([\d.e\-]+)\s+([\d.e\-]+)', +- pin_sec, +- ) +- if rect_match: +- x1, y1 = float(rect_match.group(1)), float(rect_match.group(2)) +- x2, y2 = float(rect_match.group(3)), float(rect_match.group(4)) +- pins[pin_name] = ((x1 + x2) / 2, (y1 + y2) / 2) +- +- if name: +- macros[name] = {'size': size, 'is_macro': is_macro, 'pins': pins} +- +- return macros +- +- +-# --------------------------------------------------------------------------- +-# DEF Parsing +-# --------------------------------------------------------------------------- +- +-def _parse_def_header(text: str) -> dict: +- """Parse DEF header: DESIGN, UNITS, DIEAREA, core area from ROWs.""" +- design_match = re.search(r'DESIGN\s+(\S+)\s*;', text) +- design_name = design_match.group(1) if design_match else None +- +- units_match = re.search(r'UNITS DISTANCE MICRONS\s+(\d+)', text) +- units = int(units_match.group(1)) if units_match else 1000 +- +- die_match = re.search( +- r'DIEAREA\s+\(\s*(\d+)\s+(\d+)\s*\)\s+\(\s*(\d+)\s+(\d+)\s*\)', text, +- ) +- die_area = tuple(int(die_match.group(i)) for i in range(1, 5)) if die_match else (0, 0, 0, 0) +- +- row_pattern = re.compile( +- r'ROW\s+\S+\s+\S+\s+(\d+)\s+(\d+)\s+\S+\s+DO\s+(\d+)\s+BY\s+\d+\s+STEP\s+(\d+)' +- ) +- rows = row_pattern.findall(text) +- if rows: +- row_xs, row_ys, row_x_maxs = [], [], [] +- for x_str, y_str, count_str, step_str in rows: +- x, y, count, step = int(x_str), int(y_str), int(count_str), int(step_str) +- row_xs.append(x) +- row_ys.append(y) +- row_x_maxs.append(x + count * step) +- core_area = (min(row_xs), min(row_ys), max(row_x_maxs), max(row_ys)) +- else: +- core_area = die_area +- +- return {'units': units, 'die_area': die_area, 'core_area': core_area, +- 'design_name': design_name} +- +- +-def _parse_def_components(text: str, lef_macros: Dict) -> Tuple[List[dict], List[dict]]: +- """Parse COMPONENTS section into macros and standard cells.""" +- comp_match = re.search(r'COMPONENTS\s+\d+\s*;(.*?)END COMPONENTS', text, re.DOTALL) +- if not comp_match: +- return [], [] +- +- pattern = re.compile( +- r'-\s+(\S+)\s+(\S+)\s+\+\s+(PLACED|FIXED)\s+\(\s*(-?\d+)\s+(-?\d+)\s*\)\s+(\S+)\s*;' +- ) +- +- macros, stdcells = [], [] +- for match in pattern.finditer(comp_match.group(1)): +- inst_name, inst_type = match.group(1), match.group(2) +- x, y, orient = int(match.group(4)), int(match.group(5)), match.group(6) +- +- if inst_type in lef_macros and lef_macros[inst_type]['is_macro']: +- macros.append({ +- 'name': inst_name, 'type': inst_type, +- 'x': x, 'y': y, 'orient': orient, +- 'size_microns': lef_macros[inst_type]['size'], +- }) +- else: +- stdcells.append({ +- 'name': inst_name, 'type': inst_type, +- 'x': x, 'y': y, 'orient': orient, +- }) +- +- return macros, stdcells +- +- +-def _parse_def_nets(text: str) -> List[List[Tuple[str, str]]]: +- """Parse NETS section into list of nets (component, pin) pairs.""" +- nets_match = re.search(r'NETS\s+\d+\s*;(.*?)END NETS', text, re.DOTALL) +- if not nets_match: +- return [] +- +- nets = [] +- for block in re.split(r'\n\s*-\s+', nets_match.group(1)): +- block = block.strip() +- if not block: +- continue +- pin_refs = re.findall(r'\(\s*(\S+)\s+(\S+)\s*\)', block) +- if len(pin_refs) >= 2: +- nets.append(pin_refs) +- +- return nets +- +- +-# --------------------------------------------------------------------------- +-# Circuit Loader +-# --------------------------------------------------------------------------- +- +-def load_chipbench_circuit(data_dir: str, circuit_name: Optional[str] = None, +- use_reference: bool = True) -> Dict: +- """ +- Load a ChiPBench circuit from DEF/LEF files. +- +- Args: +- data_dir: path to circuit data (contains lef/ and def/ subdirectories). +- circuit_name: override name (default: directory basename). +- use_reference: if True, load from macro_placed.def; else pre_place.def. +- +- Returns: +- dict with keys: +- node_features: (V, 2) normalized macro sizes. +- edge_index: (2, E) edge list. +- positions: (V, 2) reference placement in [-1, 1]. +- nets: list of nets, each = [(macro_idx, dx, dy), ...]. +- n_components: int. +- circuit_name: str. +- _macro_names, _macro_types, _sizes_def, _norm_bbox, _pre_place_def, +- _def_units, _lef_macros, etc. (metadata for DEF writing). +- """ +- if circuit_name is None: +- circuit_name = os.path.basename(data_dir) +- +- lef_dir = os.path.join(data_dir, 'lef') +- lef_paths = [os.path.join(lef_dir, f) for f in sorted(os.listdir(lef_dir)) +- if f.endswith('.lef')] if os.path.isdir(lef_dir) else [] +- +- lef_macros = parse_lef_macros(lef_paths) +- +- def_dir = os.path.join(data_dir, 'def') +- if use_reference: +- def_path = os.path.join(def_dir, 'macro_placed.def') +- if not os.path.exists(def_path): +- def_path = os.path.join(def_dir, 'pre_place.def') +- else: +- def_path = os.path.join(def_dir, 'pre_place.def') +- +- pre_place_path = os.path.join(def_dir, 'pre_place.def') +- +- with open(def_path, 'r') as f: +- def_text = f.read() +- +- header = _parse_def_header(def_text) +- def_units = header['units'] +- die_area = header['die_area'] +- core_area = header['core_area'] +- +- macros, _ = _parse_def_components(def_text, lef_macros) +- raw_nets = _parse_def_nets(def_text) +- +- if len(macros) == 0: +- raise ValueError(f"No macros found in {def_path}") +- +- V = len(macros) +- macro_name_to_idx = {m['name']: i for i, m in enumerate(macros)} +- +- sizes_def = np.zeros((V, 2), dtype=np.float64) +- positions_bl_def = np.zeros((V, 2), dtype=np.float64) +- for i, m in enumerate(macros): +- w_um, h_um = m['size_microns'] +- sizes_def[i] = [w_um * def_units, h_um * def_units] +- positions_bl_def[i] = [m['x'], m['y']] +- +- positions_center_def = positions_bl_def + sizes_def / 2 +- +- # Build macro-only net hypergraph +- nets_macro = [] +- for net in raw_nets: +- macro_pins = [] +- for comp_name, pin_name in net: +- if comp_name in macro_name_to_idx: +- idx = macro_name_to_idx[comp_name] +- macro_type = macros[idx]['type'] +- lef_pin_data = lef_macros.get(macro_type, {}).get('pins', {}) +- if pin_name in lef_pin_data: +- px, py = lef_pin_data[pin_name] +- dx = px * def_units - sizes_def[idx, 0] / 2 +- dy = py * def_units - sizes_def[idx, 1] / 2 +- else: +- dx, dy = 0.0, 0.0 +- macro_pins.append((idx, dx, dy)) +- if len(macro_pins) >= 2: +- nets_macro.append(macro_pins) +- +- # Normalize to [-1, 1] using core area +- core_x_min, core_y_min, core_x_max, core_y_max = core_area +- bbox_w = core_x_max - core_x_min +- bbox_h = core_y_max - core_y_min +- norm_bbox = (float(core_x_min), float(core_y_min), +- float(core_x_max), float(core_y_max)) +- +- positions_norm = np.zeros((V, 2), dtype=np.float32) +- positions_norm[:, 0] = 2.0 * (positions_center_def[:, 0] - core_x_min) / bbox_w - 1.0 +- positions_norm[:, 1] = 2.0 * (positions_center_def[:, 1] - core_y_min) / bbox_h - 1.0 +- +- sizes_norm = np.zeros((V, 2), dtype=np.float32) +- sizes_norm[:, 0] = sizes_def[:, 0] / bbox_w * 2.0 +- sizes_norm[:, 1] = sizes_def[:, 1] / bbox_h * 2.0 +- +- nets_norm = [] +- for net in nets_macro: +- nets_norm.append([(idx, dx / bbox_w * 2.0, dy / bbox_h * 2.0) +- for idx, dx, dy in net]) +- +- # Build edge_index (star decomposition, bidirectional) +- edges = [] +- for net in nets_norm: +- if len(net) < 2: +- continue +- src_idx = net[0][0] +- for sink_idx, _, _ in net[1:]: +- if src_idx != sink_idx: +- edges.append((src_idx, sink_idx)) +- edges.append((sink_idx, src_idx)) +- +- if not edges: +- for i in range(V - 1): +- edges.extend([(i, i + 1), (i + 1, i)]) +- +- edge_index = np.array(edges, dtype=np.int64).T +- +- chip_size = np.array([die_area[k] / def_units for k in range(4)], dtype=np.float32) +- +- return { +- 'node_features': sizes_norm, +- 'edge_index': edge_index, +- 'positions': positions_norm, +- 'nets': nets_norm, +- 'n_components': V, +- 'circuit_name': circuit_name, +- 'chip_size': chip_size, +- '_macro_names': [m['name'] for m in macros], +- '_macro_types': [m['type'] for m in macros], +- '_macro_orientations': [m['orient'] for m in macros], +- '_pre_place_def': pre_place_path, +- '_def_units': def_units, +- '_die_area_def': die_area, +- '_core_area_def': core_area, +- '_norm_bbox': norm_bbox, +- '_lef_macros': lef_macros, +- '_sizes_def': sizes_def, +- } +- +- +-# --------------------------------------------------------------------------- +-# DEF Writer +-# --------------------------------------------------------------------------- +- +-def denormalize_positions(positions_norm, norm_bbox, sizes_def): +- """Convert normalized [-1, 1] center positions to DEF bottom-left integer coords.""" +- x_min, y_min, x_max, y_max = norm_bbox +- bbox_w, bbox_h = x_max - x_min, y_max - y_min +- +- centers_def = np.zeros_like(positions_norm, dtype=np.float64) +- centers_def[:, 0] = (positions_norm[:, 0] + 1.0) / 2.0 * bbox_w + x_min +- centers_def[:, 1] = (positions_norm[:, 1] + 1.0) / 2.0 * bbox_h + y_min +- +- bl_def = centers_def - sizes_def / 2 +- +- GRID = 10 +- bl_int = (np.round(bl_def / GRID) * GRID).astype(np.int64) +- bl_int[:, 0] = np.clip(bl_int[:, 0], int(x_min), +- int(x_max) - sizes_def[:, 0].astype(np.int64)) +- bl_int[:, 1] = np.clip(bl_int[:, 1], int(y_min), +- int(y_max) - sizes_def[:, 1].astype(np.int64)) +- bl_int = (bl_int // GRID) * GRID +- +- return bl_int +- +- +-def write_placement_def(data: Dict, positions_norm: np.ndarray, output_path: str) -> str: +- """ +- Write a DEF file with updated macro positions. +- +- Reads the original pre_place.def as a template, replaces macro positions, +- marks them as FIXED, and writes to output_path. +- """ +- bl_positions = denormalize_positions( +- positions_norm, data['_norm_bbox'], data['_sizes_def'], +- ) +- +- macro_placements = {} +- for i, name in enumerate(data['_macro_names']): +- macro_placements[name] = (int(bl_positions[i, 0]), int(bl_positions[i, 1])) +- +- with open(data['_pre_place_def'], 'r') as f: +- lines = f.readlines() +- +- comp_pattern = re.compile( +- r'^(\s*-\s+)(\S+)(\s+\S+\s+\+\s+)(?:PLACED|FIXED)(\s+\(\s*)-?\d+\s+-?\d+(\s*\)\s+\S+\s*;)' +- ) +- +- output_lines = [] +- for line in lines: +- match = comp_pattern.match(line) +- if match: +- inst_name = match.group(2) +- if inst_name in macro_placements: +- x, y = macro_placements[inst_name] +- output_lines.append( +- f"{match.group(1)}{inst_name}{match.group(3)}" +- f"FIXED{match.group(4)}{x} {y}{match.group(5)}\n" +- ) +- continue +- output_lines.append(line) +- +- os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True) +- with open(output_path, 'w') as f: +- f.writelines(output_lines) +- +- return output_path +- +- +-# --------------------------------------------------------------------------- +-# GRT Label Loading +-# --------------------------------------------------------------------------- +- +-def load_grt_json(json_path: str) -> dict: +- """Load PPA metrics from a ChiPBench post-GRT JSON file.""" +- with open(json_path) as f: +- m = json.load(f) +- return { +- 'WNS': m.get('globalroute__timing__setup__ws', +- m.get('timing__setup__ws', 0.0)), +- 'TNS': m.get('globalroute__timing__setup__tns', +- m.get('timing__setup__tns', 0.0)), +- 'Power': m.get('globalroute__power__total', +- m.get('power__total', 0.0)), +- 'Area': 0.0, +- } ++"""DEF/LEF parsing, circuit loading, and DEF writing.""" ++ ++import os ++import re ++import json ++import math ++import numpy as np ++from typing import Dict, List, Tuple, Optional ++ ++ ++# --------------------------------------------------------------------------- ++# LEF Parsing ++# --------------------------------------------------------------------------- ++ ++def parse_lef_macros(lef_paths: List[str]) -> Dict[str, dict]: ++ """Parse LEF files to extract macro definitions and pin locations.""" ++ macros = {} ++ ++ for lef_path in lef_paths: ++ with open(lef_path, 'r') as f: ++ text = f.read() ++ ++ parts = text.split('MACRO ') ++ for part in parts[1:]: ++ lines = part.split('\n') ++ name = lines[0].strip().rstrip(';').strip() ++ ++ is_macro = False ++ size = (0.0, 0.0) ++ pins = {} ++ ++ for line in lines: ++ line_s = line.strip() ++ if line_s.startswith('CLASS BLOCK'): ++ is_macro = True ++ size_match = re.match(r'SIZE\s+([\d.]+)\s+BY\s+([\d.]+)', line_s) ++ if size_match: ++ size = (float(size_match.group(1)), float(size_match.group(2))) ++ ++ pin_sections = part.split('PIN ') ++ for pin_sec in pin_sections[1:]: ++ pin_name = pin_sec.split('\n')[0].strip() ++ if pin_name in ('VPWR', 'VPB', 'VNB', 'VGND', 'VSSD', 'VSSA', 'VDD', 'VSS'): ++ continue ++ rect_match = re.search( ++ r'RECT\s+([\d.e\-]+)\s+([\d.e\-]+)\s+([\d.e\-]+)\s+([\d.e\-]+)', ++ pin_sec, ++ ) ++ if rect_match: ++ x1, y1 = float(rect_match.group(1)), float(rect_match.group(2)) ++ x2, y2 = float(rect_match.group(3)), float(rect_match.group(4)) ++ pins[pin_name] = ((x1 + x2) / 2, (y1 + y2) / 2) ++ ++ if name: ++ macros[name] = {'size': size, 'is_macro': is_macro, 'pins': pins} ++ ++ return macros ++ ++ ++# --------------------------------------------------------------------------- ++# DEF Parsing ++# --------------------------------------------------------------------------- ++ ++def _parse_def_header(text: str) -> dict: ++ """Parse DEF header: DESIGN, UNITS, DIEAREA, core area from ROWs.""" ++ design_match = re.search(r'DESIGN\s+(\S+)\s*;', text) ++ design_name = design_match.group(1) if design_match else None ++ ++ units_match = re.search(r'UNITS DISTANCE MICRONS\s+(\d+)', text) ++ units = int(units_match.group(1)) if units_match else 1000 ++ ++ die_match = re.search( ++ r'DIEAREA\s+\(\s*(\d+)\s+(\d+)\s*\)\s+\(\s*(\d+)\s+(\d+)\s*\)', text, ++ ) ++ die_area = tuple(int(die_match.group(i)) for i in range(1, 5)) if die_match else (0, 0, 0, 0) ++ ++ row_pattern = re.compile( ++ r'ROW\s+\S+\s+\S+\s+(\d+)\s+(\d+)\s+\S+\s+DO\s+(\d+)\s+BY\s+\d+\s+STEP\s+(\d+)' ++ ) ++ rows = row_pattern.findall(text) ++ if rows: ++ row_xs, row_ys, row_x_maxs = [], [], [] ++ for x_str, y_str, count_str, step_str in rows: ++ x, y, count, step = int(x_str), int(y_str), int(count_str), int(step_str) ++ row_xs.append(x) ++ row_ys.append(y) ++ row_x_maxs.append(x + count * step) ++ core_area = (min(row_xs), min(row_ys), max(row_x_maxs), max(row_ys)) ++ else: ++ core_area = die_area ++ ++ return {'units': units, 'die_area': die_area, 'core_area': core_area, ++ 'design_name': design_name} ++ ++ ++def _parse_def_components(text: str, lef_macros: Dict) -> Tuple[List[dict], List[dict]]: ++ """Parse COMPONENTS section into macros and standard cells.""" ++ comp_match = re.search(r'COMPONENTS\s+\d+\s*;(.*?)END COMPONENTS', text, re.DOTALL) ++ if not comp_match: ++ return [], [] ++ ++ macros, stdcells = [], [] ++ for block in re.split( ++ r'(?:^|\n)\s*-\s+', comp_match.group(1)): ++ block = block.strip() ++ if not block: ++ continue ++ header = re.match(r'(\S+)\s+(\S+)', block) ++ placement = re.search( ++ r'\+\s+(PLACED|FIXED)\s+' ++ r'\(\s*(-?\d+)\s+(-?\d+)\s*\)\s+(\S+)', ++ block, re.DOTALL) ++ if not header or not placement: ++ continue ++ inst_name, inst_type = header.groups() ++ x, y = int(placement.group(2)), int(placement.group(3)) ++ orient = placement.group(4) ++ ++ if inst_type in lef_macros and lef_macros[inst_type]['is_macro']: ++ macros.append({ ++ 'name': inst_name, 'type': inst_type, ++ 'x': x, 'y': y, 'orient': orient, ++ 'size_microns': lef_macros[inst_type]['size'], ++ }) ++ else: ++ stdcells.append({ ++ 'name': inst_name, 'type': inst_type, ++ 'x': x, 'y': y, 'orient': orient, ++ 'size_microns': lef_macros.get( ++ inst_type, {}).get('size', (0.0, 0.0)), ++ }) ++ ++ return macros, stdcells ++ ++ ++def _parse_def_nets(text: str) -> List[List[Tuple[str, str]]]: ++ """Parse NETS section into list of nets (component, pin) pairs.""" ++ nets_match = re.search(r'NETS\s+\d+\s*;(.*?)END NETS', text, re.DOTALL) ++ if not nets_match: ++ return [] ++ ++ nets = [] ++ for block in re.split(r'\n\s*-\s+', nets_match.group(1)): ++ block = block.strip() ++ if not block: ++ continue ++ pin_refs = re.findall(r'\(\s*(\S+)\s+(\S+)\s*\)', block) ++ if len(pin_refs) >= 2: ++ nets.append(pin_refs) ++ ++ return nets ++ ++ ++def _parse_def_pins(text: str) -> Dict[str, Tuple[int, int]]: ++ """Parse placed top-level DEF pins by pin name.""" ++ pins_match = re.search( ++ r'PINS\s+\d+\s*;(.*?)END PINS', text, re.DOTALL) ++ if not pins_match: ++ return {} ++ ++ pins = {} ++ for block in re.split(r'\n\s*-\s+', pins_match.group(1)): ++ block = block.strip() ++ if not block: ++ continue ++ name = block.split(None, 1)[0] ++ placed = re.search( ++ r'\+\s+(?:PLACED|FIXED)\s+\(\s*(-?\d+)\s+(-?\d+)\s*\)', ++ block, re.DOTALL) ++ if placed: ++ pins[name] = (int(placed.group(1)), int(placed.group(2))) ++ return pins ++ ++ ++# --------------------------------------------------------------------------- ++# Circuit Loader ++# --------------------------------------------------------------------------- ++ ++def load_chipbench_circuit(data_dir: str, circuit_name: Optional[str] = None, ++ use_reference: bool = True) -> Dict: ++ """ ++ Load a ChiPBench circuit from DEF/LEF files. ++ ++ Args: ++ data_dir: path to circuit data (contains lef/ and def/ subdirectories). ++ circuit_name: override name (default: directory basename). ++ use_reference: if True, load from macro_placed.def; else pre_place.def. ++ ++ Returns: ++ dict with keys: ++ node_features: (V, 2) normalized macro sizes. ++ edge_index: (2, E) edge list. ++ positions: (V, 2) reference placement in [-1, 1]. ++ nets: list of nets, each = [(macro_idx, dx, dy), ...]. ++ n_components: int. ++ circuit_name: str. ++ _macro_names, _macro_types, _sizes_def, _norm_bbox, _pre_place_def, ++ _def_units, _lef_macros, etc. (metadata for DEF writing). ++ """ ++ if circuit_name is None: ++ circuit_name = os.path.basename(data_dir) ++ ++ lef_dir = os.path.join(data_dir, 'lef') ++ lef_paths = [os.path.join(lef_dir, f) for f in sorted(os.listdir(lef_dir)) ++ if f.endswith('.lef')] if os.path.isdir(lef_dir) else [] ++ ++ lef_macros = parse_lef_macros(lef_paths) ++ ++ def_dir = os.path.join(data_dir, 'def') ++ if use_reference: ++ def_path = os.path.join(def_dir, 'macro_placed.def') ++ if not os.path.exists(def_path): ++ def_path = os.path.join(def_dir, 'pre_place.def') ++ else: ++ def_path = os.path.join(def_dir, 'pre_place.def') ++ ++ pre_place_path = os.path.join(def_dir, 'pre_place.def') ++ ++ with open(def_path, 'r') as f: ++ def_text = f.read() ++ ++ header = _parse_def_header(def_text) ++ def_units = header['units'] ++ die_area = header['die_area'] ++ core_area = header['core_area'] ++ ++ macros, stdcells = _parse_def_components(def_text, lef_macros) ++ raw_nets = _parse_def_nets(def_text) ++ top_pins = _parse_def_pins(def_text) ++ declared_components = re.search( ++ r'COMPONENTS\s+(\d+)\s*;', def_text) ++ if ( ++ declared_components ++ and len(macros) + len(stdcells) ++ != int(declared_components.group(1)) ++ ): ++ raise ValueError( ++ f'Parsed {len(macros) + len(stdcells)} of ' ++ f'{declared_components.group(1)} declared components in ' ++ f'{def_path}') ++ ++ if len(macros) == 0: ++ raise ValueError(f"No macros found in {def_path}") ++ ++ V = len(macros) ++ macro_name_to_idx = {m['name']: i for i, m in enumerate(macros)} ++ ++ # Keep a complete mixed-size component view for the manuscript's spatial ++ # branch. Macro graph indices remain unchanged and occupy the first V ++ # entries; candidate DEF parsing maps by instance name, so this internal ++ # ordering does not depend on component order in the source DEF. ++ components = macros + stdcells ++ component_name_to_idx = { ++ component['name']: index ++ for index, component in enumerate(components) ++ } ++ component_sizes_def = np.zeros((len(components), 2), dtype=np.float64) ++ component_positions_bl_def = np.zeros( ++ (len(components), 2), dtype=np.float64) ++ component_orientations = [] ++ for index, component in enumerate(components): ++ width_um, height_um = component['size_microns'] ++ component_sizes_def[index] = [ ++ width_um * def_units, height_um * def_units] ++ component_positions_bl_def[index] = [ ++ component['x'], component['y']] ++ component_orientations.append(component['orient']) ++ invalid_size_indices = np.flatnonzero( ++ np.any(component_sizes_def <= 0, axis=1)) ++ if len(invalid_size_indices): ++ examples = [ ++ (components[index]['name'], components[index]['type']) ++ for index in invalid_size_indices[:10]] ++ raise ValueError( ++ f'{len(invalid_size_indices)} components have missing or ' ++ f'nonpositive LEF sizes in {def_path}: {examples}') ++ ++ sizes_def = np.zeros((V, 2), dtype=np.float64) ++ positions_bl_def = np.zeros((V, 2), dtype=np.float64) ++ for i, m in enumerate(macros): ++ w_um, h_um = m['size_microns'] ++ sizes_def[i] = [w_um * def_units, h_um * def_units] ++ positions_bl_def[i] = [m['x'], m['y']] ++ ++ positions_center_def = positions_bl_def + sizes_def / 2 ++ ++ # Build macro-only net hypergraph ++ nets_macro = [] ++ for net in raw_nets: ++ macro_pins = [] ++ for comp_name, pin_name in net: ++ if comp_name in macro_name_to_idx: ++ idx = macro_name_to_idx[comp_name] ++ macro_type = macros[idx]['type'] ++ lef_pin_data = lef_macros.get(macro_type, {}).get('pins', {}) ++ if pin_name in lef_pin_data: ++ px, py = lef_pin_data[pin_name] ++ dx = px * def_units - sizes_def[idx, 0] / 2 ++ dy = py * def_units - sizes_def[idx, 1] / 2 ++ else: ++ dx, dy = 0.0, 0.0 ++ macro_pins.append((idx, dx, dy)) ++ if len(macro_pins) >= 2: ++ nets_macro.append(macro_pins) ++ ++ # Normalize to [-1, 1] using core area ++ core_x_min, core_y_min, core_x_max, core_y_max = core_area ++ bbox_w = core_x_max - core_x_min ++ bbox_h = core_y_max - core_y_min ++ norm_bbox = (float(core_x_min), float(core_y_min), ++ float(core_x_max), float(core_y_max)) ++ ++ positions_norm = np.zeros((V, 2), dtype=np.float32) ++ positions_norm[:, 0] = 2.0 * (positions_center_def[:, 0] - core_x_min) / bbox_w - 1.0 ++ positions_norm[:, 1] = 2.0 * (positions_center_def[:, 1] - core_y_min) / bbox_h - 1.0 ++ ++ sizes_norm = np.zeros((V, 2), dtype=np.float32) ++ sizes_norm[:, 0] = sizes_def[:, 0] / bbox_w * 2.0 ++ sizes_norm[:, 1] = sizes_def[:, 1] / bbox_h * 2.0 ++ ++ nets_norm = [] ++ nets_macro_def = [] ++ for net in nets_macro: ++ nets_macro_def.append([ ++ (idx, float(dx), float(dy)) for idx, dx, dy in net]) ++ nets_norm.append([(idx, dx / bbox_w * 2.0, dy / bbox_h * 2.0) ++ for idx, dx, dy in net]) ++ ++ component_sizes_norm = np.zeros_like( ++ component_sizes_def, dtype=np.float32) ++ component_sizes_norm[:, 0] = ( ++ component_sizes_def[:, 0] / bbox_w * 2.0) ++ component_sizes_norm[:, 1] = ( ++ component_sizes_def[:, 1] / bbox_h * 2.0) ++ ++ # Flatten the complete netlist once. Candidate-specific pin coordinates ++ # can then be formed by vectorized orientation transforms without ++ # reparsing NETS for every one of the 5,000 training placements. ++ full_net_pin_component_indices = [] ++ full_net_pin_offsets_def = [] ++ full_net_pin_static_positions_def = [] ++ full_net_ids = [] ++ accepted_net_count = 0 ++ for net in raw_nets: ++ entries = [] ++ for component_name, pin_name in net: ++ if component_name in component_name_to_idx: ++ component_index = component_name_to_idx[component_name] ++ component = components[component_index] ++ width_def, height_def = component_sizes_def[component_index] ++ pin = lef_macros.get( ++ component['type'], {}).get('pins', {}).get(pin_name) ++ if pin is None: ++ local_x = width_def / 2.0 ++ local_y = height_def / 2.0 ++ else: ++ local_x = float(pin[0]) * def_units ++ local_y = float(pin[1]) * def_units ++ entries.append(( ++ component_index, ++ local_x - width_def / 2.0, ++ local_y - height_def / 2.0, ++ math.nan, ++ math.nan, ++ )) ++ elif component_name == 'PIN' and pin_name in top_pins: ++ pin_x, pin_y = top_pins[pin_name] ++ entries.append((-1, 0.0, 0.0, pin_x, pin_y)) ++ if len(entries) < 2: ++ continue ++ for component_index, dx, dy, static_x, static_y in entries: ++ full_net_pin_component_indices.append(component_index) ++ full_net_pin_offsets_def.append((dx, dy)) ++ full_net_pin_static_positions_def.append((static_x, static_y)) ++ full_net_ids.append(accepted_net_count) ++ accepted_net_count += 1 ++ ++ # Build edge_index (clique expansion, bidirectional) with edge weights ++ # equal to the number of shared nets between each macro pair. ++ from collections import Counter ++ pair_counts = Counter() ++ for net in nets_norm: ++ idxs = list(set(pin[0] for pin in net)) ++ for i in range(len(idxs)): ++ for j in range(i + 1, len(idxs)): ++ a, b = idxs[i], idxs[j] ++ pair_counts[(a, b)] += 1 ++ pair_counts[(b, a)] += 1 ++ ++ if not pair_counts: ++ for i in range(V - 1): ++ pair_counts[(i, i + 1)] = 1 ++ pair_counts[(i + 1, i)] = 1 ++ ++ edges = list(pair_counts.keys()) ++ edge_weights = np.array([pair_counts[e] for e in edges], dtype=np.float32) ++ edge_index = np.array(edges, dtype=np.int64).T ++ ++ chip_size = np.array([die_area[k] / def_units for k in range(4)], dtype=np.float32) ++ ++ return { ++ 'node_features': sizes_norm, ++ 'edge_index': edge_index, ++ 'edge_weights': edge_weights, ++ 'positions': positions_norm, ++ 'nets': nets_norm, ++ 'n_components': V, ++ 'circuit_name': circuit_name, ++ 'chip_size': chip_size, ++ '_macro_names': [m['name'] for m in macros], ++ '_macro_types': [m['type'] for m in macros], ++ '_macro_orientations': [m['orient'] for m in macros], ++ '_macro_component_indices': np.arange(V, dtype=np.int32), ++ '_pre_place_def': pre_place_path, ++ '_def_units': def_units, ++ '_die_area_def': die_area, ++ '_core_area_def': core_area, ++ '_norm_bbox': norm_bbox, ++ '_lef_macros': lef_macros, ++ '_sizes_def': sizes_def, ++ '_macro_nets_def': nets_macro_def, ++ '_component_names': [ ++ component['name'] for component in components], ++ '_component_types': [ ++ component['type'] for component in components], ++ '_component_is_macro': np.array( ++ [True] * len(macros) + [False] * len(stdcells), ++ dtype=bool), ++ '_component_sizes_def': component_sizes_def, ++ '_component_sizes_norm': component_sizes_norm, ++ '_component_reference_positions_bl_def': ++ component_positions_bl_def, ++ '_component_reference_orientations': component_orientations, ++ '_full_net_pin_component_indices': np.asarray( ++ full_net_pin_component_indices, dtype=np.int32), ++ '_full_net_pin_offsets_def': np.asarray( ++ full_net_pin_offsets_def, dtype=np.float64).reshape(-1, 2), ++ '_full_net_pin_static_positions_def': np.asarray( ++ full_net_pin_static_positions_def, ++ dtype=np.float64).reshape(-1, 2), ++ '_full_net_ids': np.asarray(full_net_ids, dtype=np.int32), ++ '_full_net_count': accepted_net_count, ++ } ++ ++ ++# --------------------------------------------------------------------------- ++# Candidate placement parsing ++# --------------------------------------------------------------------------- ++ ++_ORIENTATION_CODES = { ++ 'N': 0, ++ 'S': 1, ++ 'FN': 2, ++ 'FS': 3, ++ 'W': 4, ++ 'E': 5, ++ 'FW': 6, ++ 'FE': 7, ++} ++ ++ ++def _orientation_codes(orientations: List[str]) -> np.ndarray: ++ try: ++ return np.asarray( ++ [_ORIENTATION_CODES[item] for item in orientations], ++ dtype=np.int8) ++ except KeyError as exc: ++ raise ValueError(f'Unsupported DEF orientation: {exc.args[0]}') from exc ++ ++ ++def _oriented_sizes_def( ++ sizes_def: np.ndarray, orientation_codes: np.ndarray) -> np.ndarray: ++ """Return placed bounding-box sizes for DEF orientations.""" ++ result = np.asarray(sizes_def, dtype=np.float64).copy() ++ rotated = orientation_codes >= 4 ++ if np.any(rotated): ++ result[rotated] = result[rotated][:, ::-1] ++ return result ++ ++ ++def _transform_offsets_def( ++ offsets_def: np.ndarray, orientation_codes: np.ndarray) -> np.ndarray: ++ """Transform center-relative pin offsets for DEF orientations.""" ++ offsets = np.asarray(offsets_def, dtype=np.float64) ++ codes = np.asarray(orientation_codes, dtype=np.int8) ++ if offsets.shape != (len(codes), 2): ++ raise ValueError( ++ f'Offset/orientation shape mismatch: {offsets.shape}, {codes.shape}') ++ x = offsets[:, 0] ++ y = offsets[:, 1] ++ result = np.empty_like(offsets) ++ ++ transforms = { ++ 0: (x, y), # N: R0 ++ 1: (-x, -y), # S: R180 ++ 2: (-x, y), # FN: mirror Y ++ 3: (x, -y), # FS: mirror X ++ 4: (-y, x), # W: R90 ++ 5: (y, -x), # E: R270 ++ 6: (y, x), # FW: mirror X then R90 ++ 7: (-y, -x), # FE: mirror Y then R90 ++ } ++ for code, (tx, ty) in transforms.items(): ++ mask = codes == code ++ result[mask, 0] = tx[mask] ++ result[mask, 1] = ty[mask] ++ if np.any((codes < 0) | (codes > 7)): ++ raise ValueError('Invalid orientation code') ++ return result ++ ++ ++def _read_def_component_section(def_path: str) -> str: ++ """Read only the COMPONENTS section, avoiding routed DEF tail data.""" ++ lines = [] ++ inside = False ++ with open(def_path, encoding='utf-8', errors='replace') as stream: ++ for line in stream: ++ if not inside: ++ if re.match(r'^\s*COMPONENTS\s+\d+\s*;', line): ++ inside = True ++ continue ++ if re.match(r'^\s*END\s+COMPONENTS\b', line): ++ break ++ lines.append(line) ++ if not inside: ++ raise ValueError(f'Missing COMPONENTS section: {def_path}') ++ return ''.join(lines) ++ ++ ++def parse_placement_state(def_path: str, circuit_data: Dict) -> Dict: ++ """ ++ Parse candidate-specific macro and standard-cell state from a DEF. ++ ++ The returned macro tensors feed the graph branch, while the complete ++ component and full-net pin tensors feed the manuscript's mixed-size ++ five-channel spatial branch. ++ """ ++ component_names = circuit_data['_component_names'] ++ component_types = circuit_data['_component_types'] ++ name_to_index = { ++ name: index for index, name in enumerate(component_names)} ++ component_count = len(component_names) ++ positions_bl_def = np.full( ++ (component_count, 2), np.nan, dtype=np.float64) ++ orientations = [None] * component_count ++ statuses = [None] * component_count ++ found = np.zeros(component_count, dtype=bool) ++ ++ section = _read_def_component_section(def_path) ++ for block in re.split(r'(?:^|\n)\s*-\s+', section): ++ block = block.strip() ++ if not block: ++ continue ++ header = re.match(r'(\S+)\s+(\S+)', block) ++ placement = re.search( ++ r'\+\s+(PLACED|FIXED)\s+' ++ r'\(\s*(-?\d+)\s+(-?\d+)\s*\)\s+(\S+)', ++ block, re.DOTALL) ++ if not header or not placement: ++ continue ++ name, component_type = header.groups() ++ index = name_to_index.get(name) ++ if index is None: ++ raise ValueError(f'Unknown component in {def_path}: {name}') ++ if found[index]: ++ raise ValueError(f'Duplicate component in {def_path}: {name}') ++ if component_type != component_types[index]: ++ raise ValueError( ++ f'Component type mismatch for {name}: ' ++ f'{component_type} != {component_types[index]}') ++ statuses[index] = placement.group(1) ++ positions_bl_def[index] = [ ++ int(placement.group(2)), int(placement.group(3))] ++ orientations[index] = placement.group(4) ++ found[index] = True ++ ++ if not np.all(found): ++ missing = [ ++ component_names[index] ++ for index in np.flatnonzero(~found)[:10]] ++ raise ValueError( ++ f'Missing {int((~found).sum())} components in {def_path}: ' ++ f'{missing}') ++ ++ orientation_codes = _orientation_codes(orientations) ++ oriented_sizes_def = _oriented_sizes_def( ++ circuit_data['_component_sizes_def'], orientation_codes) ++ centers_def = positions_bl_def + oriented_sizes_def / 2.0 ++ ++ x_min, y_min, x_max, y_max = circuit_data['_norm_bbox'] ++ bbox_w = x_max - x_min ++ bbox_h = y_max - y_min ++ component_positions = np.empty( ++ (component_count, 2), dtype=np.float32) ++ component_positions[:, 0] = ( ++ 2.0 * (centers_def[:, 0] - x_min) / bbox_w - 1.0) ++ component_positions[:, 1] = ( ++ 2.0 * (centers_def[:, 1] - y_min) / bbox_h - 1.0) ++ component_sizes = np.empty_like( ++ oriented_sizes_def, dtype=np.float32) ++ component_sizes[:, 0] = oriented_sizes_def[:, 0] / bbox_w * 2.0 ++ component_sizes[:, 1] = oriented_sizes_def[:, 1] / bbox_h * 2.0 ++ ++ macro_indices = circuit_data['_macro_component_indices'] ++ macro_positions = component_positions[macro_indices] ++ macro_sizes = component_sizes[macro_indices] ++ ++ macro_nets = [] ++ macro_orientation_codes = orientation_codes[macro_indices] ++ for net in circuit_data['_macro_nets_def']: ++ indices = np.asarray( ++ [entry[0] for entry in net], dtype=np.int32) ++ offsets = np.asarray( ++ [[entry[1], entry[2]] for entry in net], ++ dtype=np.float64) ++ transformed = _transform_offsets_def( ++ offsets, macro_orientation_codes[indices]) ++ macro_nets.append([ ++ ( ++ int(index), ++ float(transformed[row, 0] / bbox_w * 2.0), ++ float(transformed[row, 1] / bbox_h * 2.0), ++ ) ++ for row, index in enumerate(indices) ++ ]) ++ ++ pin_component_indices = circuit_data[ ++ '_full_net_pin_component_indices'] ++ pin_positions_def = circuit_data[ ++ '_full_net_pin_static_positions_def'].copy() ++ component_pin_mask = pin_component_indices >= 0 ++ if np.any(component_pin_mask): ++ indices = pin_component_indices[component_pin_mask] ++ offsets = circuit_data['_full_net_pin_offsets_def'][ ++ component_pin_mask] ++ transformed = _transform_offsets_def( ++ offsets, orientation_codes[indices]) ++ pin_positions_def[component_pin_mask] = ( ++ centers_def[indices] + transformed) ++ if not np.isfinite(pin_positions_def).all(): ++ raise ValueError(f'Non-finite full-net pin position in {def_path}') ++ pin_positions = np.empty_like(pin_positions_def, dtype=np.float32) ++ pin_positions[:, 0] = ( ++ 2.0 * (pin_positions_def[:, 0] - x_min) / bbox_w - 1.0) ++ pin_positions[:, 1] = ( ++ 2.0 * (pin_positions_def[:, 1] - y_min) / bbox_h - 1.0) ++ ++ return { ++ 'macro_positions': macro_positions, ++ 'macro_sizes': macro_sizes, ++ 'macro_nets': macro_nets, ++ 'component_positions': component_positions, ++ 'component_sizes': component_sizes, ++ 'component_is_macro': circuit_data['_component_is_macro'], ++ 'pin_positions': pin_positions, ++ 'pin_net_ids': circuit_data['_full_net_ids'], ++ 'net_count': circuit_data['_full_net_count'], ++ 'component_orientations': orientations, ++ 'component_statuses': statuses, ++ 'macro_def_fixed_record_count': sum( ++ statuses[index] == 'FIXED' for index in macro_indices), ++ } ++ ++ ++# --------------------------------------------------------------------------- ++# DEF Writer ++# --------------------------------------------------------------------------- ++ ++def denormalize_positions(positions_norm, norm_bbox, sizes_def): ++ """Convert normalized [-1, 1] center positions to DEF bottom-left integer coords.""" ++ x_min, y_min, x_max, y_max = norm_bbox ++ bbox_w, bbox_h = x_max - x_min, y_max - y_min ++ ++ centers_def = np.zeros_like(positions_norm, dtype=np.float64) ++ centers_def[:, 0] = (positions_norm[:, 0] + 1.0) / 2.0 * bbox_w + x_min ++ centers_def[:, 1] = (positions_norm[:, 1] + 1.0) / 2.0 * bbox_h + y_min ++ ++ bl_def = centers_def - sizes_def / 2 ++ ++ GRID = 10 ++ bl_int = (np.round(bl_def / GRID) * GRID).astype(np.int64) ++ bl_int[:, 0] = np.clip(bl_int[:, 0], int(x_min), ++ int(x_max) - sizes_def[:, 0].astype(np.int64)) ++ bl_int[:, 1] = np.clip(bl_int[:, 1], int(y_min), ++ int(y_max) - sizes_def[:, 1].astype(np.int64)) ++ bl_int = (bl_int // GRID) * GRID ++ ++ return bl_int ++ ++ ++def write_placement_def(data: Dict, positions_norm: np.ndarray, output_path: str) -> str: ++ """ ++ Write a DEF file with updated macro positions. ++ ++ Reads the original pre_place.def as a template, replaces macro positions, ++ marks them as FIXED, and writes to output_path. ++ """ ++ bl_positions = denormalize_positions( ++ positions_norm, data['_norm_bbox'], data['_sizes_def'], ++ ) ++ ++ macro_placements = {} ++ for i, name in enumerate(data['_macro_names']): ++ macro_placements[name] = (int(bl_positions[i, 0]), int(bl_positions[i, 1])) ++ ++ with open(data['_pre_place_def'], 'r') as f: ++ lines = f.readlines() ++ ++ comp_pattern = re.compile( ++ r'^(\s*-\s+)(\S+)(\s+\S+\s+\+\s+)(?:PLACED|FIXED)(\s+\(\s*)-?\d+\s+-?\d+(\s*\)\s+\S+\s*;)' ++ ) ++ ++ output_lines = [] ++ for line in lines: ++ match = comp_pattern.match(line) ++ if match: ++ inst_name = match.group(2) ++ if inst_name in macro_placements: ++ x, y = macro_placements[inst_name] ++ output_lines.append( ++ f"{match.group(1)}{inst_name}{match.group(3)}" ++ f"FIXED{match.group(4)}{x} {y}{match.group(5)}\n" ++ ) ++ continue ++ output_lines.append(line) ++ ++ os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True) ++ with open(output_path, 'w') as f: ++ f.writelines(output_lines) ++ ++ return output_path ++ ++ ++# --------------------------------------------------------------------------- ++# GRT Label Loading ++# --------------------------------------------------------------------------- ++ ++def load_grt_json(json_path: str) -> dict: ++ """Load PPA metrics from a ChiPBench post-GRT JSON file.""" ++ with open(json_path) as f: ++ m = json.load(f) ++ return { ++ 'WNS': m.get('globalroute__timing__setup__ws', ++ m.get('timing__setup__ws', 0.0)), ++ 'TNS': m.get('globalroute__timing__setup__tns', ++ m.get('timing__setup__tns', 0.0)), ++ 'Power': m.get('globalroute__power__total', ++ m.get('power__total', 0.0)), ++ # The manuscript defines Area as physical footprint, which is fixed by ++ # the floorplan within each circuit. ChiPBench records this directly ++ # in its post-GRT metrics. ++ 'Area': m.get('globalroute__design__core__area', ++ m.get('globalroute__design__die__area', ++ m.get('globalroute__design__instance__area', 0.0))), ++ } +diff --git a/ppaplace/features.py b/ppaplace/features.py +index ca0899c..a999e42 100644 +--- a/ppaplace/features.py ++++ b/ppaplace/features.py +@@ -7,15 +7,25 @@ grid and 8-dimensional node feature vector. + """ + + import numpy as np +-import torch +-import torch.nn.functional as F +- +- +-# --------------------------------------------------------------------------- ++import torch ++import torch.nn.functional as F ++ ++ ++MIXED_SIZE_SPATIAL_REPRESENTATION = 'complete_mixed_size_v1' ++MIXED_SIZE_SPATIAL_CHANNELS = ( ++ 'standard_cell_density', ++ 'full_net_pin_concentration', ++ 'macro_occupancy', ++ 'full_net_rudy', ++ 'full_net_bounding_box_density', ++) ++ ++ ++# --------------------------------------------------------------------------- + # NumPy implementations (used during data preprocessing and training) + # --------------------------------------------------------------------------- + +-def compute_spatial_grid(positions, sizes, nets, grid_size=64): ++def compute_spatial_grid(positions, sizes, nets, grid_size=64): + """ + Compute 5-channel spatial grid from placement state. + +@@ -94,10 +104,264 @@ def compute_spatial_grid(positions, sizes, nets, grid_size=64): + if cmax > 0: + grid[c] /= cmax + +- return grid +- +- +-def compute_node_features(positions, sizes, nets): ++ return grid ++ ++ ++def _rasterize_rectangle_overlap(positions, sizes, grid_size): ++ """Rasterize exact rectangle/bin overlap for an instance collection.""" ++ grid = np.zeros((grid_size, grid_size), dtype=np.float32) ++ if len(positions) == 0: ++ return grid ++ ++ positions = np.asarray(positions, dtype=np.float64) ++ sizes = np.asarray(sizes, dtype=np.float64) ++ left = np.maximum(positions[:, 0] - sizes[:, 0] / 2.0, -1.0) ++ right = np.minimum(positions[:, 0] + sizes[:, 0] / 2.0, 1.0) ++ bottom = np.maximum(positions[:, 1] - sizes[:, 1] / 2.0, -1.0) ++ top = np.minimum(positions[:, 1] + sizes[:, 1] / 2.0, 1.0) ++ valid = (right > left) & (top > bottom) ++ if not np.any(valid): ++ return grid ++ left, right = left[valid], right[valid] ++ bottom, top = bottom[valid], top[valid] ++ ++ edges = np.linspace(-1.0, 1.0, grid_size + 1) ++ cell_width = 2.0 / grid_size ++ cell_area = cell_width ** 2 ++ left_bin = np.clip( ++ np.floor((left + 1.0) / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ right_bin = np.clip( ++ np.floor( ++ (np.nextafter(right, -np.inf) + 1.0) ++ / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ bottom_bin = np.clip( ++ np.floor((bottom + 1.0) / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ top_bin = np.clip( ++ np.floor( ++ (np.nextafter(top, -np.inf) + 1.0) ++ / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ ++ # Standard cells are normally much smaller than one 64x64 bin. Handle ++ # their at-most-2x2 overlaps as four vectorized scatter operations. ++ compact = ( ++ (right_bin - left_bin <= 1) ++ & (top_bin - bottom_bin <= 1)) ++ if np.any(compact): ++ lx, rx = left_bin[compact], right_bin[compact] ++ by, ty = bottom_bin[compact], top_bin[compact] ++ l, r = left[compact], right[compact] ++ b, t = bottom[compact], top[compact] ++ overlap_left = np.minimum(r, edges[lx + 1]) - l ++ overlap_right = np.where( ++ rx == lx, 0.0, r - np.maximum(l, edges[rx])) ++ overlap_bottom = np.minimum(t, edges[by + 1]) - b ++ overlap_top = np.where( ++ ty == by, 0.0, t - np.maximum(b, edges[ty])) ++ np.add.at( ++ grid, (by, lx), ++ overlap_bottom * overlap_left / cell_area) ++ np.add.at( ++ grid, (by, rx), ++ overlap_bottom * overlap_right / cell_area) ++ np.add.at( ++ grid, (ty, lx), ++ overlap_top * overlap_left / cell_area) ++ np.add.at( ++ grid, (ty, rx), ++ overlap_top * overlap_right / cell_area) ++ ++ # This fallback keeps the function exact for unusually large non-macro ++ # cells without putting the common hundreds-of-thousands-cell path in a ++ # Python loop. ++ for row in np.flatnonzero(~compact): ++ xs = np.arange(left_bin[row], right_bin[row] + 1) ++ ys = np.arange(bottom_bin[row], top_bin[row] + 1) ++ x_overlap = np.maximum( ++ 0.0, ++ np.minimum(right[row], edges[xs + 1]) ++ - np.maximum(left[row], edges[xs])) ++ y_overlap = np.maximum( ++ 0.0, ++ np.minimum(top[row], edges[ys + 1]) ++ - np.maximum(bottom[row], edges[ys])) ++ grid[np.ix_(ys, xs)] += ( ++ np.outer(y_overlap, x_overlap) / cell_area) ++ return grid ++ ++ ++def _rectangle_accumulate( ++ x_min, x_max, y_min, y_max, weights, grid_size): ++ """Accumulate weighted axis-aligned boxes with a 2D difference grid.""" ++ if len(weights) == 0: ++ return np.zeros((grid_size, grid_size), dtype=np.float32) ++ x_min = np.clip(np.asarray(x_min, dtype=np.float64), -1.0, 1.0) ++ x_max = np.clip(np.asarray(x_max, dtype=np.float64), -1.0, 1.0) ++ y_min = np.clip(np.asarray(y_min, dtype=np.float64), -1.0, 1.0) ++ y_max = np.clip(np.asarray(y_max, dtype=np.float64), -1.0, 1.0) ++ weights = np.asarray(weights, dtype=np.float64) ++ valid = (x_max >= x_min) & (y_max >= y_min) & np.isfinite(weights) ++ if not np.any(valid): ++ return np.zeros((grid_size, grid_size), dtype=np.float32) ++ x_min, x_max = x_min[valid], x_max[valid] ++ y_min, y_max = y_min[valid], y_max[valid] ++ weights = weights[valid] ++ left = np.clip( ++ np.floor((x_min + 1.0) / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ right = np.clip( ++ np.floor( ++ (np.nextafter(x_max, -np.inf) + 1.0) ++ / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ bottom = np.clip( ++ np.floor((y_min + 1.0) / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ top = np.clip( ++ np.floor( ++ (np.nextafter(y_max, -np.inf) + 1.0) ++ / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ diff = np.zeros((grid_size + 1, grid_size + 1), dtype=np.float64) ++ np.add.at(diff, (bottom, left), weights) ++ np.add.at(diff, (top + 1, left), -weights) ++ np.add.at(diff, (bottom, right + 1), -weights) ++ np.add.at(diff, (top + 1, right + 1), weights) ++ return np.cumsum( ++ np.cumsum(diff, axis=0), axis=1)[:grid_size, :grid_size].astype( ++ np.float32) ++ ++ ++def compute_mixed_size_spatial_grid(placement, grid_size=64): ++ """ ++ Compute the manuscript's five spatial channels from a complete DEF. ++ ++ Unlike ``compute_spatial_grid`` (the differentiable macro-only path), ++ this production preprocessing function uses every standard-cell ++ rectangle and every accepted full-net pin from the candidate placement. ++ """ ++ component_positions = np.asarray( ++ placement['component_positions'], dtype=np.float32) ++ component_sizes = np.asarray( ++ placement['component_sizes'], dtype=np.float32) ++ macro_mask = np.asarray( ++ placement['component_is_macro'], dtype=bool) ++ pin_positions = np.asarray( ++ placement['pin_positions'], dtype=np.float32) ++ pin_net_ids = np.asarray( ++ placement['pin_net_ids'], dtype=np.int32) ++ net_count = int(placement['net_count']) ++ ++ if ( ++ component_positions.shape != component_sizes.shape ++ or component_positions.ndim != 2 ++ or component_positions.shape[1] != 2 ++ or macro_mask.shape != (len(component_positions),) ++ or pin_positions.shape != (len(pin_net_ids), 2) ++ or net_count < 0 ++ or (len(pin_net_ids) ++ and (pin_net_ids.min() < 0 or pin_net_ids.max() >= net_count)) ++ ): ++ raise ValueError('Invalid mixed-size placement tensor shapes') ++ if not ( ++ np.isfinite(component_positions).all() ++ and np.isfinite(component_sizes).all() ++ and np.isfinite(pin_positions).all() ++ and np.all(component_sizes > 0) ++ ): ++ raise ValueError('Non-finite or nonpositive mixed-size placement') ++ ++ grid = np.zeros((5, grid_size, grid_size), dtype=np.float32) ++ ++ # Ch 0: exact standard-cell rectangle overlap divided by bin capacity. ++ standard_mask = ~macro_mask ++ grid[0] = _rasterize_rectangle_overlap( ++ component_positions[standard_mask], ++ component_sizes[standard_mask], ++ grid_size) ++ ++ # Ch 2: discrete macro occupancy. ++ macro_positions = component_positions[macro_mask] ++ macro_sizes = component_sizes[macro_mask] ++ for position, size in zip(macro_positions, macro_sizes): ++ left = int(np.clip( ++ np.floor( ++ (position[0] - size[0] / 2.0 + 1.0) ++ / 2.0 * grid_size), ++ 0, grid_size - 1)) ++ right = int(np.clip( ++ np.floor( ++ (np.nextafter( ++ position[0] + size[0] / 2.0, -np.inf) + 1.0) ++ / 2.0 * grid_size), ++ 0, grid_size - 1)) ++ bottom = int(np.clip( ++ np.floor( ++ (position[1] - size[1] / 2.0 + 1.0) ++ / 2.0 * grid_size), ++ 0, grid_size - 1)) ++ top = int(np.clip( ++ np.floor( ++ (np.nextafter( ++ position[1] + size[1] / 2.0, -np.inf) + 1.0) ++ / 2.0 * grid_size), ++ 0, grid_size - 1)) ++ grid[2, bottom:top + 1, left:right + 1] = 1.0 ++ ++ # Ch 1: full-net pin concentration. ++ if len(pin_positions): ++ pin_x = np.clip( ++ np.floor( ++ (pin_positions[:, 0] + 1.0) ++ / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ pin_y = np.clip( ++ np.floor( ++ (pin_positions[:, 1] + 1.0) ++ / 2.0 * grid_size).astype(np.int64), ++ 0, grid_size - 1) ++ np.add.at(grid[1], (pin_y, pin_x), 1.0) ++ ++ # Ch 3 and 4: full-net RUDY demand and bounding-box density. ++ if net_count and len(pin_net_ids): ++ counts = np.bincount(pin_net_ids, minlength=net_count) ++ x_min = np.full(net_count, np.inf, dtype=np.float64) ++ x_max = np.full(net_count, -np.inf, dtype=np.float64) ++ y_min = np.full(net_count, np.inf, dtype=np.float64) ++ y_max = np.full(net_count, -np.inf, dtype=np.float64) ++ np.minimum.at(x_min, pin_net_ids, pin_positions[:, 0]) ++ np.maximum.at(x_max, pin_net_ids, pin_positions[:, 0]) ++ np.minimum.at(y_min, pin_net_ids, pin_positions[:, 1]) ++ np.maximum.at(y_max, pin_net_ids, pin_positions[:, 1]) ++ valid_nets = ( ++ (counts >= 2) ++ & np.isfinite(x_min) & np.isfinite(x_max) ++ & np.isfinite(y_min) & np.isfinite(y_max)) ++ x_min, x_max = x_min[valid_nets], x_max[valid_nets] ++ y_min, y_max = y_min[valid_nets], y_max[valid_nets] ++ widths = np.maximum(x_max - x_min, 1e-6) ++ heights = np.maximum(y_max - y_min, 1e-6) ++ grid[3] = _rectangle_accumulate( ++ x_min, x_max, y_min, y_max, ++ 1.0 / (widths * heights), grid_size) ++ grid[4] = _rectangle_accumulate( ++ x_min, x_max, y_min, y_max, ++ np.ones(len(x_min), dtype=np.float64), grid_size) ++ ++ for channel in range(5): ++ # Difference-grid cancellation can leave sub-ulp negative residue. ++ np.maximum(grid[channel], 0.0, out=grid[channel]) ++ maximum = float(grid[channel].max()) ++ if maximum > 0: ++ grid[channel] /= maximum ++ np.minimum(grid[channel], 1.0, out=grid[channel]) ++ return grid ++ ++ ++def compute_node_features(positions, sizes, nets): + """ + Compute per-node features for the GAT branch. + +diff --git a/ppaplace/model.py b/ppaplace/model.py +index fa949d4..a8525c4 100644 +--- a/ppaplace/model.py ++++ b/ppaplace/model.py +@@ -24,11 +24,12 @@ class GATLayer(nn.Module): + self.dropout = nn.Dropout(dropout) + self.norm = nn.LayerNorm(out_dim) + +- def forward(self, h, edge_index): ++ def forward(self, h, edge_index, edge_weight=None): + """ + Args: + h: (N, in_dim) node features. + edge_index: (2, E) source -> target edges. ++ edge_weight: (E,) optional edge weights (e.g. shared net count). + Returns: + (N, out_dim) updated features. + """ +@@ -42,6 +43,10 @@ class GATLayer(nn.Module): + e_dst = (h_heads[dst] * self.a_dst).sum(dim=-1) + e = self.leaky_relu(e_src + e_dst) + ++ # Scale attention logits by edge weight (number of shared nets). ++ if edge_weight is not None: ++ e = e + edge_weight.unsqueeze(-1).log() ++ + e_max = torch.zeros(N, self.n_heads, device=h.device) + e_max.scatter_reduce_( + 0, dst.unsqueeze(1).expand_as(e), e, +@@ -105,12 +110,13 @@ class PPAPredictor(nn.Module): + nn.Linear(embed_dim, 4), + ) + +- def forward(self, node_features, edge_index, spatial_grid): ++ def forward(self, node_features, edge_index, spatial_grid, edge_weight=None): + """ + Args: + node_features: (B, N, 8) or (N, 8). + edge_index: (2, E). + spatial_grid: (B, 5, 64, 64) or (5, 64, 64). ++ edge_weight: (E,) optional edge weights. + Returns: + (B, 4) predictions [WNS, TNS, Power, Area]. + """ +@@ -125,7 +131,7 @@ class PPAPredictor(nn.Module): + for b in range(B): + h = self.node_encoder(node_features[b]) + for gat in self.gat_layers: +- h = self.gat_act(gat(h, edge_index)) ++ h = self.gat_act(gat(h, edge_index, edge_weight)) + graph_embeds.append(h.mean(dim=0)) + e_g = self.graph_proj(torch.stack(graph_embeds)) + +diff --git a/ppaplace/refine.py b/ppaplace/refine.py +index af7d53f..00c822d 100644 +--- a/ppaplace/refine.py ++++ b/ppaplace/refine.py +@@ -26,6 +26,7 @@ def refine_placement(model, circuit_data, positions_norm, device='cuda', + sizes = circuit_data['node_features'] + nets = circuit_data['nets'] + edge_index = torch.tensor(circuit_data['edge_index'], dtype=torch.long).to(device) ++ edge_weight = torch.tensor(circuit_data['edge_weights'], dtype=torch.float32).to(device) + + # Pre-compute static node features + pin_counts = np.zeros(len(sizes)) +@@ -72,7 +73,7 @@ def refine_placement(model, circuit_data, positions_norm, device='cuda', + spatial = diff_grid(pos, sizes_t, net_pin_positions) + node_feat = diff_node(pos, sizes_t, nets, pin_counts, net_degrees) + +- pred = model(node_feat.unsqueeze(0), edge_index, spatial.unsqueeze(0)) ++ pred = model(node_feat.unsqueeze(0), edge_index, spatial.unsqueeze(0), edge_weight) + loss = pred[0, 0] + pred[0, 1] # WNS + TNS + + loss.backward() +diff --git a/requirements.txt b/requirements.txt +index 76e0c5d..4fdc63b 100644 +--- a/requirements.txt ++++ b/requirements.txt +@@ -1,4 +1,7 @@ + torch>=2.0 +-numpy>=1.24 +-scipy>=1.10 +-pyyaml>=6.0 ++numpy>=1.23,<1.24 ++scipy>=1.10 ++matplotlib>=3.7 ++pyyaml>=6.0 ++ortools==9.10.4067 ++pandas==2.0.3 +diff --git a/scripts/evaluate.py b/scripts/evaluate.py +index c3bdb58..476fc80 100644 +--- a/scripts/evaluate.py ++++ b/scripts/evaluate.py +@@ -22,7 +22,7 @@ from ppaplace.data import load_chipbench_circuit + from scripts.train import load_circuit_samples + + +-def evaluate(model, samples, device, batch_size=64): ++def evaluate(model, samples, device, batch_size=32): + """Compute ranking metrics on a list of samples.""" + model.eval() + nf = torch.tensor(np.stack([s['node_features'] for s in samples]), +@@ -31,11 +31,12 @@ def evaluate(model, samples, device, batch_size=64): + dtype=torch.float32).to(device) + tg = np.stack([s['ppa_label'] for s in samples]) + ei = torch.tensor(samples[0]['edge_index'], dtype=torch.long).to(device) ++ ew = torch.tensor(samples[0]['edge_weights'], dtype=torch.float32).to(device) + + preds = [] + with torch.no_grad(): + for s in range(0, nf.size(0), batch_size): +- preds.append(model(nf[s:s + batch_size], ei, sp[s:s + batch_size])) ++ preds.append(model(nf[s:s + batch_size], ei, sp[s:s + batch_size], ew)) + pred_np = torch.cat(preds).cpu().numpy() + + results = {} +diff --git a/scripts/generate_data.py b/scripts/generate_data.py +index a0176c7..1087088 100644 +--- a/scripts/generate_data.py ++++ b/scripts/generate_data.py +@@ -1,212 +1,425 @@ +-#!/usr/bin/env python3 +-""" +-Generate training data: DREAMPlace with randomized hyperparameters. +- +-Pipeline per configuration: +- 1. Mixed-size global placement (macros + std cells move). +- 2. Macro legalization (fix overlaps). +- 3. Standard-cell-only global placement (macros fixed). +- +-Output DEFs are then evaluated through ChiPBench post-GRT flow to +-produce PPA labels. See scripts/grt_eval.sh. +- +-Usage: +- python scripts/generate_data.py --circuit bp_fe --n_configs 1000 \ +- --dreamplace_dir /path/to/DREAMPlace/install \ +- --output_dir data/dreamplace/bp_fe +-""" +- +-import os +-import sys +-import json +-import time +-import glob +-import shutil +-import subprocess +-import argparse +-import numpy as np +- +-sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) +- +- +-def random_hyperparams(rng): +- """Sample one DREAMPlace configuration.""" +- return { +- 'density_weight': float(10 ** rng.uniform(-5, -3)), +- 'learning_rate': float(10 ** rng.uniform(-3, -1.5)), +- 'gamma': float(rng.uniform(2.0, 10.0)), +- 'target_density': float(rng.uniform(0.70, 0.90)), +- 'stop_overflow': float(rng.choice([0.05, 0.07, 0.10, 0.15])), +- 'random_seed': int(rng.integers(1, 100000)), +- 'gp_noise_ratio': float(rng.uniform(0.01, 0.05)), +- 'wirelength': str(rng.choice(['weighted_average', 'logsumexp'])), +- 'macro_halo_x': int(rng.integers(0, 11)), +- 'macro_halo_y': int(rng.integers(0, 11)), +- 'iteration': int(rng.choice([800, 1000, 1200, 1500])), +- } +- +- +-def make_dreamplace_config(circuit, hp, lef_files, def_input, result_dir): +- """Build a DREAMPlace JSON config dict.""" +- return { +- 'gpu': 1, +- 'num_bins_x': 512, 'num_bins_y': 512, +- 'global_place_stages': [{ +- 'num_bins_x': 512, 'num_bins_y': 512, +- 'iteration': hp['iteration'], +- 'learning_rate': hp['learning_rate'], +- 'wirelength': hp['wirelength'], +- 'optimizer': 'nesterov', +- }], +- 'target_density': hp['target_density'], +- 'density_weight': hp['density_weight'], +- 'gamma': hp['gamma'], +- 'random_seed': hp['random_seed'], +- 'ignore_net_degree': 100, 'enable_fillers': 1, +- 'gp_noise_ratio': hp['gp_noise_ratio'], +- 'global_place_flag': 1, 'legalize_flag': 0, +- 'detailed_place_flag': 0, 'detailed_place_engine': '', +- 'detailed_place_command': '', +- 'stop_overflow': hp['stop_overflow'], +- 'dtype': 'float32', 'plot_flag': 0, +- 'random_center_init_flag': 1, 'sort_nets_by_degree': 0, +- 'num_threads': 8, 'deterministic_flag': 0, 'sol_file_format': 'DEF', +- 'macro_place_flag': 1, +- 'macro_halo_x': hp['macro_halo_x'], +- 'macro_halo_y': hp['macro_halo_y'], +- 'lef_input': lef_files, +- 'def_input': def_input, +- 'result_dir': result_dir, +- } +- +- +-def run_dreamplace(dreamplace_dir, config_path, timeout=300): +- """Run DREAMPlace and return (success, hpwl).""" +- cmd = f"cd {dreamplace_dir} && python3 dreamplace/Placer.py {config_path} 2>&1" +- hpwl = None +- try: +- proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, +- stderr=subprocess.STDOUT, text=True) +- for line in proc.stdout: +- if 'wHPWL' in line: +- parts = line.split('wHPWL') +- if len(parts) > 1: +- try: +- hpwl = float(parts[1].split(',')[0].strip()) +- except ValueError: +- pass +- proc.wait(timeout=timeout) +- return proc.returncode == 0, hpwl +- except subprocess.TimeoutExpired: +- proc.kill() +- return False, None +- +- +-def find_gp_def(result_dir): +- """Find .gp.def output in DREAMPlace result directory.""" +- matches = glob.glob(os.path.join(result_dir, '**', '*.gp.def'), recursive=True) +- return matches[0] if matches else None +- +- +-def main(): +- parser = argparse.ArgumentParser() +- parser.add_argument('--circuit', required=True) +- parser.add_argument('--dreamplace_dir', required=True, +- help='Path to DREAMPlace install directory') +- parser.add_argument('--output_dir', default=None) +- parser.add_argument('--n_configs', type=int, default=1000) +- parser.add_argument('--n_target', type=int, default=500) +- parser.add_argument('--master_seed', type=int, default=42) +- parser.add_argument('--skip_existing', action='store_true') +- args = parser.parse_args() +- +- circuit = args.circuit +- dp_dir = args.dreamplace_dir +- bench_dir = os.path.join(dp_dir, 'benchmarks', 'chipbench', circuit) +- +- if args.output_dir is None: +- args.output_dir = os.path.join('data', 'dreamplace', circuit) +- os.makedirs(args.output_dir, exist_ok=True) +- +- # Discover LEF files +- lef_dir = os.path.join(bench_dir, 'lef') +- lef_files = [os.path.join('benchmarks', 'chipbench', circuit, 'lef', f) +- for f in sorted(os.listdir(lef_dir)) if f.endswith('.lef')] +- +- def_input = f'benchmarks/chipbench/{circuit}/def/pre_place.def' +- +- rng = np.random.default_rng(args.master_seed) +- configs = [random_hyperparams(rng) for _ in range(args.n_configs)] +- +- # Save configs +- for i, hp in enumerate(configs): +- hp['config_id'] = f'cfg_{i:03d}' +- with open(os.path.join(args.output_dir, 'configs.json'), 'w') as f: +- json.dump(configs, f, indent=2) +- +- n_success = 0 +- for hp in configs: +- cid = hp['config_id'] +- final_def = os.path.join(args.output_dir, f'{cid}_final.def') +- +- if args.skip_existing and os.path.exists(final_def): +- n_success += 1 +- continue +- +- # Step 1: mixed-size GP +- result_dir = f'results/train_{circuit}_mixed_{hp["random_seed"]}' +- cfg = make_dreamplace_config(circuit, hp, lef_files, def_input, result_dir) +- cfg_path = os.path.join(bench_dir, f'_tmp_{cid}.json') +- with open(cfg_path, 'w') as f: +- json.dump(cfg, f, indent=2) +- +- ok, _ = run_dreamplace(dp_dir, cfg_path) +- gp_def = find_gp_def(os.path.join(dp_dir, result_dir)) +- if not ok or not gp_def: +- continue +- +- # Step 2: Legalization +- from ppaplace.data import load_chipbench_circuit +- from ppaplace.legalize import legalize_dreamplace_output +- circuit_dir = os.path.join(dp_dir, 'benchmarks', 'chipbench', circuit) +- circuit_data = load_chipbench_circuit(circuit_dir, use_reference=False) +- leg_name = f'train_{cid}_legalized.def' +- leg_path = os.path.join(bench_dir, 'def', leg_name) +- result = legalize_dreamplace_output(gp_def, circuit_data, leg_path) +- if not result.get('success'): +- continue +- +- # Step 3: std-cell-only GP +- cfg3 = make_dreamplace_config( +- circuit, hp, lef_files, +- f'benchmarks/chipbench/{circuit}/def/{leg_name}', +- f'results/train_{circuit}_stdcell_{hp["random_seed"]}', +- ) +- cfg3.pop('macro_place_flag', None) +- cfg3_path = os.path.join(bench_dir, f'_tmp_{cid}_sc.json') +- with open(cfg3_path, 'w') as f: +- json.dump(cfg3, f, indent=2) +- +- ok, _ = run_dreamplace(dp_dir, cfg3_path) +- sc_def = find_gp_def(os.path.join( +- dp_dir, f'results/train_{circuit}_stdcell_{hp["random_seed"]}')) +- if sc_def: +- shutil.copy2(sc_def, final_def) +- n_success += 1 +- print(f" {cid}: OK ({n_success}/{args.n_target})") +- +- # Cleanup temp configs +- for p in [cfg_path, cfg3_path]: +- try: +- os.remove(p) +- except OSError: +- pass +- +- if n_success >= args.n_target: +- break +- +- print(f"\nDone: {n_success}/{args.n_target} successful placements") +- +- +-if __name__ == '__main__': +- main() ++#!/usr/bin/env python3 ++""" ++Generate training data: DREAMPlace with randomized hyperparameters. ++ ++Pipeline per configuration: ++ 1. Mixed-size global placement (macros + std cells move). ++ 2. Macro legalization (fix overlaps). ++ 3. Standard-cell-only global placement (macros fixed). ++ ++Output DEFs are then evaluated through ChiPBench post-GRT flow to ++produce PPA labels. See scripts/grt_eval.sh. ++ ++Usage: ++ python scripts/generate_data.py --circuit bp_fe --n_configs 1000 \ ++ --dreamplace_dir /path/to/DREAMPlace/install \ ++ --output_dir data/dreamplace/bp_fe ++""" ++ ++import os ++import sys ++import json ++import time ++import glob ++import shutil ++import subprocess ++import argparse ++import shlex ++import signal ++import threading ++from concurrent.futures import ThreadPoolExecutor, as_completed ++import numpy as np ++ ++sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) ++ ++ ++def random_hyperparams(rng): ++ """Sample one DREAMPlace configuration.""" ++ macro_halo = int(rng.integers(0, 11)) ++ return { ++ 'density_weight': float(10 ** rng.uniform(-5, -3)), ++ 'learning_rate': float(10 ** rng.uniform(-3, -1.5)), ++ 'gamma': float(rng.uniform(2.0, 10.0)), ++ 'target_density': float(rng.uniform(0.70, 0.90)), ++ 'stop_overflow': float(rng.choice([0.05, 0.07, 0.10, 0.15])), ++ 'random_seed': int(rng.integers(1, 100000)), ++ 'gp_noise_ratio': float(rng.uniform(0.01, 0.05)), ++ 'wirelength': str(rng.choice(['weighted_average', 'logsumexp'])), ++ 'macro_halo_x': macro_halo, ++ 'macro_halo_y': macro_halo, ++ 'iteration': int(rng.choice([800, 1000, 1200, 1500])), ++ } ++ ++ ++def order_lef_files(lef_dir): ++ """Return LEFs in parser-safe order: technology, cells, then macros.""" ++ names = [name for name in os.listdir(lef_dir) if name.endswith('.lef')] ++ ++ def priority(name): ++ lower = name.lower() ++ if 'tech' in lower: ++ return 0, lower ++ if lower in ('cells.lef',) or 'macro.mod.lef' in lower: ++ return 1, lower ++ return 2, lower ++ ++ return [os.path.join(lef_dir, name) for name in sorted(names, key=priority)] ++ ++ ++def make_dreamplace_config(circuit, hp, lef_files, def_input, result_dir): ++ """Build a DREAMPlace JSON config dict.""" ++ return { ++ 'gpu': 1, ++ 'num_bins_x': 512, 'num_bins_y': 512, ++ 'global_place_stages': [{ ++ 'num_bins_x': 512, 'num_bins_y': 512, ++ 'iteration': hp['iteration'], ++ 'learning_rate': hp['learning_rate'], ++ 'wirelength': hp['wirelength'], ++ 'optimizer': 'nesterov', ++ }], ++ 'target_density': hp['target_density'], ++ 'density_weight': hp['density_weight'], ++ 'gamma': hp['gamma'], ++ 'random_seed': hp['random_seed'], ++ 'ignore_net_degree': 100, 'enable_fillers': 1, ++ 'gp_noise_ratio': hp['gp_noise_ratio'], ++ 'global_place_flag': 1, 'legalize_flag': 0, ++ 'detailed_place_flag': 0, 'detailed_place_engine': '', ++ 'detailed_place_command': '', ++ 'stop_overflow': hp['stop_overflow'], ++ 'dtype': 'float32', 'plot_flag': 0, ++ 'random_center_init_flag': 1, 'sort_nets_by_degree': 0, ++ 'num_threads': 8, 'deterministic_flag': 0, 'sol_file_format': 'DEF', ++ 'macro_place_flag': 1, ++ 'macro_halo_x': hp['macro_halo_x'], ++ 'macro_halo_y': hp['macro_halo_y'], ++ 'lef_input': lef_files, ++ 'def_input': def_input, ++ 'result_dir': result_dir, ++ } ++ ++ ++def run_dreamplace(dreamplace_dir, config_path, dreamplace_cmd=None, ++ timeout=300, log_path=None): ++ """Run DREAMPlace and return ``(success, hpwl)``. ++ ++ ``dreamplace_cmd`` may name a launcher that activates DREAMPlace's Python ++ environment (for example ``~/bin/dreamplace-chipbench``). Using an argv ++ list instead of ``shell=True`` also keeps paths and process termination ++ predictable on remote machines. ++ """ ++ if dreamplace_cmd: ++ cmd = shlex.split(dreamplace_cmd) + [os.path.abspath(config_path)] ++ else: ++ cmd = [sys.executable, ++ os.path.join(os.path.abspath(dreamplace_dir), ++ 'dreamplace', 'Placer.py'), ++ os.path.abspath(config_path)] ++ hpwl = None ++ try: ++ proc = subprocess.Popen( ++ cmd, cwd=dreamplace_dir, stdout=subprocess.PIPE, ++ stderr=subprocess.STDOUT, text=True, start_new_session=True) ++ output, _ = proc.communicate(timeout=timeout) ++ if log_path: ++ os.makedirs(os.path.dirname(log_path), exist_ok=True) ++ with open(log_path, 'w', encoding='utf-8') as stream: ++ stream.write(output) ++ for line in output.splitlines(): ++ if 'wHPWL' in line: ++ parts = line.split('wHPWL') ++ if len(parts) > 1: ++ try: ++ hpwl = float(parts[1].split(',')[0].strip()) ++ except ValueError: ++ pass ++ return proc.returncode == 0, hpwl ++ except subprocess.TimeoutExpired: ++ try: ++ os.killpg(proc.pid, signal.SIGKILL) ++ except (AttributeError, ProcessLookupError): ++ proc.kill() ++ output, _ = proc.communicate() ++ if log_path: ++ os.makedirs(os.path.dirname(log_path), exist_ok=True) ++ with open(log_path, 'w', encoding='utf-8') as stream: ++ stream.write(output) ++ stream.write(f'\nTIMEOUT after {timeout} seconds\n') ++ return False, None ++ ++ ++def find_gp_def(result_dir): ++ """Find .gp.def output in DREAMPlace result directory.""" ++ matches = glob.glob(os.path.join(result_dir, '**', '*.gp.def'), recursive=True) ++ return matches[0] if matches else None ++ ++ ++def main(): ++ parser = argparse.ArgumentParser() ++ parser.add_argument('--circuit', required=True) ++ parser.add_argument('--dreamplace_dir', required=True, ++ help='Path to DREAMPlace install directory') ++ parser.add_argument( ++ '--benchmark_root', default=None, ++ help='Root containing /lef and /def; defaults to ' ++ '/benchmarks/chipbench') ++ parser.add_argument( ++ '--dreamplace_cmd', default=None, ++ help='Optional DREAMPlace launcher command; defaults to the current ' ++ 'Python interpreter and /dreamplace/Placer.py') ++ parser.add_argument('--timeout', type=int, default=900, ++ help='Per-DREAMPlace-stage timeout in seconds') ++ parser.add_argument('--output_dir', default=None) ++ parser.add_argument('--n_configs', type=int, default=1000) ++ parser.add_argument( ++ '--n_target', type=int, default=500, ++ help='Stop after this many DREAMPlace successes; use 0 to evaluate ' ++ 'all sampled configurations so later OpenROAD failures can be ' ++ 'replaced by the next successful configuration') ++ parser.add_argument('--master_seed', type=int, default=42) ++ parser.add_argument( ++ '--jobs', type=int, default=1, ++ help='Number of configurations to evaluate concurrently. Parallel ' ++ 'execution is supported when --n_target=0; the sampled ' ++ 'configuration list remains deterministic.') ++ parser.add_argument('--skip_existing', action='store_true') ++ parser.add_argument( ++ '--keep_intermediates', action='store_true', ++ help='Keep mixed-size, legalized, and std-cell DREAMPlace outputs. ' ++ 'By default only final DEFs, configs, status, and logs are kept.') ++ args = parser.parse_args() ++ if args.jobs < 1: ++ parser.error('--jobs must be at least 1') ++ if args.jobs > 1 and args.n_target != 0: ++ parser.error('--jobs > 1 requires --n_target=0') ++ ++ circuit = args.circuit ++ dp_dir = os.path.abspath(os.path.expanduser(args.dreamplace_dir)) ++ benchmark_root = (args.benchmark_root or ++ os.path.join(dp_dir, 'benchmarks', 'chipbench')) ++ benchmark_root = os.path.abspath(os.path.expanduser(benchmark_root)) ++ bench_dir = os.path.join(benchmark_root, circuit) ++ ++ if args.output_dir is None: ++ args.output_dir = os.path.join('data', 'dreamplace', circuit) ++ args.output_dir = os.path.abspath(os.path.expanduser(args.output_dir)) ++ os.makedirs(args.output_dir, exist_ok=True) ++ ++ # Discover LEF files ++ lef_dir = os.path.join(bench_dir, 'lef') ++ lef_files = order_lef_files(lef_dir) ++ ++ def_dir = os.path.join(bench_dir, 'def') ++ def_candidates = [ ++ os.path.join(def_dir, 'pre_place.def'), ++ os.path.join(def_dir, 'floorplan_unplaced.def'), ++ os.path.join(def_dir, 'macro_placed.def'), ++ ] ++ def_input = next((path for path in def_candidates if os.path.isfile(path)), ++ None) ++ if def_input is None: ++ raise FileNotFoundError( ++ f'No DREAMPlace input DEF found in {def_dir}; expected one of ' ++ 'pre_place.def, floorplan_unplaced.def, or macro_placed.def') ++ ++ runtime_config_dir = os.path.join(args.output_dir, 'runtime_configs') ++ runtime_result_dir = os.path.join(args.output_dir, 'dreamplace_results') ++ os.makedirs(runtime_config_dir, exist_ok=True) ++ os.makedirs(runtime_result_dir, exist_ok=True) ++ ++ rng = np.random.default_rng(args.master_seed) ++ configs = [random_hyperparams(rng) for _ in range(args.n_configs)] ++ ++ # Save configs ++ for i, hp in enumerate(configs): ++ hp['config_id'] = f'cfg_{i:03d}' ++ with open(os.path.join(args.output_dir, 'configs.json'), 'w') as f: ++ json.dump(configs, f, indent=2) ++ ++ status_path = os.path.join(args.output_dir, 'generation_status.json') ++ try: ++ with open(status_path, encoding='utf-8') as stream: ++ generation_status = json.load(stream) ++ except (OSError, ValueError): ++ generation_status = {} ++ ++ status_lock = threading.Lock() ++ ++ def record_status(cid, status, **details): ++ # A single lock protects both the in-memory dictionary and the atomic ++ # status-file replacement when configurations run concurrently. ++ with status_lock: ++ generation_status[cid] = { ++ 'status': status, ++ 'updated_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', ++ time.gmtime()), ++ **details, ++ } ++ temporary = status_path + '.tmp' ++ with open(temporary, 'w', encoding='utf-8') as stream: ++ json.dump(generation_status, stream, indent=2, sort_keys=True) ++ os.replace(temporary, status_path) ++ ++ # Parsing the circuit for every sampled configuration is prohibitively ++ # expensive for the larger ChiPBench designs. Cache it once per process. ++ from ppaplace.data import load_chipbench_circuit ++ from ppaplace.legalize import legalize_dreamplace_output ++ circuit_data = load_chipbench_circuit(bench_dir, use_reference=False) ++ ++ def process_config(hp): ++ """Run one deterministic sampled configuration. ++ ++ All paths are configuration-specific; the only shared mutable state is ++ the generation-status file, which ``record_status`` serializes. ++ """ ++ cid = hp['config_id'] ++ final_def = os.path.join(args.output_dir, f'{cid}_final.def') ++ archived_def = final_def + '.zst' ++ config_started = time.time() ++ ++ with status_lock: ++ prior_status = generation_status.get(cid, {}).get('status') ++ archived_success = False ++ if (args.skip_existing and os.path.isfile(archived_def) ++ and prior_status == 'success'): ++ archived_success = subprocess.run( ++ ['zstd', '-q', '-t', archived_def], ++ stdin=subprocess.DEVNULL, ++ stdout=subprocess.DEVNULL, ++ stderr=subprocess.DEVNULL, ++ ).returncode == 0 ++ if args.skip_existing and (os.path.exists(final_def) ++ or archived_success): ++ # Preserve original HPWL and timing metadata across a resumable ++ # restart. A validated .def.zst is the lossless temporary-corpus ++ # representation used for storage-heavy circuits. ++ if prior_status != 'success': ++ record_status(cid, 'success', final_def=final_def, ++ reused_existing=True) ++ return True ++ ++ # Step 1: mixed-size GP ++ result_dir = os.path.join(runtime_result_dir, f'{cid}_mixed') ++ stdcell_result_dir = os.path.join(runtime_result_dir, ++ f'{cid}_stdcell') ++ leg_path = os.path.join(runtime_result_dir, f'{cid}_legalized.def') ++ cfg = make_dreamplace_config(circuit, hp, lef_files, def_input, result_dir) ++ cfg_path = os.path.join(runtime_config_dir, f'{cid}_mixed.json') ++ cfg3_path = os.path.join(runtime_config_dir, f'{cid}_stdcell.json') ++ with open(cfg_path, 'w') as f: ++ json.dump(cfg, f, indent=2) ++ ++ try: ++ mixed_started = time.time() ++ ok, mixed_hpwl = run_dreamplace( ++ dp_dir, cfg_path, args.dreamplace_cmd, args.timeout, ++ os.path.join(args.output_dir, 'logs', f'{cid}_mixed.log')) ++ mixed_seconds = time.time() - mixed_started ++ gp_def = find_gp_def(result_dir) ++ if not ok or not gp_def: ++ record_status(cid, 'mixed_failed', ++ mixed_seconds=mixed_seconds, ++ total_seconds=time.time() - config_started) ++ return False ++ ++ # Step 2: Legalization ++ legalize_started = time.time() ++ result = legalize_dreamplace_output(gp_def, circuit_data, leg_path) ++ legalize_seconds = time.time() - legalize_started ++ if not result.get('success'): ++ record_status(cid, 'legalization_failed', ++ mixed_seconds=mixed_seconds, ++ legalize_seconds=legalize_seconds, ++ total_seconds=time.time() - config_started, ++ legalizer=result) ++ return False ++ ++ # Step 3: std-cell-only GP ++ cfg3 = make_dreamplace_config( ++ circuit, hp, lef_files, leg_path, stdcell_result_dir) ++ cfg3.pop('macro_place_flag', None) ++ with open(cfg3_path, 'w') as f: ++ json.dump(cfg3, f, indent=2) ++ ++ stdcell_started = time.time() ++ ok, stdcell_hpwl = run_dreamplace( ++ dp_dir, cfg3_path, args.dreamplace_cmd, args.timeout, ++ os.path.join(args.output_dir, 'logs', f'{cid}_stdcell.log')) ++ stdcell_seconds = time.time() - stdcell_started ++ sc_def = find_gp_def(stdcell_result_dir) ++ if ok and sc_def: ++ shutil.copy2(sc_def, final_def) ++ record_status( ++ cid, 'success', final_def=final_def, ++ mixed_hpwl=mixed_hpwl, stdcell_hpwl=stdcell_hpwl, ++ mixed_seconds=mixed_seconds, ++ legalize_seconds=legalize_seconds, ++ stdcell_seconds=stdcell_seconds, ++ total_seconds=time.time() - config_started) ++ return True ++ ++ record_status( ++ cid, 'stdcell_failed', mixed_hpwl=mixed_hpwl, ++ mixed_seconds=mixed_seconds, ++ legalize_seconds=legalize_seconds, ++ stdcell_seconds=stdcell_seconds, ++ total_seconds=time.time() - config_started) ++ return False ++ finally: ++ for path in (cfg_path, cfg3_path): ++ try: ++ os.remove(path) ++ except OSError: ++ pass ++ if not args.keep_intermediates: ++ shutil.rmtree(result_dir, ignore_errors=True) ++ shutil.rmtree(stdcell_result_dir, ignore_errors=True) ++ try: ++ os.remove(leg_path) ++ except OSError: ++ pass ++ ++ n_success = 0 ++ if args.jobs == 1: ++ for hp in configs: ++ if process_config(hp): ++ n_success += 1 ++ target_text = (str(args.n_target) if args.n_target > 0 ++ else 'all') ++ print(f" {hp['config_id']}: OK ({n_success}/{target_text})") ++ if args.n_target > 0 and n_success >= args.n_target: ++ break ++ else: ++ with ThreadPoolExecutor(max_workers=args.jobs) as executor: ++ futures = {executor.submit(process_config, hp): hp ++ for hp in configs} ++ completed = 0 ++ for future in as_completed(futures): ++ hp = futures[future] ++ completed += 1 ++ if future.result(): ++ n_success += 1 ++ print(f" {hp['config_id']}: OK " ++ f"({n_success} successful, {completed}/" ++ f"{len(configs)} completed)") ++ ++ target_text = str(args.n_target) if args.n_target > 0 else 'all sampled' ++ print(f"\nDone: {n_success}/{target_text} successful placements") ++ with open(os.path.join(args.output_dir, 'generation_complete.json'), ++ 'w', encoding='utf-8') as stream: ++ json.dump({ ++ 'circuit': circuit, ++ 'sampled_configurations': args.n_configs, ++ 'dreamplace_successes': n_success, ++ 'requested_target': args.n_target, ++ 'master_seed': args.master_seed, ++ 'completed_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', ++ time.gmtime()), ++ }, stream, indent=2, sort_keys=True) ++ if args.n_target > 0 and n_success < args.n_target: ++ raise SystemExit(1) ++ ++ ++if __name__ == '__main__': ++ main() +diff --git a/scripts/grt_eval.sh b/scripts/grt_eval.sh +index 8c54f05..a704b1c 100644 +--- a/scripts/grt_eval.sh ++++ b/scripts/grt_eval.sh +@@ -1,98 +1,254 @@ +-#!/bin/bash +-# Evaluate placement DEFs through ChiPBench post-GRT flow. +-# +-# Runs inside the ChiPBench Docker container. Processes up to +-# MAX_PARALLEL DEFs concurrently. +-# +-# Usage (inside Docker): +-# bash grt_eval.sh [max_parallel] +-# +-# Example: +-# docker exec bash /scripts/grt_eval.sh bp_fe /data/defs /data/grt_jsons 8 +- +-set -e +- +-CIRCUIT=$1 +-DEF_DIR=$2 +-OUTPUT_DIR=$3 +-MAX_PARALLEL=${4:-8} +- +-if [ -z "$CIRCUIT" ] || [ -z "$DEF_DIR" ] || [ -z "$OUTPUT_DIR" ]; then +- echo "Usage: grt_eval.sh [max_parallel]" +- exit 1 +-fi +- +-CHIPBENCH_DIR="/ChiPBench/flow" +-DESIGN_DIR="$CHIPBENCH_DIR/designs/nangate45/$CIRCUIT" +- +-mkdir -p "$OUTPUT_DIR" +- +-# Map circuit names to ChiPBench design config paths +-get_design_config() { +- echo "$CHIPBENCH_DIR/designs/nangate45/$1/config.mk" +-} +- +-CONFIG=$(get_design_config "$CIRCUIT") +-if [ ! -f "$CONFIG" ]; then +- echo "Design config not found: $CONFIG" +- exit 1 +-fi +- +-eval_one_def() { +- local DEF_PATH=$1 +- local BASENAME=$(basename "$DEF_PATH" .def) +- local EVAL_NAME="eval_${BASENAME}" +- local JSON_OUT="$OUTPUT_DIR/${BASENAME}_grt.json" +- +- if [ -f "$JSON_OUT" ]; then +- return 0 +- fi +- +- # Preprocess DEF: strip backslash-escaped names if needed +- local CLEAN_DEF="/tmp/${BASENAME}_clean.def" +- sed 's/\\//g' "$DEF_PATH" > "$CLEAN_DEF" +- +- # Remove BLOCKAGES section if present (causes issues with some circuits) +- sed -i '/^BLOCKAGES/,/^END BLOCKAGES/d' "$CLEAN_DEF" +- +- # Run flow stages: def2db -> place-global -> CTS -> GRT +- cd "$CHIPBENCH_DIR" +- +- make DESIGN_CONFIG="$CONFIG" \ +- FLOW_VARIANT="$EVAL_NAME" \ +- ADDITIONAL_DEF="$CLEAN_DEF" \ +- do-def2db 2>/dev/null || return 1 +- +- make DESIGN_CONFIG="$CONFIG" \ +- FLOW_VARIANT="$EVAL_NAME" \ +- do-place-global 2>/dev/null || return 1 +- +- make DESIGN_CONFIG="$CONFIG" \ +- FLOW_VARIANT="$EVAL_NAME" \ +- do-cts 2>/dev/null || return 1 +- +- make DESIGN_CONFIG="$CONFIG" \ +- FLOW_VARIANT="$EVAL_NAME" \ +- do-grt 2>/dev/null || return 1 +- +- # Extract GRT metrics JSON +- local GRT_JSON="$CHIPBENCH_DIR/logs/nangate45/$CIRCUIT/$EVAL_NAME/5_1_grt.json" +- if [ -f "$GRT_JSON" ]; then +- cp "$GRT_JSON" "$JSON_OUT" +- fi +- +- # Cleanup +- rm -f "$CLEAN_DEF" +- rm -rf "$CHIPBENCH_DIR/results/nangate45/$CIRCUIT/$EVAL_NAME" +- rm -rf "$CHIPBENCH_DIR/logs/nangate45/$CIRCUIT/$EVAL_NAME" +-} +- +-export -f eval_one_def +-export OUTPUT_DIR CHIPBENCH_DIR CONFIG CIRCUIT +- +-# Process all DEFs in parallel +-find "$DEF_DIR" -name "*.def" -type f | \ +- xargs -P "$MAX_PARALLEL" -I {} bash -c 'eval_one_def "$@"' _ {} +- +-N_DONE=$(ls "$OUTPUT_DIR"/*.json 2>/dev/null | wc -l) +-echo "Done: $N_DONE GRT JSONs in $OUTPUT_DIR" ++#!/bin/bash ++# Evaluate placement DEFs through ChiPBench post-GRT flow. ++# ++# Runs either natively or inside the ChiPBench Docker container. Processes up ++# to MAX_PARALLEL DEFs concurrently. For a native installation, source ++# scripts/server/chipbench-env.sh first or export CHIPBENCH_FLOW_DIR and ++# OPENROAD_EXE. ++# ++# Usage (inside Docker): ++# bash grt_eval.sh [max_parallel] ++# ++# Example: ++# docker exec bash /scripts/grt_eval.sh bp_fe /data/defs /data/grt_jsons 8 ++ ++set -euo pipefail ++ ++CIRCUIT=${1:-} ++DEF_DIR=${2:-} ++OUTPUT_DIR=${3:-} ++REQUESTED_MAX_PARALLEL=${4:-8} ++STAGE_TIMEOUT=${STAGE_TIMEOUT:-7200} ++STOP_AFTER_LABELS=${STOP_AFTER_LABELS:-0} ++ ++if [ -z "$CIRCUIT" ] || [ -z "$DEF_DIR" ] || [ -z "$OUTPUT_DIR" ]; then ++ echo "Usage: grt_eval.sh [max_parallel]" ++ exit 1 ++fi ++if ! [[ "$STOP_AFTER_LABELS" =~ ^[0-9]+$ ]]; then ++ echo "STOP_AFTER_LABELS must be a nonnegative integer." >&2 ++ exit 2 ++fi ++ ++# OpenROAD memory scales strongly with netlist size. The 64 GiB reproduction ++# server also runs the independent fidelity sweep, so cap concurrent GRT ++# workers by circuit to avoid swap exhaustion/OOM on the largest designs. ++# The caller's value remains an upper bound, allowing a more conservative ++# launch without changing this script. ++case "$CIRCUIT" in ++ isa_npu|bp_multi) ++ MEMORY_SAFE_PARALLEL=1 ++ DEFAULT_WORKER_MEMORY_MIB=8192 ++ ;; ++ swerv_wrapper43|vga_lcd) ++ MEMORY_SAFE_PARALLEL=2 ++ DEFAULT_WORKER_MEMORY_MIB=5120 ++ ;; ++ mor1kx) ++ MEMORY_SAFE_PARALLEL=4 ++ DEFAULT_WORKER_MEMORY_MIB=3584 ++ ;; ++ bp_fe|bp_be12|or1200|ethernet|dft68) ++ MEMORY_SAFE_PARALLEL=16 ++ DEFAULT_WORKER_MEMORY_MIB=2048 ++ ;; ++ *) ++ MEMORY_SAFE_PARALLEL=8 ++ DEFAULT_WORKER_MEMORY_MIB=3072 ++ ;; ++esac ++MAX_PARALLEL=$REQUESTED_MAX_PARALLEL ++if (( MAX_PARALLEL > MEMORY_SAFE_PARALLEL )); then ++ MAX_PARALLEL=$MEMORY_SAFE_PARALLEL ++fi ++ ++# Other research jobs share the server. Limit a new batch from the currently ++# available memory as well as from the per-circuit hard cap. This check only ++# chooses how many independent configurations start; it does not change an ++# OpenROAD command or any generated label. ++MEMORY_RESERVE_MIB=${PPAPLACE_MEMORY_RESERVE_MIB:-8192} ++WORKER_MEMORY_MIB=${PPAPLACE_GRT_WORKER_MIB:-$DEFAULT_WORKER_MEMORY_MIB} ++MEMORY_POLL_SECONDS=${PPAPLACE_MEMORY_POLL_SECONDS:-60} ++if ! [[ "$MEMORY_RESERVE_MIB" =~ ^[0-9]+$ ]] || \ ++ ! [[ "$WORKER_MEMORY_MIB" =~ ^[1-9][0-9]*$ ]] || \ ++ ! [[ "$MEMORY_POLL_SECONDS" =~ ^[1-9][0-9]*$ ]]; then ++ echo "PPAPLACE_MEMORY_RESERVE_MIB must be nonnegative; PPAPLACE_GRT_WORKER_MIB and PPAPLACE_MEMORY_POLL_SECONDS must be positive integers." >&2 ++ exit 2 ++fi ++MINIMUM_REQUIRED_MEMORY_MIB=$((MEMORY_RESERVE_MIB + WORKER_MEMORY_MIB)) ++while true; do ++ AVAILABLE_MEMORY_MIB=$(awk \ ++ '/^MemAvailable:/ { print int($2 / 1024); exit }' /proc/meminfo) ++ if [[ -z "$AVAILABLE_MEMORY_MIB" ]]; then ++ echo "Cannot read MemAvailable from /proc/meminfo." >&2 ++ exit 2 ++ fi ++ if (( AVAILABLE_MEMORY_MIB >= MINIMUM_REQUIRED_MEMORY_MIB )); then ++ break ++ fi ++ echo "Waiting for post-GRT memory: circuit=$CIRCUIT available_mib=$AVAILABLE_MEMORY_MIB required_mib=$MINIMUM_REQUIRED_MEMORY_MIB reserve_mib=$MEMORY_RESERVE_MIB worker_mib=$WORKER_MEMORY_MIB" ++ sleep "$MEMORY_POLL_SECONDS" ++done ++MEMORY_LIMITED_PARALLEL=$((( ++ AVAILABLE_MEMORY_MIB - MEMORY_RESERVE_MIB) / WORKER_MEMORY_MIB)) ++if (( MAX_PARALLEL > MEMORY_LIMITED_PARALLEL )); then ++ MAX_PARALLEL=$MEMORY_LIMITED_PARALLEL ++fi ++echo "Post-GRT concurrency: requested=$REQUESTED_MAX_PARALLEL effective=$MAX_PARALLEL circuit=$CIRCUIT hard_cap=$MEMORY_SAFE_PARALLEL available_mib=$AVAILABLE_MEMORY_MIB reserve_mib=$MEMORY_RESERVE_MIB worker_mib=$WORKER_MEMORY_MIB" ++ ++CHIPBENCH_DIR=${CHIPBENCH_FLOW_DIR:-${CHIPBENCH_ROOT:-/ChiPBench}/flow} ++ ++mkdir -p "$OUTPUT_DIR" ++ ++# Map circuit names to ChiPBench design config paths ++get_design_config() { ++ local design_key ++ case "$1" in ++ bp_fe) design_key=bp_fe_top ;; ++ bp_be) design_key=bp_be_top ;; ++ bp_multi) design_key=bp_multi_top ;; ++ *) design_key=$1 ;; ++ esac ++ echo "$CHIPBENCH_DIR/designs/nangate45/$design_key/config.mk" ++} ++ ++CONFIG=$(get_design_config "$CIRCUIT") ++if [ ! -f "$CONFIG" ]; then ++ echo "Design config not found: $CONFIG" ++ exit 1 ++fi ++DESIGN_NICKNAME=$(sed -n \ ++ 's/^export[[:space:]]\+DESIGN_NICKNAME[[:space:]]*=[[:space:]]*//p' \ ++ "$CONFIG" | head -n 1) ++if [ -z "$DESIGN_NICKNAME" ]; then ++ DESIGN_NICKNAME=$(basename "$(dirname "$CONFIG")") ++fi ++ ++if [ ! -x "${OPENROAD_EXE:-}" ]; then ++ echo "OPENROAD_EXE is not executable: ${OPENROAD_EXE:-}" >&2 ++ echo "Source scripts/server/chipbench-env.sh (native) or /ChiPBench/env.sh (Docker)." >&2 ++ exit 1 ++fi ++ ++eval_one_def() { ++ local DEF_PATH=$1 ++ local BASENAME ++ BASENAME=$(basename "$DEF_PATH" .def) ++ local EVAL_NAME="eval_${BASENAME}" ++ local JSON_OUT="$OUTPUT_DIR/${BASENAME}_grt.json" ++ local RUN_LOG="$OUTPUT_DIR/logs/${BASENAME}.log" ++ local RESULT_PATH="$CHIPBENCH_DIR/results/nangate45/$DESIGN_NICKNAME/$EVAL_NAME" ++ local FLOW_LOG_PATH="$CHIPBENCH_DIR/logs/nangate45/$DESIGN_NICKNAME/$EVAL_NAME" ++ local REPORT_PATH="$CHIPBENCH_DIR/reports/nangate45/$DESIGN_NICKNAME/$EVAL_NAME" ++ local OBJECT_PATH="$CHIPBENCH_DIR/objects/nangate45/$DESIGN_NICKNAME/$EVAL_NAME" ++ local JSON_TEMP="$OUTPUT_DIR/.${BASENAME}_grt.json.tmp" ++ ++ if [ -f "$JSON_OUT" ]; then ++ return 0 ++ fi ++ # Large batches tolerate individual flow failures, but once the requested ++ # number of atomically published labels exists there is no value in ++ # launching the remaining queued candidates. Concurrent workers that were ++ # already in flight may publish a small excess; select_training_data.py ++ # deterministically retains exactly the target and moves those extras. ++ if (( STOP_AFTER_LABELS > 0 )); then ++ local PUBLISHED_LABELS ++ PUBLISHED_LABELS=$(find "$OUTPUT_DIR" -maxdepth 1 -type f \ ++ -name 'cfg_*_final_grt.json' -printf '.' | wc -c) ++ if (( PUBLISHED_LABELS >= STOP_AFTER_LABELS )); then ++ return 0 ++ fi ++ fi ++ ++ # A host reboot cannot run the previous worker's EXIT trap. Start an ++ # unsealed retry from clean flow scratch, and publish its JSON atomically ++ # so a second reboot cannot leave a truncated file that looks complete. ++ rm -rf -- "$RESULT_PATH" "$FLOW_LOG_PATH" "$REPORT_PATH" "$OBJECT_PATH" ++ rm -f -- "$JSON_TEMP" ++ ++ # Preprocess DEF: strip backslash-escaped names if needed ++ local CLEAN_DEF ++ CLEAN_DEF=$(mktemp "${TMPDIR:-/tmp}/ppaplace_${BASENAME}.XXXXXX.def") ++ # Expand and shell-quote paths while the function locals are in scope. ++ # Each xargs invocation is a dedicated bash process. EXIT therefore ++ # cleans failed and successful variants without firing between stages. ++ local cleanup_command ++ if [ "${KEEP_FLOW_ARTIFACTS:-0}" != 1 ]; then ++ printf -v cleanup_command 'rm -f -- %q %q; rm -rf -- %q %q %q %q' \ ++ "$CLEAN_DEF" "$JSON_TEMP" "$RESULT_PATH" "$FLOW_LOG_PATH" \ ++ "$REPORT_PATH" "$OBJECT_PATH" ++ else ++ printf -v cleanup_command 'rm -f -- %q %q' "$CLEAN_DEF" "$JSON_TEMP" ++ fi ++ trap "$cleanup_command" EXIT ++ sed 's/\\//g' "$DEF_PATH" > "$CLEAN_DEF" ++ ++ # Remove BLOCKAGES section if present (causes issues with some circuits) ++ sed -i '/^BLOCKAGES/,/^END BLOCKAGES/d' "$CLEAN_DEF" ++ ++ # Run flow stages: def2db -> place-global -> CTS -> GRT ++ cd "$CHIPBENCH_DIR" ++ ++ mkdir -p "$(dirname "$RUN_LOG")" ++ : > "$RUN_LOG" ++ ++ # Let GNU timeout own a separate process group. In foreground mode it ++ # only signals make, allowing OpenROAD grandchildren to survive a stage ++ # timeout as orphaned CPU consumers. ++ timeout --kill-after=60s "$STAGE_TIMEOUT" make \ ++ NUM_CORES="${NUM_CORES:-8}" DESIGN_CONFIG="$CONFIG" \ ++ FLOW_VARIANT="$EVAL_NAME" \ ++ TARGET_DEF_PATH="$CLEAN_DEF" \ ++ TARGET_DB_PATH=3_3_place_gp.odb \ ++ def2db >>"$RUN_LOG" 2>&1 || return 1 ++ ++ timeout --kill-after=60s "$STAGE_TIMEOUT" make \ ++ NUM_CORES="${NUM_CORES:-8}" DESIGN_CONFIG="$CONFIG" \ ++ FLOW_VARIANT="$EVAL_NAME" \ ++ macro-pre_macro_GPFlow >>"$RUN_LOG" 2>&1 || return 1 ++ ++ timeout --kill-after=60s "$STAGE_TIMEOUT" make \ ++ NUM_CORES="${NUM_CORES:-8}" DESIGN_CONFIG="$CONFIG" \ ++ FLOW_VARIANT="$EVAL_NAME" \ ++ do-place-global >>"$RUN_LOG" 2>&1 || return 1 ++ ++ timeout --kill-after=60s "$STAGE_TIMEOUT" make \ ++ NUM_CORES="${NUM_CORES:-8}" DESIGN_CONFIG="$CONFIG" \ ++ FLOW_VARIANT="$EVAL_NAME" \ ++ do-cts >>"$RUN_LOG" 2>&1 || return 1 ++ ++ timeout --kill-after=60s "$STAGE_TIMEOUT" make \ ++ NUM_CORES="${NUM_CORES:-8}" DESIGN_CONFIG="$CONFIG" \ ++ FLOW_VARIANT="$EVAL_NAME" \ ++ do-grt >>"$RUN_LOG" 2>&1 || return 1 ++ ++ # Extract GRT metrics JSON ++ local GRT_JSON="$CHIPBENCH_DIR/logs/nangate45/$DESIGN_NICKNAME/$EVAL_NAME/5_1_grt.json" ++ if [ -f "$GRT_JSON" ]; then ++ cp "$GRT_JSON" "$JSON_TEMP" ++ test -s "$JSON_TEMP" ++ mv "$JSON_TEMP" "$JSON_OUT" ++ else ++ echo "Missing expected GRT metrics: $GRT_JSON" >>"$RUN_LOG" ++ return 1 ++ fi ++ ++} ++ ++export -f eval_one_def ++export OUTPUT_DIR CHIPBENCH_DIR CONFIG CIRCUIT DESIGN_NICKNAME STAGE_TIMEOUT ++export STOP_AFTER_LABELS ++ ++# Process all DEFs in deterministic configuration order. The stop-after ++# boundary can leave up to MAX_PARALLEL candidates in flight, so filesystem ++# traversal order must not decide which configurations are attempted first. ++set +e ++find "$DEF_DIR" -maxdepth 1 -name "*.def" -type f -print0 | \ ++ sort -z | \ ++ xargs -0 -r -P "$MAX_PARALLEL" -I {} bash -c 'eval_one_def "$@"' _ {} ++STATUS=$? ++set -e ++ ++N_DONE=$(ls "$OUTPUT_DIR"/*.json 2>/dev/null | wc -l) ++echo "Done: $N_DONE GRT JSONs in $OUTPUT_DIR" ++exit "$STATUS" +diff --git a/scripts/train.py b/scripts/train.py +index 1b8a8b8..b34a4e6 100644 +--- a/scripts/train.py ++++ b/scripts/train.py +@@ -1,332 +1,314 @@ +-#!/usr/bin/env python3 +-""" +-Train the PPAPlace dual-stream predictor. +- +-Supports two modes: +- - train_all: train on all circuits, save checkpoint for deployment. +- - loco: leave-one-circuit-out cross-validation. +- +-Usage: +- python scripts/train.py --circuits bp_fe,ethernet,dft68 --epochs 200 +- python scripts/train.py --mode loco --circuits bp_fe,ethernet,dft68 +-""" +- +-import os +-import sys +-import re +-import argparse +-import numpy as np +-import torch +-import torch.nn.functional as F +-import torch.optim as optim +-from scipy import stats +- +-sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) +-from ppaplace.model import PPAPredictor +-from ppaplace.data import load_chipbench_circuit, load_grt_json +-from ppaplace.features import compute_spatial_grid, compute_node_features +- +- +-def parse_macro_positions(def_path, circuit_data): +- """Extract normalized macro positions from a DEF file.""" +- with open(def_path, 'r') as f: +- text = f.read() +- +- macro_names = circuit_data['_macro_names'] +- sizes_def = circuit_data['_sizes_def'] +- norm_bbox = circuit_data['_norm_bbox'] +- V = len(macro_names) +- name_to_idx = {name: i for i, name in enumerate(macro_names)} +- +- comp_match = re.search(r'COMPONENTS\s+\d+\s*;(.*?)END COMPONENTS', text, re.DOTALL) +- if not comp_match: +- return None +- +- pattern = re.compile( +- r'-\s+(\S+)\s+(\S+)\s+\+\s+(PLACED|FIXED)\s+\(\s*(-?\d+)\s+(-?\d+)\s*\)\s+(\S+)\s*;' +- ) +- +- positions_bl = np.zeros((V, 2), dtype=np.float64) +- found = set() +- for match in pattern.finditer(comp_match.group(1)): +- inst_name = match.group(1) +- if inst_name in name_to_idx: +- idx = name_to_idx[inst_name] +- positions_bl[idx] = [int(match.group(4)), int(match.group(5))] +- found.add(idx) +- +- if len(found) < V: +- return None +- +- positions_center = positions_bl + sizes_def / 2 +- x_min, y_min, x_max, y_max = norm_bbox +- positions_norm = np.zeros((V, 2), dtype=np.float32) +- positions_norm[:, 0] = 2.0 * (positions_center[:, 0] - x_min) / (x_max - x_min) - 1.0 +- positions_norm[:, 1] = 2.0 * (positions_center[:, 1] - y_min) / (y_max - y_min) - 1.0 +- return positions_norm +- +- +-def load_circuit_samples(circuit_name, circuit_data, data_dir): +- """Load all (DEF, GRT JSON) pairs for one circuit.""" +- grt_dir = os.path.join(data_dir, 'grt_jsons') +- if not os.path.isdir(grt_dir): +- return [] +- +- sizes = circuit_data['node_features'] +- nets = circuit_data['nets'] +- samples = [] +- +- for fname in sorted(os.listdir(grt_dir)): +- if not fname.endswith('.json'): +- continue +- cfg_name = fname.replace('_dp_grt.json', '').replace('_grt.json', '') +- if cfg_name.startswith('dp_'): +- def_file = f"{cfg_name[3:]}.def" +- else: +- def_file = f"{cfg_name}_final.def" +- def_path = os.path.join(data_dir, def_file) +- if not os.path.exists(def_path): +- continue +- +- try: +- ppa = load_grt_json(os.path.join(grt_dir, fname)) +- positions = parse_macro_positions(def_path, circuit_data) +- if positions is None: +- continue +- samples.append({ +- 'node_features': compute_node_features(positions, sizes, nets), +- 'edge_index': circuit_data['edge_index'], +- 'spatial_grid': compute_spatial_grid(positions, sizes, nets), +- 'ppa_label': np.array([ppa['WNS'], ppa['TNS'], ppa['Power'], ppa['Area']], +- dtype=np.float32), +- 'circuit_id': circuit_name, +- }) +- except Exception: +- continue +- +- print(f" {circuit_name}: {len(samples)} samples loaded") +- return samples +- +- +-def build_circuit_tensors(samples, device): +- """Group samples by circuit_id and stack into tensors.""" +- groups = {} +- for s in samples: +- groups.setdefault(s['circuit_id'], []).append(s) +- +- result = {} +- for cid, group in groups.items(): +- result[cid] = ( +- torch.tensor(np.stack([s['node_features'] for s in group]), +- dtype=torch.float32).to(device), +- torch.tensor(np.stack([s['spatial_grid'] for s in group]), +- dtype=torch.float32).to(device), +- torch.tensor(np.stack([s['ppa_label'] for s in group]), +- dtype=torch.float32).to(device), +- torch.tensor(group[0]['edge_index'], dtype=torch.long).to(device), +- ) +- return result +- +- +-def compute_norm_stats(circuit_tensors): +- """Per-circuit z-score statistics.""" +- return { +- cid: (tg.mean(dim=0), tg.std(dim=0).clamp(min=1e-6)) +- for cid, (_, _, tg, _) in circuit_tensors.items() +- } +- +- +-def train_epoch(model, circuit_tensors, norm_stats, optimizer, +- lambda_rank, device, batch_size=64): +- """One epoch: same-circuit batching with round-robin and ranking loss.""" +- model.train() +- circuit_ids = list(circuit_tensors.keys()) +- +- norm_targets = {} +- for cid in circuit_ids: +- _, _, targets, _ = circuit_tensors[cid] +- mean, std = norm_stats[cid] +- norm_targets[cid] = (targets - mean) / std +- +- # Cache predictions for ranking +- cached_preds = {} +- with torch.no_grad(): +- for cid in circuit_ids: +- nf, sp, _, ei = circuit_tensors[cid] +- chunks = [model(nf[s:s + batch_size], ei, sp[s:s + batch_size]) +- for s in range(0, nf.size(0), batch_size)] +- cached_preds[cid] = torch.cat(chunks, dim=0) +- +- # Round-robin batches +- batch_lists = {} +- for cid in circuit_ids: +- N = circuit_tensors[cid][0].size(0) +- perm = torch.randperm(N, device=device) +- batch_lists[cid] = [perm[s:s + batch_size] +- for s in range(0, N, batch_size)] +- +- all_batches = [] +- max_batches = max(len(bl) for bl in batch_lists.values()) +- for i in range(max_batches): +- for cid in circuit_ids: +- if i < len(batch_lists[cid]): +- all_batches.append((cid, batch_lists[cid][i])) +- +- total_loss, n_batches = 0.0, 0 +- for cid, idx in all_batches: +- nf, sp, _, ei = circuit_tensors[cid] +- tn = norm_targets[cid] +- B = len(idx) +- K = tn.size(1) +- +- optimizer.zero_grad() +- pred = model(nf[idx], ei, sp[idx]) +- +- mse = F.mse_loss(pred, tn[idx]) +- diff_true = tn[idx].unsqueeze(1) - tn.unsqueeze(0) +- diff_pred = pred.unsqueeze(1) - cached_preds[cid].unsqueeze(0) +- rank_loss = F.relu(-diff_true * diff_pred).sum() / (B * tn.size(0) * K) +- +- loss = mse + lambda_rank * rank_loss +- loss.backward() +- torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) +- optimizer.step() +- +- total_loss += loss.item() +- n_batches += 1 +- +- return total_loss / max(n_batches, 1) +- +- +-def evaluate_circuit(model, node_feats, spatials, targets, edge_index, +- device, batch_size=64): +- """Ranking metrics (Kendall tau, Spearman rho) on one circuit.""" +- model.eval() +- preds = [] +- with torch.no_grad(): +- for s in range(0, node_feats.size(0), batch_size): +- preds.append(model(node_feats[s:s + batch_size], edge_index, +- spatials[s:s + batch_size])) +- pred_np = torch.cat(preds).cpu().numpy() +- target_np = targets.cpu().numpy() +- +- metrics = {} +- for k, name in enumerate(['WNS', 'TNS', 'Power']): +- if target_np[:, k].std() < 1e-8: +- continue +- tau, _ = stats.kendalltau(target_np[:, k], pred_np[:, k]) +- rho, _ = stats.spearmanr(target_np[:, k], pred_np[:, k]) +- metrics[name] = {'kendall_tau': tau, 'spearman_rho': rho} +- return metrics +- +- +-def main(): +- parser = argparse.ArgumentParser(description='Train PPAPlace predictor') +- parser.add_argument('--data_root', default='data', +- help='Root directory containing circuit data') +- parser.add_argument('--circuits', required=True, +- help='Comma-separated circuit names') +- parser.add_argument('--epochs', type=int, default=200) +- parser.add_argument('--lr', type=float, default=5e-4) +- parser.add_argument('--lambda_rank', type=float, default=0.1) +- parser.add_argument('--batch_size', type=int, default=64) +- parser.add_argument('--mode', default='train_all', +- choices=['train_all', 'loco']) +- parser.add_argument('--save', default='checkpoints/ppaplace.pt') +- parser.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu') +- parser.add_argument('--eval_every', type=int, default=25) +- args = parser.parse_args() +- +- device = torch.device(args.device) +- circuit_list = [c.strip() for c in args.circuits.split(',')] +- +- # Load all circuit data +- all_samples = [] +- for cname in circuit_list: +- chipbench_dir = os.path.join(args.data_root, 'chipbench', cname) +- data_dir = os.path.join(args.data_root, 'dreamplace', cname) +- cdata = load_chipbench_circuit(chipbench_dir) +- all_samples.extend(load_circuit_samples(cname, cdata, data_dir)) +- +- print(f"Total: {len(all_samples)} samples across {len(circuit_list)} circuits") +- +- if len(all_samples) < 10: +- print("Not enough samples.") +- return +- +- def create_model(): +- return PPAPredictor(node_feat_dim=8, grid_channels=5, hidden_dim=128, +- n_heads=4, n_gat_layers=4, embed_dim=256, +- dropout=0.1).to(device) +- +- if args.mode == 'train_all': +- ct = build_circuit_tensors(all_samples, device) +- ns = compute_norm_stats(ct) +- model = create_model() +- optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=1e-5) +- scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs) +- +- best_loss, best_state = float('inf'), None +- for epoch in range(1, args.epochs + 1): +- loss = train_epoch(model, ct, ns, optimizer, args.lambda_rank, +- device, args.batch_size) +- scheduler.step() +- if loss < best_loss: +- best_loss = loss +- best_state = {k: v.cpu().clone() for k, v in model.state_dict().items()} +- if epoch % args.eval_every == 0: +- print(f"Epoch {epoch:4d} | loss={loss:.4f}") +- +- if best_state: +- model.load_state_dict(best_state) +- +- ns_save = {cid: {'mean': m.cpu().tolist(), 'std': s.cpu().tolist()} +- for cid, (m, s) in ns.items()} +- os.makedirs(os.path.dirname(args.save), exist_ok=True) +- torch.save({ +- 'model_state_dict': model.state_dict(), +- 'norm_stats': ns_save, +- 'circuits': circuit_list, +- }, args.save) +- print(f"Saved to {args.save}") +- +- elif args.mode == 'loco': +- for test_circuit in circuit_list: +- train_samples = [s for s in all_samples if s['circuit_id'] != test_circuit] +- test_samples = [s for s in all_samples if s['circuit_id'] == test_circuit] +- if not test_samples: +- continue +- +- print(f"\n--- LOCO: held-out = {test_circuit} ---") +- ct = build_circuit_tensors(train_samples, device) +- ns = compute_norm_stats(ct) +- model = create_model() +- optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=1e-5) +- scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs) +- +- test_nf = torch.tensor(np.stack([s['node_features'] for s in test_samples]), +- dtype=torch.float32).to(device) +- test_sp = torch.tensor(np.stack([s['spatial_grid'] for s in test_samples]), +- dtype=torch.float32).to(device) +- test_tg = torch.tensor(np.stack([s['ppa_label'] for s in test_samples]), +- dtype=torch.float32).to(device) +- test_ei = torch.tensor(test_samples[0]['edge_index'], +- dtype=torch.long).to(device) +- +- for epoch in range(1, args.epochs + 1): +- train_epoch(model, ct, ns, optimizer, args.lambda_rank, +- device, args.batch_size) +- scheduler.step() +- if epoch % args.eval_every == 0: +- m = evaluate_circuit(model, test_nf, test_sp, test_tg, +- test_ei, device) +- parts = [f"{n}: tau={m[n]['kendall_tau']:+.3f}" +- for n in ['WNS', 'TNS'] if n in m] +- print(f" Epoch {epoch:4d} | {' | '.join(parts)}") +- +- del model, optimizer, ct +- torch.cuda.empty_cache() +- +- +-if __name__ == '__main__': +- main() ++#!/usr/bin/env python3 ++""" ++Train the PPAPlace dual-stream predictor. ++ ++Supports two modes: ++ - train_all: train on all circuits, save checkpoint for deployment. ++ - loco: leave-one-circuit-out cross-validation. ++ ++Usage: ++ python scripts/train.py --circuits bp_fe,ethernet,dft68 --epochs 200 ++ python scripts/train.py --mode loco --circuits bp_fe,ethernet,dft68 ++""" ++ ++import os ++import sys ++import argparse ++import numpy as np ++import torch ++import torch.nn.functional as F ++import torch.optim as optim ++from scipy import stats ++ ++sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) ++from ppaplace.model import PPAPredictor ++from ppaplace.data import ( ++ load_chipbench_circuit, ++ load_grt_json, ++ parse_placement_state, ++) ++from ppaplace.features import ( ++ compute_mixed_size_spatial_grid, ++ compute_node_features, ++) ++ ++ ++def parse_macro_positions(def_path, circuit_data): ++ """Extract normalized macro positions from a DEF file.""" ++ try: ++ return parse_placement_state( ++ def_path, circuit_data)['macro_positions'] ++ except (OSError, ValueError): ++ return None ++ ++ ++def load_circuit_samples(circuit_name, circuit_data, data_dir): ++ """Load all (DEF, GRT JSON) pairs for one circuit.""" ++ grt_dir = os.path.join(data_dir, 'grt_jsons') ++ if not os.path.isdir(grt_dir): ++ return [] ++ ++ samples = [] ++ ++ for fname in sorted(os.listdir(grt_dir)): ++ if not fname.endswith('.json'): ++ continue ++ cfg_name = fname.replace('_dp_grt.json', '').replace('_grt.json', '') ++ if cfg_name.startswith('dp_'): ++ def_file = f"{cfg_name[3:]}.def" ++ elif cfg_name.endswith('_final'): ++ def_file = f"{cfg_name}.def" ++ else: ++ def_file = f"{cfg_name}_final.def" ++ def_path = os.path.join(data_dir, def_file) ++ if not os.path.exists(def_path): ++ continue ++ ++ try: ++ ppa = load_grt_json(os.path.join(grt_dir, fname)) ++ placement = parse_placement_state(def_path, circuit_data) ++ samples.append({ ++ 'node_features': compute_node_features( ++ placement['macro_positions'], ++ placement['macro_sizes'], ++ placement['macro_nets']), ++ 'edge_index': circuit_data['edge_index'], ++ 'edge_weights': circuit_data['edge_weights'], ++ 'spatial_grid': compute_mixed_size_spatial_grid(placement), ++ 'ppa_label': np.array([ppa['WNS'], ppa['TNS'], ppa['Power'], ppa['Area']], ++ dtype=np.float32), ++ 'circuit_id': circuit_name, ++ }) ++ except Exception: ++ continue ++ ++ print(f" {circuit_name}: {len(samples)} samples loaded") ++ return samples ++ ++ ++def build_circuit_tensors(samples, device): ++ """Group samples by circuit_id and stack into tensors.""" ++ groups = {} ++ for s in samples: ++ groups.setdefault(s['circuit_id'], []).append(s) ++ ++ result = {} ++ for cid, group in groups.items(): ++ result[cid] = ( ++ torch.tensor(np.stack([s['node_features'] for s in group]), ++ dtype=torch.float32).to(device), ++ torch.tensor(np.stack([s['spatial_grid'] for s in group]), ++ dtype=torch.float32).to(device), ++ torch.tensor(np.stack([s['ppa_label'] for s in group]), ++ dtype=torch.float32).to(device), ++ torch.tensor(group[0]['edge_index'], dtype=torch.long).to(device), ++ torch.tensor(group[0]['edge_weights'], dtype=torch.float32).to(device), ++ ) ++ return result ++ ++ ++def compute_norm_stats(circuit_tensors): ++ """Per-circuit z-score statistics.""" ++ return { ++ cid: (tg.mean(dim=0), tg.std(dim=0).clamp(min=1e-6)) ++ for cid, (_, _, tg, _, _) in circuit_tensors.items() ++ } ++ ++ ++def train_epoch(model, circuit_tensors, norm_stats, optimizer, ++ lambda_rank, device, batch_size=32): ++ """One epoch: same-circuit batching with round-robin and ranking loss.""" ++ model.train() ++ circuit_ids = list(circuit_tensors.keys()) ++ ++ norm_targets = {} ++ for cid in circuit_ids: ++ _, _, targets, _, _ = circuit_tensors[cid] ++ mean, std = norm_stats[cid] ++ norm_targets[cid] = (targets - mean) / std ++ ++ # Cache predictions for ranking ++ cached_preds = {} ++ with torch.no_grad(): ++ for cid in circuit_ids: ++ nf, sp, _, ei, ew = circuit_tensors[cid] ++ chunks = [model(nf[s:s + batch_size], ei, sp[s:s + batch_size], ew) ++ for s in range(0, nf.size(0), batch_size)] ++ cached_preds[cid] = torch.cat(chunks, dim=0) ++ ++ # Round-robin batches ++ batch_lists = {} ++ for cid in circuit_ids: ++ N = circuit_tensors[cid][0].size(0) ++ perm = torch.randperm(N, device=device) ++ batch_lists[cid] = [perm[s:s + batch_size] ++ for s in range(0, N, batch_size)] ++ ++ all_batches = [] ++ max_batches = max(len(bl) for bl in batch_lists.values()) ++ for i in range(max_batches): ++ for cid in circuit_ids: ++ if i < len(batch_lists[cid]): ++ all_batches.append((cid, batch_lists[cid][i])) ++ ++ total_loss, n_batches = 0.0, 0 ++ for cid, idx in all_batches: ++ nf, sp, _, ei, ew = circuit_tensors[cid] ++ tn = norm_targets[cid] ++ B = len(idx) ++ K = tn.size(1) ++ ++ optimizer.zero_grad() ++ pred = model(nf[idx], ei, sp[idx], ew) ++ ++ mse = F.mse_loss(pred, tn[idx]) ++ diff_true = tn[idx].unsqueeze(1) - tn.unsqueeze(0) ++ diff_pred = pred.unsqueeze(1) - cached_preds[cid].unsqueeze(0) ++ rank_loss = F.relu(-diff_true * diff_pred).sum() / (B * tn.size(0) * K) ++ ++ loss = mse + lambda_rank * rank_loss ++ loss.backward() ++ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) ++ optimizer.step() ++ ++ total_loss += loss.item() ++ n_batches += 1 ++ ++ return total_loss / max(n_batches, 1) ++ ++ ++def evaluate_circuit(model, node_feats, spatials, targets, edge_index, ++ device, batch_size=32, edge_weight=None): ++ """Ranking metrics (Kendall tau, Spearman rho) on one circuit.""" ++ model.eval() ++ preds = [] ++ with torch.no_grad(): ++ for s in range(0, node_feats.size(0), batch_size): ++ preds.append(model(node_feats[s:s + batch_size], edge_index, ++ spatials[s:s + batch_size], edge_weight)) ++ pred_np = torch.cat(preds).cpu().numpy() ++ target_np = targets.cpu().numpy() ++ ++ metrics = {} ++ for k, name in enumerate(['WNS', 'TNS', 'Power']): ++ if target_np[:, k].std() < 1e-8: ++ continue ++ tau, _ = stats.kendalltau(target_np[:, k], pred_np[:, k]) ++ rho, _ = stats.spearmanr(target_np[:, k], pred_np[:, k]) ++ metrics[name] = {'kendall_tau': tau, 'spearman_rho': rho} ++ return metrics ++ ++ ++def main(): ++ parser = argparse.ArgumentParser(description='Train PPAPlace predictor') ++ parser.add_argument('--data_root', default='data', ++ help='Root directory containing circuit data') ++ parser.add_argument('--circuits', required=True, ++ help='Comma-separated circuit names') ++ parser.add_argument('--epochs', type=int, default=200) ++ parser.add_argument('--lr', type=float, default=5e-4) ++ parser.add_argument('--lambda_rank', type=float, default=0.5) ++ parser.add_argument('--batch_size', type=int, default=32) ++ parser.add_argument('--mode', default='train_all', ++ choices=['train_all', 'loco']) ++ parser.add_argument('--save', default='checkpoints/ppaplace.pt') ++ parser.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu') ++ parser.add_argument('--eval_every', type=int, default=25) ++ args = parser.parse_args() ++ ++ device = torch.device(args.device) ++ circuit_list = [c.strip() for c in args.circuits.split(',')] ++ ++ # Load all circuit data ++ all_samples = [] ++ for cname in circuit_list: ++ chipbench_dir = os.path.join(args.data_root, 'chipbench', cname) ++ data_dir = os.path.join(args.data_root, 'dreamplace', cname) ++ cdata = load_chipbench_circuit(chipbench_dir) ++ all_samples.extend(load_circuit_samples(cname, cdata, data_dir)) ++ ++ print(f"Total: {len(all_samples)} samples across {len(circuit_list)} circuits") ++ ++ if len(all_samples) < 10: ++ print("Not enough samples.") ++ return ++ ++ def create_model(): ++ return PPAPredictor(node_feat_dim=8, grid_channels=5, hidden_dim=128, ++ n_heads=4, n_gat_layers=4, embed_dim=256, ++ dropout=0.1).to(device) ++ ++ if args.mode == 'train_all': ++ ct = build_circuit_tensors(all_samples, device) ++ ns = compute_norm_stats(ct) ++ model = create_model() ++ optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=1e-5) ++ scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs) ++ ++ best_loss, best_state = float('inf'), None ++ for epoch in range(1, args.epochs + 1): ++ loss = train_epoch(model, ct, ns, optimizer, args.lambda_rank, ++ device, args.batch_size) ++ scheduler.step() ++ if loss < best_loss: ++ best_loss = loss ++ best_state = {k: v.cpu().clone() for k, v in model.state_dict().items()} ++ if epoch % args.eval_every == 0: ++ print(f"Epoch {epoch:4d} | loss={loss:.4f}") ++ ++ if best_state: ++ model.load_state_dict(best_state) ++ ++ ns_save = {cid: {'mean': m.cpu().tolist(), 'std': s.cpu().tolist()} ++ for cid, (m, s) in ns.items()} ++ os.makedirs(os.path.dirname(args.save), exist_ok=True) ++ torch.save({ ++ 'model_state_dict': model.state_dict(), ++ 'norm_stats': ns_save, ++ 'circuits': circuit_list, ++ }, args.save) ++ print(f"Saved to {args.save}") ++ ++ elif args.mode == 'loco': ++ for test_circuit in circuit_list: ++ train_samples = [s for s in all_samples if s['circuit_id'] != test_circuit] ++ test_samples = [s for s in all_samples if s['circuit_id'] == test_circuit] ++ if not test_samples: ++ continue ++ ++ print(f"\n--- LOCO: held-out = {test_circuit} ---") ++ ct = build_circuit_tensors(train_samples, device) ++ ns = compute_norm_stats(ct) ++ model = create_model() ++ optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=1e-5) ++ scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs) ++ ++ test_nf = torch.tensor(np.stack([s['node_features'] for s in test_samples]), ++ dtype=torch.float32).to(device) ++ test_sp = torch.tensor(np.stack([s['spatial_grid'] for s in test_samples]), ++ dtype=torch.float32).to(device) ++ test_tg = torch.tensor(np.stack([s['ppa_label'] for s in test_samples]), ++ dtype=torch.float32).to(device) ++ test_ei = torch.tensor(test_samples[0]['edge_index'], ++ dtype=torch.long).to(device) ++ test_ew = torch.tensor(test_samples[0]['edge_weights'], ++ dtype=torch.float32).to(device) ++ ++ for epoch in range(1, args.epochs + 1): ++ train_epoch(model, ct, ns, optimizer, args.lambda_rank, ++ device, args.batch_size) ++ scheduler.step() ++ if epoch % args.eval_every == 0: ++ m = evaluate_circuit(model, test_nf, test_sp, test_tg, ++ test_ei, device, ++ edge_weight=test_ew) ++ parts = [f"{n}: tau={m[n]['kendall_tau']:+.3f}" ++ for n in ['WNS', 'TNS'] if n in m] ++ print(f" Epoch {epoch:4d} | {' | '.join(parts)}") ++ ++ del model, optimizer, ct ++ torch.cuda.empty_cache() ++ ++ ++if __name__ == '__main__': ++ main() +diff --git a/setup.py b/setup.py +index 5b97a23..d493658 100644 +--- a/setup.py ++++ b/setup.py +@@ -7,7 +7,11 @@ setup( + python_requires='>=3.8', + install_requires=[ + 'torch>=2.0', +- 'numpy>=1.24', +- 'scipy>=1.10', ++ 'numpy>=1.23,<1.24', ++ 'scipy>=1.10', ++ 'matplotlib>=3.7', ++ 'pyyaml>=6.0', ++ 'ortools==9.10.4067', ++ 'pandas==2.0.3', + ], + )