Try verified perimeter construction early and reuse probe routes as movable hints during lookahead. Batch collision checks and cache component generation for repeated placement and refinement candidates.
245 lines
11 KiB
Python
245 lines
11 KiB
Python
"""Compare opt-in automatic retry orders on the routing corpus."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from argparse import ArgumentParser
|
|
from concurrent.futures import ProcessPoolExecutor
|
|
from dataclasses import asdict, dataclass, replace
|
|
from functools import partial
|
|
from json import dumps
|
|
from pathlib import Path
|
|
from statistics import median
|
|
from time import perf_counter
|
|
from typing import TYPE_CHECKING
|
|
|
|
from inire import route
|
|
from inire.router._automatic import _AutomaticRun
|
|
from inire.router._routing_policy import LockPlan, _best_trial, _disconnected_nets, _route_residual
|
|
from inire.tests.routing_corpus import (
|
|
CASE_GROUPS,
|
|
PROFILES,
|
|
automatic_options,
|
|
benchmark_weighted_length,
|
|
native_verified_costs,
|
|
profile_options,
|
|
select_cases,
|
|
)
|
|
|
|
if TYPE_CHECKING:
|
|
from typing import Literal
|
|
|
|
from inire.model import RoutingOptions, RoutingProblem
|
|
from inire.results import RoutingResult
|
|
from inire.router._routing_policy import Trial
|
|
from inire.seeds import PathSeed
|
|
from inire.tests.routing_benchmark_case import BenchmarkCase
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class _RetryPolicy:
|
|
lattice_limit: int | None = None
|
|
probe_iterations: int | Literal["configured"] | None = None
|
|
residual_limit: int | None = None
|
|
residual_after_fallback: bool = False
|
|
|
|
|
|
_POLICIES = {
|
|
"baseline": _RetryPolicy(),
|
|
**{f"lattice-{limit}": _RetryPolicy(lattice_limit=limit) for limit in (500, 750, 1000, 1500, 2000)},
|
|
**{f"probe-iterations-{count}": _RetryPolicy(probe_iterations=count) for count in (1, 2, 3)},
|
|
"probe-full-budget": _RetryPolicy(probe_iterations="configured"),
|
|
**{f"residual-{limit}": _RetryPolicy(residual_limit=limit) for limit in (1500, 3000)},
|
|
"late-residual-3000": _RetryPolicy(residual_limit=3000, residual_after_fallback=True),
|
|
}
|
|
|
|
|
|
class _RetryExperiment(_AutomaticRun):
|
|
def __init__(self, problem: RoutingProblem, options: RoutingOptions, policy: _RetryPolicy) -> None:
|
|
super().__init__(problem, options, None)
|
|
self.retry_policy = policy
|
|
self.retry_attempts: list[dict] = []
|
|
|
|
def _record_retry(self, policy: str, outcome: str, started: float, first_run: int) -> None:
|
|
self.retry_attempts.append({
|
|
"policy": policy,
|
|
"outcome": outcome,
|
|
"elapsed_s": perf_counter() - started,
|
|
"nodes_expanded": sum(metrics.nodes_expanded for metrics in self.metrics[first_run:]),
|
|
})
|
|
|
|
def _search_trials(self, trials: list[Trial], target: int) -> None:
|
|
super()._search_trials(trials, target)
|
|
limit = self.retry_policy.residual_limit
|
|
if (
|
|
not self.retry_policy.residual_after_fallback
|
|
or limit is None
|
|
or limit > self.options.search.node_limit
|
|
or target != len(self.problem.nets)
|
|
or self.problem.initial_paths
|
|
):
|
|
return
|
|
best = _best_trial(trials)
|
|
if target <= 2 or len(best.valid_costs) != target - 1:
|
|
return
|
|
|
|
retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs}
|
|
options = replace(self.options, refinement=replace(self.options.refinement, enabled=False))
|
|
trials.extend(self._widen_residual(options, retained, limit, target, policy="late-bounded-residual", check_connectivity=True))
|
|
|
|
def _direct(self, options: RoutingOptions, policy: str, *, hints: dict[str, PathSeed] | None = None) -> list[Trial]:
|
|
cap = self.retry_policy.probe_iterations
|
|
if policy == "direct-probe-near-port" and cap is not None:
|
|
configured = self.options.congestion.max_iterations
|
|
iterations = configured if cap == "configured" else min(configured, cap)
|
|
if iterations != options.congestion.max_iterations:
|
|
options = replace(options, congestion=replace(options.congestion, max_iterations=iterations))
|
|
return super()._direct(options, policy, hints=hints)
|
|
|
|
def _seed_recovery_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> None:
|
|
limit = self.retry_policy.lattice_limit
|
|
if (
|
|
limit is not None
|
|
and limit <= self.options.search.node_limit
|
|
and target == len(self.problem.nets) > 2
|
|
and not self.problem.initial_paths
|
|
and _near_port_coverage_stalled(trials, target)
|
|
):
|
|
retry = replace(options, search=replace(options.search, node_limit=limit))
|
|
started, first_run = perf_counter(), len(self.metrics)
|
|
self._lattice_fallback(trials, retry, "Near-port and lookahead searches were one net short", policy="early-bounded-lattice")
|
|
complete = len(trials[-1].valid_costs) == target
|
|
self._record_retry("bounded-lattice", "complete" if complete else "incomplete", started, first_run)
|
|
if complete:
|
|
return
|
|
trials[-1] = replace(trials[-1], selection="incomplete-layout")
|
|
super()._seed_recovery_trials(options, trials, target)
|
|
|
|
def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int) -> list[Trial]:
|
|
trials = super()._incumbent_trials(options, best, target)
|
|
limit = self.retry_policy.residual_limit
|
|
if (
|
|
limit is None
|
|
or self.retry_policy.residual_after_fallback
|
|
or not options.search.node_limit < limit <= self.options.search.node_limit
|
|
or target != len(self.problem.nets)
|
|
or len(best.valid_costs) != target - 1
|
|
or not trials
|
|
or trials[0].stage.kind != "incumbent-residual"
|
|
or any(trial.selectable and len(trial.valid_costs) >= target for trial in trials)
|
|
):
|
|
return trials
|
|
|
|
retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs}
|
|
return [*trials, *self._widen_residual(options, retained, limit, target, policy="bounded-residual")]
|
|
|
|
def _widen_residual(
|
|
self,
|
|
options: RoutingOptions,
|
|
retained: dict[str, RoutingResult],
|
|
limit: int,
|
|
target: int,
|
|
*,
|
|
policy: str,
|
|
check_connectivity: bool = False,
|
|
) -> list[Trial]:
|
|
started, first_run = perf_counter(), len(self.metrics)
|
|
if check_connectivity:
|
|
with self._time("plan", policy=policy):
|
|
blocked = _disconnected_nets(self.problem, self.board, options, retained)
|
|
if blocked:
|
|
self._record_retry(policy, "disconnected", started, first_run)
|
|
return []
|
|
|
|
retry = replace(
|
|
options,
|
|
search=replace(options.search, node_limit=limit),
|
|
topology=replace(options.topology, seed_node_limit=max(limit, options.topology.seed_node_limit)),
|
|
congestion=replace(options.congestion, max_iterations=min(2, options.congestion.max_iterations)),
|
|
)
|
|
run, stage = _route_residual(self.problem, retry, LockPlan(retained), residual_mode="seed", run_route=partial(self._run, policy=policy))
|
|
trial = self._trial(run, replace(stage, kind=policy, policy=policy, incumbent_net_ids=tuple(retained)))
|
|
trials = [replace(trial, selection="requires-layout-check")]
|
|
complete = False
|
|
if len(trial.valid_costs) == target:
|
|
verified = self._verify_incumbent(trial)
|
|
complete = len(verified.valid_costs) == target
|
|
trials.append(verified if complete else replace(verified, selection="incomplete-layout"))
|
|
self._record_retry(policy, "complete" if complete else "incomplete", started, first_run)
|
|
return trials
|
|
|
|
|
|
def _near_port_coverage_stalled(trials: list[Trial], target: int) -> bool:
|
|
near = [trial for trial in trials if trial.selectable and trial.stage.policy == "direct-probe-near-port"]
|
|
wider = [trial for trial in trials if trial.selectable and trial.stage.policy == "direct-lookahead-retry"]
|
|
if not near or not wider:
|
|
return False
|
|
first, second = _best_trial(near), _best_trial(wider)
|
|
return len(first.valid_costs) == target - 1 and first.valid_costs.keys() == second.valid_costs.keys()
|
|
|
|
|
|
def _measure(case: BenchmarkCase, profile: str, name: str) -> dict:
|
|
options = automatic_options(profile_options(case, profile), profile)
|
|
started = perf_counter()
|
|
experiment = None if name == "baseline" else _RetryExperiment(case.problem, options, _POLICIES[name])
|
|
if experiment is None:
|
|
run = route(case.problem, options=options)
|
|
else:
|
|
run = experiment.execute()
|
|
elapsed = perf_counter() - started
|
|
report = run.automatic
|
|
assert report is not None
|
|
verified = sorted(report.verified_net_ids)
|
|
return {
|
|
"elapsed_s": elapsed,
|
|
"verified": verified,
|
|
"routing_bound": report.max_routed,
|
|
"nodes_expanded": run.metrics.nodes_expanded,
|
|
"weighted_cost": {net_id: benchmark_weighted_length(run.results_by_net[net_id]) for net_id in verified},
|
|
"native_cost": native_verified_costs(case, options, run.results_by_net, verified),
|
|
"seeds": {net_id: repr(run.results_by_net[net_id].as_seed()) for net_id in verified},
|
|
"stages": [asdict(stage) for stage in report.stages],
|
|
"selected_stage": report.selected_stage,
|
|
"retry_attempts": [] if experiment is None else experiment.retry_attempts,
|
|
"timings": [asdict(timing) for timing in report.timings],
|
|
}
|
|
|
|
|
|
def _measure_case(job: tuple[BenchmarkCase, str, tuple[str, ...], int]) -> dict:
|
|
case, profile, policies, repeats = job
|
|
samples = {name: [] for name in policies}
|
|
for index in range(repeats):
|
|
offset = index % len(policies)
|
|
for name in policies[offset:] + policies[:offset]:
|
|
samples[name].append(_measure(case, profile, name))
|
|
return {"case": case.name, "profile": profile, "required": len(case.problem.nets), "samples": samples}
|
|
|
|
|
|
def main() -> None:
|
|
parser = ArgumentParser(description=__doc__)
|
|
parser.add_argument("--case", choices=tuple(CASE_GROUPS), action="append")
|
|
parser.add_argument("--profile", choices=PROFILES, action="append")
|
|
parser.add_argument("--policy", choices=tuple(_POLICIES), action="append")
|
|
parser.add_argument("--repeat", type=int, default=1)
|
|
parser.add_argument("--jobs", type=int, default=1)
|
|
parser.add_argument("--json", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
if args.repeat < 1 or args.jobs < 1:
|
|
parser.error("--repeat and --jobs must be positive")
|
|
cases = select_cases(args.case or ["corpus"])
|
|
profiles = tuple(dict.fromkeys(args.profile or ("public-defaults", "corpus-regression")))
|
|
policies = tuple(dict.fromkeys(args.policy or _POLICIES))
|
|
jobs = [(case, profile, policies, args.repeat) for case in cases for profile in profiles]
|
|
rows = []
|
|
with ProcessPoolExecutor(max_workers=args.jobs) as pool:
|
|
for result in pool.map(_measure_case, jobs):
|
|
rows.append(result)
|
|
summary = " ".join(
|
|
f"{name}={len(samples[0]['verified'])}/{result['required']}@{median(s['elapsed_s'] for s in samples):.3f}s"
|
|
for name, samples in result["samples"].items()
|
|
)
|
|
print(result["case"], result["profile"], summary, flush=True)
|
|
args.json.write_text(dumps({"runs": rows}, indent=2) + "\n", encoding="utf-8")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|