Make retry exports optional and report benchmark placement and selection
This commit is contained in:
parent
f247cff54a
commit
f6e7bac4c5
9 changed files with 78 additions and 20 deletions
|
|
@ -45,6 +45,8 @@ Both budget profiles use benchmark weights when selecting an automatic candidate
|
|||
|
||||
Benchmark JSON records the configured options for each strategy. Each sample's `attempt_options` lists the effective options passed to routing workers in execution order, including rejected bundle attempts and any fallback workers. `requested_mode` is null for policies that choose their own mode for each attempt.
|
||||
|
||||
For explicit `guide` and `seed` runs, `selected_attempt` is the zero-based index into `attempt_options` of the worker whose routes were returned.
|
||||
|
||||
### Run the full benchmark corpus
|
||||
|
||||
```sh
|
||||
|
|
@ -83,7 +85,7 @@ python -m scripts.benchmark_retry_order \
|
|||
--json /tmp/inire-residual.json
|
||||
```
|
||||
|
||||
Compare verified IDs, unchanged incumbents, and time spent on failed attempts.
|
||||
Omit `--json` for a console summary. The optional JSON includes effective ports and polygon hashes for verified nets, so you can compare incumbent placement as well as coverage and time spent on failed attempts.
|
||||
|
||||
- [Earlier retry results](benchmark-results.md#early-and-late-retries)
|
||||
|
||||
|
|
|
|||
|
|
@ -88,6 +88,7 @@ def _dispatch_route(
|
|||
iteration_callback: _IterationCallback | None,
|
||||
*,
|
||||
attempt_callback: Callable[[RoutingOptions], None] | None = None,
|
||||
selected_attempt_callback: Callable[[int], None] | None = None,
|
||||
) -> RoutingRunResult:
|
||||
if options.topology.mode == "automatic":
|
||||
from .router._automatic import route_automatic # noqa: PLC0415
|
||||
|
|
@ -96,7 +97,10 @@ def _dispatch_route(
|
|||
|
||||
from .router._stack import route_explicit # noqa: PLC0415
|
||||
|
||||
return route_explicit(problem, options=options, iteration_callback=iteration_callback, attempt_callback=attempt_callback)
|
||||
return route_explicit(
|
||||
problem, options=options, iteration_callback=iteration_callback, attempt_callback=attempt_callback,
|
||||
selected_attempt_callback=selected_attempt_callback,
|
||||
)
|
||||
|
||||
|
||||
def route(
|
||||
|
|
|
|||
|
|
@ -155,6 +155,7 @@ def route_explicit(
|
|||
options: RoutingOptions,
|
||||
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
|
||||
attempt_callback: Callable[[RoutingOptions], None] | None = None,
|
||||
selected_attempt_callback: Callable[[int], None] | None = None,
|
||||
) -> RoutingRunResult:
|
||||
attempts = RoutingAttempts(iteration_callback, attempt_callback=attempt_callback)
|
||||
with_guidance = attempts.run(problem, options=options)
|
||||
|
|
@ -165,6 +166,8 @@ def route_explicit(
|
|||
or with_guidance.metrics.timeout_events or not with_guidance.topology or not with_guidance.topology.corridor_counts
|
||||
or all(result.is_valid for result in with_guidance.results_by_net.values())
|
||||
):
|
||||
if selected_attempt_callback is not None:
|
||||
selected_attempt_callback(0)
|
||||
return with_guidance
|
||||
|
||||
retry = replace(
|
||||
|
|
@ -174,5 +177,8 @@ def route_explicit(
|
|||
without_guidance = attempts.run(problem, options=retry)
|
||||
old_count = sum(result.is_valid for result in with_guidance.results_by_net.values())
|
||||
new_count = sum(result.is_valid for result in without_guidance.results_by_net.values())
|
||||
selected = without_guidance if new_count > old_count else with_guidance
|
||||
retry_won = new_count > old_count
|
||||
if selected_attempt_callback is not None:
|
||||
selected_attempt_callback(int(retry_won))
|
||||
selected = without_guidance if retry_won else with_guidance
|
||||
return replace(selected, metrics=attempts.metrics())
|
||||
|
|
|
|||
|
|
@ -2,9 +2,12 @@
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from dataclasses import asdict, replace
|
||||
from hashlib import sha256
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from shapely import to_wkb
|
||||
|
||||
from inire import RoutingOptions
|
||||
from inire.router.cost import build_native_cost_evaluator, weighted_path_length
|
||||
from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES
|
||||
|
|
@ -134,6 +137,13 @@ def benchmark_weighted_length(result: RoutingResult) -> float:
|
|||
return weighted_path_length(result.path, LENGTH_COST)
|
||||
|
||||
|
||||
def route_placement(result: RoutingResult) -> dict:
|
||||
return {
|
||||
"effective_net": asdict(result.effective_net) if result.effective_net is not None else None,
|
||||
"physical_polygon_hashes": [sha256(wkb).hexdigest() for wkb in to_wkb(result.locked_geometry, byte_order=1)],
|
||||
}
|
||||
|
||||
|
||||
def native_verified_costs(
|
||||
case: BenchmarkCase,
|
||||
options: RoutingOptions,
|
||||
|
|
|
|||
|
|
@ -192,6 +192,17 @@ def test_retry_experiment_preserves_public_input_handling() -> None:
|
|||
assert baseline["routing_bound"] == experiment["routing_bound"] == 1
|
||||
assert baseline["nodes_expanded"] == experiment["nodes_expanded"] == 0
|
||||
assert baseline["stages"] == experiment["stages"]
|
||||
assert baseline["placements"] == experiment["placements"]
|
||||
|
||||
coincident, straight = problem.nets
|
||||
moved = replace(straight, start=straight.start.translate(dy=5), target=straight.target.translate(dy=5))
|
||||
moved_case = replace(case, problem=replace(problem, nets=(coincident, moved)))
|
||||
shifted = _measure_retry(moved_case, "matched-budget", "baseline")
|
||||
assert shifted["seeds"] == baseline["seeds"]
|
||||
original_placement = baseline["placements"]["straight"]
|
||||
moved_placement = shifted["placements"]["straight"]
|
||||
assert moved_placement["effective_net"]["start"]["y"] == 20
|
||||
assert moved_placement["physical_polygon_hashes"] != original_placement["physical_polygon_hashes"]
|
||||
|
||||
|
||||
def test_direct_benchmarks_validate_inputs_before_locking_routes() -> None:
|
||||
|
|
|
|||
|
|
@ -9,7 +9,9 @@ from inire import (
|
|||
)
|
||||
from inire.router._stack import build_routing_stack
|
||||
from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_lane_assignments, plan_corridors
|
||||
from inire.tests.routing_benchmark_case import BenchmarkCase
|
||||
from inire.tests.routing_benchmarks import DETOUR
|
||||
from scripts.compare_topological_routing import _measure
|
||||
|
||||
|
||||
def test_seed_mode_recovers_a_corridor_after_an_invalid_hint() -> None:
|
||||
|
|
@ -135,6 +137,13 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None:
|
|||
assert [entry.iteration for entry in run.conflict_trace if entry.stage == "iteration"] == [2]
|
||||
assert run.conflict_trace[-1].iteration is None
|
||||
|
||||
case = BenchmarkCase("guidance-retry", "Two offset gates", problem, options)
|
||||
sample = _measure(case, options, mode)
|
||||
|
||||
assert sample.valid_costs.keys() == {"a", "b"}
|
||||
assert [attempt.topology.guide_strength for attempt in sample.attempt_options] == [0.75, 0.0]
|
||||
assert sample.selected_attempt == 1
|
||||
|
||||
|
||||
def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
problem = DETOUR.problem
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ from inire.tests.routing_corpus import (
|
|||
benchmark_weighted_length,
|
||||
native_verified_costs,
|
||||
profile_options,
|
||||
route_placement,
|
||||
select_cases,
|
||||
)
|
||||
|
||||
|
|
@ -184,7 +185,7 @@ def _near_port_coverage_stalled(trials: list[Trial], target: int) -> bool:
|
|||
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:
|
||||
def _measure(case: BenchmarkCase, profile: str, name: str, *, capture_details: bool = True) -> dict:
|
||||
options = automatic_options(profile_options(case, profile), profile)
|
||||
retry_attempts: list[dict] = []
|
||||
|
||||
|
|
@ -205,14 +206,17 @@ def _measure(case: BenchmarkCase, profile: str, name: str) -> dict:
|
|||
report = run.automatic
|
||||
assert report is not None
|
||||
verified = sorted(report.verified_net_ids)
|
||||
summary = {"elapsed_s": elapsed, "verified": verified}
|
||||
if not capture_details:
|
||||
return summary
|
||||
return {
|
||||
"elapsed_s": elapsed,
|
||||
"verified": verified,
|
||||
**summary,
|
||||
"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},
|
||||
"placements": {net_id: route_placement(run.results_by_net[net_id]) for net_id in verified},
|
||||
"stages": [asdict(stage) for stage in report.stages],
|
||||
"selected_stage": report.selected_stage,
|
||||
"retry_attempts": retry_attempts,
|
||||
|
|
@ -220,13 +224,13 @@ def _measure(case: BenchmarkCase, profile: str, name: str) -> dict:
|
|||
}
|
||||
|
||||
|
||||
def _measure_case(job: tuple[BenchmarkCase, str, tuple[str, ...], int]) -> dict:
|
||||
case, profile, policies, repeats = job
|
||||
def _measure_case(job: tuple[BenchmarkCase, str, tuple[str, ...], int, bool]) -> dict:
|
||||
case, profile, policies, repeats, capture_details = 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))
|
||||
samples[name].append(_measure(case, profile, name, capture_details=capture_details))
|
||||
return {"case": case.name, "profile": profile, "required": len(case.problem.nets), "samples": samples}
|
||||
|
||||
|
||||
|
|
@ -237,23 +241,26 @@ def main() -> None:
|
|||
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)
|
||||
parser.add_argument("--json", type=Path, help="Write per-run coverage, placement, costs, and retry details to this file.")
|
||||
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]
|
||||
capture_details = args.json is not None
|
||||
jobs = [(case, profile, policies, args.repeat, capture_details) 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):
|
||||
if capture_details:
|
||||
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)
|
||||
if args.json is not None:
|
||||
args.json.write_text(dumps({"runs": rows}, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ class RunSample:
|
|||
bundle_rejection: str | None = None
|
||||
bundle_duration_s: float | None = None
|
||||
selected_stage: int = 0
|
||||
selected_attempt: int | None = None
|
||||
capacity_limit: CapacityLimit | None = None
|
||||
planner_rejections: tuple[str, ...] = ()
|
||||
port_conflicts: tuple[tuple[str, str], ...] = ()
|
||||
|
|
@ -116,7 +117,17 @@ def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: st
|
|||
def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> RunSample:
|
||||
board = box(*case.problem.bounds)
|
||||
attempt_options: list[RoutingOptions] = []
|
||||
run_route = partial(_route, run_router=partial(_dispatch_route, attempt_callback=attempt_options.append))
|
||||
selected_attempt: int | None = None
|
||||
|
||||
def select_attempt(index: int) -> None:
|
||||
nonlocal selected_attempt
|
||||
selected_attempt = index
|
||||
|
||||
dispatch = partial(
|
||||
_dispatch_route, attempt_callback=attempt_options.append,
|
||||
selected_attempt_callback=select_attempt if strategy in ("guide", "seed") else None,
|
||||
)
|
||||
run_route = partial(_route, run_router=dispatch)
|
||||
run_worker = partial(route_once, attempt_callback=attempt_options.append)
|
||||
|
||||
def measure_direct(problem: RoutingProblem, policy: str) -> tuple[RoutingRunResult, list[Trial]]:
|
||||
|
|
@ -203,6 +214,7 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run
|
|||
bundle_rejection=bundle_rejection,
|
||||
bundle_duration_s=bundle_duration,
|
||||
selected_stage=next(i for i, trial in enumerate(trials) if trial is best),
|
||||
selected_attempt=selected_attempt,
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -5,14 +5,11 @@ from __future__ import annotations
|
|||
from argparse import ArgumentParser
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from dataclasses import asdict, replace
|
||||
from hashlib import sha256
|
||||
from json import dumps, loads
|
||||
from pathlib import Path
|
||||
from time import perf_counter
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from shapely import to_wkb
|
||||
|
||||
from inire import DiagnosticsOptions, route
|
||||
from inire.results import RouteMetrics
|
||||
from inire.tests.routing_corpus import (
|
||||
|
|
@ -22,6 +19,7 @@ from inire.tests.routing_corpus import (
|
|||
benchmark_weighted_length,
|
||||
native_verified_costs,
|
||||
profile_options,
|
||||
route_placement,
|
||||
select_cases,
|
||||
)
|
||||
from scripts.compare_topological_routing import _geometry_json
|
||||
|
|
@ -42,8 +40,7 @@ def _paths(results: dict[str, RoutingResult]) -> dict:
|
|||
"outcome": result.outcome,
|
||||
"reached_target": result.reached_target,
|
||||
"seed": [{"kind": type(move).__name__, **asdict(move)} for move in result.as_seed().segments],
|
||||
"effective_net": asdict(result.effective_net) if result.effective_net is not None else None,
|
||||
"physical_polygon_hashes": [sha256(wkb).hexdigest() for wkb in to_wkb(result.locked_geometry, byte_order=1)],
|
||||
**route_placement(result),
|
||||
"report": asdict(result.report),
|
||||
}
|
||||
for net_id, result in results.items()
|
||||
|
|
|
|||
Loading…
Reference in a new issue