inire/scripts/benchmark_catalog_routing.py

465 lines
23 KiB
Python
Raw Permalink Normal View History

"""Compare catalog and native routing on 5 mm layouts at 100 nm pitch."""
from __future__ import annotations
import argparse
import json
import platform
import resource
from dataclasses import asdict, dataclass, field, replace
from itertools import pairwise
from math import fsum, pi, sqrt
from statistics import median
from time import perf_counter
from shapely.affinity import scale
from shapely.geometry import Polygon, box
from inire import NetSpec, ObjectiveWeights, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route
from inire._catalog import (
HEADING_STEPS, BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant,
)
from inire._catalog_timing import DelayModel, evaluate_delay
from inire.router._catalog_guidance import AutomaticGrid, CoarseGuidance
from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout
from inire.router._catalog_matching import DelayChoice, MatchGroup, choose_match
from inire.router._catalog_verify import replay_moves, verify_path
from scripts.catalog_floorplan import BLOCKS, COMPONENTS, NET_BANKS, STEPPED_BLOCKS
PROFILE_HOLDOUTS = ("peer-cost-holdout", "matched-cost-holdout")
@dataclass(frozen=True, slots=True)
class ScaleCase:
grid: Grid
board: Polygon
nets: dict[str, CatalogNet]
obstacles: tuple[Polygon, ...]
references: dict[str, tuple[Move, ...]]
timing: DelayModel | None = None
groups: tuple[MatchGroup, ...] = ()
windows: dict[str, Polygon] = field(default_factory=dict)
clearance: float = 1000.0
cheaper_references: dict[str, tuple[Move, ...]] | None = None
def profile_holdout(matched: bool) -> ScaleCase:
"""Two nearby lanes compete for a cheaper profile beside a long keepout."""
grid = Grid((0, 0), 100, 1e-9)
lanes = {"bypass": 975_000, "through": 1_000_000}
if matched:
lanes["reference"] = 1_150_000
nets = {name: CatalogNet(Pose(200_000, y, 0, "4"), Pose(4_800_000, y, 0, "4")) for name, y in lanes.items()}
enter_wide = Move("centered", traversal=("a", "b"))
exit_wide = Move("centered", traversal=("b", "a"), orientation=Orientation(180))
widen = (enter_wide, Move("5-straight", steps=45_800), exit_wide)
left_up = Move("left-90", displacement=(10_000, 10_000))
left_down = Move("left-90", displacement=(10_000, -10_000))
right_up = Move("right-90", displacement=(10_000, 10_000))
right_down = Move("right-90", displacement=(10_000, -10_000))
references = {
"bypass": (left_up, right_up, Move("4-straight", steps=45_600), right_down, left_down),
"through": (Move("4-straight", steps=46_000),),
}
cheaper = {
"bypass": (
right_down, Move("4-straight", steps=600), left_down,
enter_wide, Move("5-straight", steps=45_400), exit_wide,
left_up, Move("4-straight", steps=600), right_up,
),
"through": widen,
}
timing = None
groups = ()
if matched:
references["reference"] = cheaper["reference"] = widen
timing = DelayModel(1.55e-6, group_indices={"4": 4, "5": 4}, variant_delays={"centered": 40_000})
groups = (MatchGroup("delay", {"through": 0, "reference": 0}, timing.wavelength, 0),)
return ScaleCase(
grid, box(0, 0, 5_000_000, 1_200_000), nets, (box(400_000, 900_000, 4_600_000, 990_000),),
references, timing, groups, cheaper_references=cheaper,
)
def timing_case(name: str) -> ScaleCase:
grid = Grid((0, 0), 100, 1e-9)
if name == "tuning":
nets = {
net: CatalogNet(Pose(20_000, y, 0, "4"), Pose(140_000, y, 0, "4"))
for net, y in (("reference", 40_000), ("adjust", 120_000))
}
timing = DelayModel(1.55e-6, group_indices={"4": 4}, fixed_contributions={"adjust": (20_000,)})
group = MatchGroup("delay", {"reference": 0, "adjust": (80 * pi - 60) * 1000}, 1.55e-6, 50)
windows = {"adjust": box(40_000, 115_000, 100_000, 155_000)}
else:
nets = {
net: CatalogNet(Pose(20_000, y, 0, "4"), Pose(140_000, y, 0, "4"))
for net, y in (("reference", 40_000), ("adjust", 120_000), ("independent", 140_000))
}
timing = DelayModel(1.55e-6, group_indices={"4": 4})
group = MatchGroup("delay", {"reference": 0, "adjust": -1000}, 1.55e-6, 50)
windows = {"adjust": box(40_000, 115_000, 100_000, 155_000)}
return ScaleCase(
grid, box(0, 0, 400_000, 300_000), nets, (), {net: (Move("4-straight", steps=1200),) for net in nets},
timing, (group,), windows,
)
def corpus_lanes(name: str) -> ScaleCase:
from inire.tests.routing_corpus import CASE_GROUPS # noqa: PLC0415
case = "scale-bank-216-with-keepouts" if name == "corpus-lanes" else "scale-bank-224"
problem = CASE_GROUPS[case][0].problem
grid = Grid((0, 0), 100, 1e-9)
nets = {
net.net_id: CatalogNet(
Pose(1000 * net.start.x, 1000 * net.start.y, net.start.r, "4"),
Pose(1000 * net.target.x, 1000 * net.target.y, net.target.r, "4"),
)
for net in problem.nets[:12]
}
references = {name: (Move("4-straight", steps=abs(net.target.x - net.start.x) // grid.pitch),) for name, net in nets.items()}
obstacles = tuple(scale(shape, xfact=1000, yfact=1000, origin=(0, 0)) for shape in problem.static_obstacles)
return ScaleCase(
grid, box(*(1000 * coord for coord in problem.bounds)), nets, obstacles, references, clearance=1000 * problem.clearance,
)
def floorplan_case() -> ScaleCase:
"""Build unseeded port pairs and rounded Manhattan references from authored waypoints."""
grid = Grid((0, 0), 100, 1e-9)
radius_um = 10
cardinal_headings = {step: heading for heading, step in HEADING_STEPS.items() if heading % 90 == 0}
nets: dict[str, CatalogNet] = {}
references: dict[str, tuple[Move, ...]] = {}
for bank, paths in NET_BANKS.items():
for index, points in enumerate(paths, 1):
name = f"{bank}-{index}"
deltas = [(x1 - x0, y1 - y0) for (x0, y0), (x1, y1) in pairwise(points)]
directions = [((dx > 0) - (dx < 0), (dy > 0) - (dy < 0)) for dx, dy in deltas]
headings = [cardinal_headings[direction] for direction in directions]
source, destination = points[0], points[-1]
nets[name] = CatalogNet(
Pose(1000 * source[0], 1000 * source[1], headings[0], "4"),
Pose(1000 * destination[0], 1000 * destination[1], headings[-1], "4"),
)
recipe: list[Move] = []
for segment, (dx, dy) in enumerate(deltas):
has_corner = segment < len(deltas) - 1
# Each rounded corner uses one radius of the incoming and outgoing straights.
length = abs(dx) + abs(dy) - radius_um * (int(segment > 0) + int(has_corner))
if length < 0:
raise ValueError(f"Reference bend exceeds its setback on {name}")
if length:
recipe.append(Move("4-straight", steps=1000 * length // grid.pitch))
if has_corner:
travel, onward = directions[segment:segment + 2]
turn = travel[0] * onward[1] - travel[1] * onward[0]
if not turn:
raise ValueError(f"Reference corner must be a quarter turn on {name}")
radius = 1000 * radius_um
offset = (radius * (travel[0] + onward[0]), radius * (travel[1] + onward[1]))
recipe.append(Move("left-90" if turn > 0 else "right-90", displacement=offset))
references[name] = tuple(recipe)
obstacles = (
*(box(*(1000 * coordinate for coordinate in block)) for block in (*BLOCKS, *COMPONENTS)),
*(Polygon([(1000 * x, 1000 * y) for x, y in block]) for block in STEPPED_BLOCKS),
)
return ScaleCase(grid, box(0, 0, 5_000_000, 5_000_000), nets, obstacles, references)
def scale_case(name: str) -> ScaleCase:
if name == "floorplan":
return floorplan_case()
if name in ("tuning", "retry"):
return timing_case(name)
if name in PROFILE_HOLDOUTS:
return profile_holdout(matched=name == "matched-cost-holdout")
if name in ("corpus-lanes", "corpus-open-lanes"):
return corpus_lanes(name)
grid = Grid((0, 0), 100, 1e-9)
obstacles = [
box(x, y, x + 250_000, y + 140_000)
for j in range(8) for i in range(9)
for x, y in ((400_000 + 500_000 * i, 400_000 + 550_000 * j),)
]
nets = {
f"lane-{row}-{lane}": CatalogNet(Pose(200_000, y, 0, "4"), Pose(4_800_000, y, 0, "4"))
for row in range(8) for lane in range(5)
for y in (170_000 + 550_000 * row + 20_000 * lane,)
}
references = {net: (Move("4-straight", steps=46_000),) for net in nets}
if name == "constrained":
obstacles[0] = box(400_000, 20_000, 650_000, 160_000)
special = "lane-0-0"
nets[special] = CatalogNet(Pose(200_000, 60_000, 0, "4"), Pose(4_800_000, 60_000, 0, "4"))
references[special] = (
Move("4-straight", steps=1700), Move("right-90", displacement=(10_000, -10_000)),
Move("4-straight", steps=300), Move("left-90", displacement=(10_000, -10_000)),
Move("4-straight", steps=2800), Move("left-90", displacement=(10_000, 10_000)),
Move("4-straight", steps=300), Move("right-90", displacement=(10_000, 10_000)),
Move("4-straight", steps=41_100),
)
if name == "diagonal-savings":
special = "lane-7-4"
nets[special] = CatalogNet(Pose(300_000, 4_500_000, 0, "4"), Pose(700_000, 4_700_000, 0, "4"))
references[special] = (
Move("4-straight", steps=200), Move("left-90", displacement=(10_000, 10_000)),
Move("4-straight", steps=1800), Move("right-90", displacement=(10_000, 10_000)), Move("4-straight", steps=3600),
)
if name == "diagonal":
special = "lane-7-4"
nets[special] = CatalogNet(Pose(300_000, 4_600_000, 45, "4"), Pose(500_000, 4_800_000, 45, "4"))
references[special] = (Move("4-straight", steps=2000),)
if name == "off-coarse":
grid = Grid((0, 0), 1, 1e-9)
nets = {"displaced": CatalogNet(Pose(20_001, 30_001, 0, "4"), Pose(170_001, 30_201, 0, "8"))}
references = {"displaced": (Move("displaced", traversal=("a", "b")), Move("8-straight", steps=50_000))}
return ScaleCase(grid, box(0, 0, 5_000_000, 5_000_000), nets, tuple(obstacles), references)
def catalog(mode: str, case: str) -> Catalog:
profiles = {"4": Profile("4 µm", 4000), "5": Profile("5 µm", 5000), "8": Profile("8 µm", 8000)}
variants: dict[str, StraightVariant | FixedVariant | BendVariant] = {"4-straight": StraightVariant("4", 1)}
if mode in ("typed", "octagonal"):
variants["5-straight"] = StraightVariant("5", 0.5)
variants["centered"] = FixedVariant(
"centered",
{"a": Pose(0, 0, 0, "4"), "b": Pose(10_000, 0, 180, "5")},
(Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),),
(("a", "b"), ("b", "a")), (Orientation(), Orientation(180)), 0.01, 10_000,
)
if case in ("floorplan", "constrained", "diagonal-savings", "tuning", *PROFILE_HOLDOUTS):
variants["left-90"] = BendVariant("4", 90, 10_000, 0.01, sagitta=30)
variants["right-90"] = BendVariant("4", -90, 10_000, 0.01, sagitta=30)
if mode == "octagonal":
variants["left-45"] = BendVariant("4", 45, 10_000, 0.01, max_lead=200, lead_cost_per_cm=1, sagitta=30)
variants["right-45"] = BendVariant("4", -45, 10_000, 0.01, max_lead=200, lead_cost_per_cm=1, sagitta=30)
if case == "off-coarse":
variants["8-straight"] = StraightVariant("8", 0.2)
variants["displaced"] = FixedVariant(
"displaced", {"a": Pose(0, 0, 0, "4"), "b": Pose(100_000, 200, 180, "8")},
(Polygon(((0, -2000), (100_000, -3800), (100_000, 4200), (0, 2000))),),
(("a", "b"),), (Orientation(),), 0.2, 100_010,
)
return Catalog("scale", profiles, variants)
def _reference_cost(case: ScaleCase, technology: Catalog, recipes: dict[str, tuple[Move, ...]]) -> float:
if recipes.keys() != case.nets.keys():
raise AssertionError("Reference layout must route every net")
evaluator = MoveEvaluator(case.grid, technology)
placed = {}
for name, recipe in recipes.items():
net = case.nets[name]
path = replay_moves(evaluator, net.start, recipe)
if path is None:
raise AssertionError(f"Reference recipe did not evaluate for {name}")
placed[name] = path
for name, path in placed.items():
net = case.nets[name]
occupied = tuple(shape for owner, other in placed.items() if owner != name for piece in other for shape in piece.footprints)
error = verify_path(
evaluator, path, net.start, net.target, board=case.board, keepouts=case.obstacles, occupied=occupied, clearance=case.clearance,
)
if error is not None:
raise AssertionError(f"Invalid reference for {name}: {error}")
if case.cheaper_references is not None and case.timing is not None:
for group in case.groups:
timing = replace(case.timing, wavelength=group.wavelength)
choices = {}
for name in group.offsets:
delay = evaluate_delay(evaluator, placed[name], timing, net_id=name)
if delay is None:
raise AssertionError(f"Missing reference delay for {name}")
choices[name] = (DelayChoice(placed[name], delay),)
if not choose_match(group, choices)[2]:
raise AssertionError(f"Unmatched reference group {group.group_id}")
return fsum(piece.cost for path in placed.values() for piece in path)
def verify_references(case: ScaleCase, technology: Catalog) -> dict[str, float]:
cost = _reference_cost(case, technology, case.references)
if case.cheaper_references is None:
return {}
cheaper = _reference_cost(case, technology, case.cheaper_references)
if cheaper >= cost:
raise AssertionError("Cheaper reference must lower the total cost")
return {"original": cost, "cheaper": cheaper}
def bank_order_key(net: CatalogNet) -> tuple[int, int, bool, int, int]:
"""Group by heading and put the outside of each lateral fan-out first."""
start, target = net.start, net.target
dx, dy = HEADING_STEPS[start.heading]
start_side = dx * start.y - dy * start.x
shift = dx * target.y - dy * target.x - start_side
side = (shift > 0) - (shift < 0)
return start.heading, target.heading, shift != 0, side, -side * start_side
def run_catalog(case: ScaleCase, technology: Catalog, args: argparse.Namespace) -> tuple[dict, float]:
settings = LayoutSettings(
case.board, case.obstacles, clearance=case.clearance, node_limit=args.node_limit, refinement=not args.no_refinement,
guidance=None if args.guide_pitch is None else CoarseGuidance(args.guide_pitch),
retry_independent=not args.no_independent_retry,
constructive=args.constructive,
)
start = perf_counter()
grid = case.grid
if args.auto_pitch is not None:
terminals = tuple(pose for net in case.nets.values() for pose in (net.start, net.target))
grid = AutomaticGrid(args.auto_pitch, grid.meters_per_unit).select(terminals, technology)
result = route_layout(
MoveEvaluator(grid, technology), case.nets, settings,
timing=case.timing, groups=case.groups, windows=case.windows,
)
elapsed = perf_counter() - start
paths = {name: result.routes[name].path or () for name in result.completed}
expanded = sum(attempt.expanded for attempt in result.attempts)
proposed = sum(attempt.proposed for attempt in result.attempts)
measurements = {
"proposals_per_expansion": proposed / expanded if expanded else None,
"completed": result.completed,
"verified": tuple(name for name, report in result.routes.items() if report.path is not None),
"matching": {name: asdict(report) for name, report in result.matching.items()},
"outcomes": {name: report.outcome for name, report in result.routes.items()},
"per_net": {
name: {"cost": result.routes[name].cost, "length_nm": result.routes[name].length}
for name in paths
},
"routing_pitch_nm": grid.pitch,
"typed_improvements": sum(any(move.move.variant == "centered" for move in path) for path in paths.values()),
"used_guidance": sum(report.used_guidance for report in result.routes.values()),
"guide_fallbacks": sum(report.guide_fallback for report in result.routes.values()),
"profile_fallbacks": sum(report.profile_fallback for report in result.routes.values()),
"attempts": [asdict(attempt) for attempt in result.attempts],
}
if args.geometry:
measurements["polygons"] = {
name: [shape.wkb_hex for move in path for shape in move.footprints] for name, path in paths.items()
}
measurements["moves"] = {name: [asdict(piece.move) for piece in path] for name, path in paths.items()}
return measurements, elapsed
def run_native(case: ScaleCase, args: argparse.Namespace) -> tuple[dict, float]:
pitch = case.grid.pitch
specs = tuple(
NetSpec(name, Port(net.start.x // pitch, net.start.y // pitch, net.start.heading),
Port(net.target.x // pitch, net.target.y // pitch, net.target.heading), width=4000 / pitch)
for name, net in case.nets.items()
)
problem = RoutingProblem(
tuple(value / pitch for value in case.board.bounds), specs,
tuple(scale(shape, xfact=1 / pitch, yfact=1 / pitch, origin=(0, 0)) for shape in case.obstacles),
clearance=case.clearance / pitch,
)
rate = pitch * case.grid.meters_per_unit * 100
radius = 10_000 / pitch
options = RoutingOptions(
search=SearchOptions(
node_limit=args.node_limit, max_straight_length=50_000, bend_radii=(radius,), sbend_radii=(),
terminal_jog_limit=args.native_jog_limit,
),
objective=ObjectiveWeights(unit_length_cost=rate, bend_penalty=(0.01 - radius * pi / 2 * rate) * sqrt(radius / 10), danger_weight=0),
topology=TopologyOptions(mode="off"),
refinement=RefinementOptions(enabled=not args.no_refinement),
)
start = perf_counter()
result = route(problem, options=options)
elapsed = perf_counter() - start
paths = {name: outcome.path for name, outcome in result.results_by_net.items() if outcome.is_valid}
metrics = result.metrics
measurements = {
"completed": tuple(paths),
"outcomes": {name: outcome.outcome for name, outcome in result.results_by_net.items()},
"per_net": {
name: {
"cost": fsum(move.length * rate if move.move_type == "straight" else 0.01 for move in path),
"length_nm": fsum(move.length * pitch for move in path),
}
for name, path in paths.items()
},
"expanded": metrics.nodes_expanded,
"proposed": metrics.moves_generated,
"proposals_per_expansion": metrics.moves_generated / metrics.nodes_expanded if metrics.nodes_expanded else None,
"geometry_cache_hits": metrics.move_cache_abs_hits + metrics.move_cache_rel_hits,
"geometry_cache_misses": metrics.move_cache_abs_misses + metrics.move_cache_rel_misses,
"exact_ray_checks": metrics.ray_cast_exact_geometry_checks,
}
if args.geometry:
measurements["polygons"] = {
name: [
scale(shape, xfact=pitch, yfact=pitch, origin=(0, 0)).wkb_hex for move in path for shape in move.physical_geometry
] for name, path in paths.items()
}
return measurements, elapsed
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--mode", choices=("native", "manhattan", "typed", "octagonal"), default="typed")
parser.add_argument(
"--case", default="floorplan", help="routing fixture (default: floorplan)",
choices=(
"floorplan", "aligned", "constrained", "diagonal-savings", "diagonal", "off-coarse", "tuning", "retry",
"corpus-lanes", "corpus-open-lanes", *PROFILE_HOLDOUTS,
),
)
parser.add_argument("--guide-pitch", type=int, help="coarse pitch in nanometers")
parser.add_argument("--auto-pitch", type=int, help="preferred pitch for automatic grid selection in nanometers")
parser.add_argument("--repeat", type=int, default=3)
parser.add_argument("--node-limit", type=int, default=1000)
parser.add_argument("--net-order", choices=("input", "bank"), help="order for routing nets (floorplan defaults to bank order)")
parser.add_argument("--native-jog-limit", type=int, help="jog or detour attempts per net during native warm start")
parser.add_argument("--constructive", action=argparse.BooleanOptionalAction, help="try constructive catalog routes first")
parser.add_argument("--no-refinement", action="store_true")
parser.add_argument("--no-independent-retry", action="store_true")
parser.add_argument("--geometry", action="store_true")
args = parser.parse_args()
if args.repeat < 1:
parser.error("--repeat must be positive")
if args.native_jog_limit is not None and (args.mode != "native" or args.native_jog_limit < 0):
parser.error("--native-jog-limit requires native mode and a nonnegative limit")
if args.case == "diagonal" and args.mode != "octagonal":
parser.error("The native-diagonal terminal case requires octagonal mode")
if args.case in PROFILE_HOLDOUTS and args.mode not in ("typed", "octagonal"):
parser.error("The profile holdouts require typed or octagonal mode")
if args.mode == "native" and (
args.guide_pitch is not None or args.auto_pitch is not None
or args.case not in ("floorplan", "constrained", "aligned", "diagonal-savings", "corpus-lanes", "corpus-open-lanes")
):
parser.error("Native mode needs a case with cardinal terminals on the explicit grid")
case = scale_case(args.case)
technology = catalog(args.mode, args.case)
reference_costs = verify_references(case, technology)
if args.net_order is None:
args.net_order = "bank" if args.case == "floorplan" else "input"
if args.net_order == "bank":
names = sorted(case.nets, key=lambda name: bank_order_key(case.nets[name]))
case = replace(case, nets={name: case.nets[name] for name in names})
if args.mode == "native" and args.native_jog_limit is None:
args.native_jog_limit = 48 if args.case == "floorplan" else 0
if args.constructive is None:
args.constructive = args.case in ("floorplan", *PROFILE_HOLDOUTS) and args.mode != "native"
samples = []
measurements = {}
for _ in range(args.repeat):
measurements, elapsed = run_native(case, args) if args.mode == "native" else run_catalog(case, technology, args)
samples.append(elapsed)
elapsed = median(samples)
total_cost = fsum(entry["cost"] for entry in measurements["per_net"].values())
print(json.dumps({
"options": vars(args), "machine": platform.machine(), "python": platform.python_version(), "requested": len(case.nets),
"wall_seconds": samples, "median_seconds": elapsed, "peak_rss": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
"catalog_cost": total_cost, "time_cost_squared": elapsed * total_cost**2 if measurements["completed"] else None,
**({"reference_costs": reference_costs} if reference_costs else {}),
**measurements,
}, indent=2))
if __name__ == "__main__":
main()