diff --git a/CHANGELOG.md b/CHANGELOG.md index 352067f..2b607c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,6 +76,15 @@ brute-force reference or a closed-form value and has a regression test. - `targeted_line_split_seeds` begins no start after its deadline, even when none has succeeded, and a running Nelder-Mead start stops there while COBYLA keeps its last feasible point; only the polish of the best decomposition runs past it. On `n3-t131-d2` seventeen failed starts had carried the stage 466 s past its deadline. +- `functional_cover_search` takes a `deadline`, and the pipeline's functional stage gets 30% of the remaining budget. + Each solve gets the time left as HiGHS's time limit; a solve stopped there, or a deadline passed between covers, + ends the search with `exact` False, the identity cover and `stopped` set, and the stage then offers no generator. + With a deadline the search is skipped above 20,000 product rectangles, since HiGHS checks its time limit only after + a presolve whose cost grows faster than the column count. On `s3-n2-t0022-d2`, a 2-state ternary process with + 132,103 product rectangles, the first cover took 535 s and a 5 s time limit stopped it at 343 s (at 9 s with + 20,000 of its rectangles), and `generative_model` took 750 s on a 300 s budget when the stage started before its + deadline. Of the 825 processes in the generator archive it is the only one with more than 20,000 product + rectangles and fewer than `product_rectangles`' limit of 200,000 (median 6, next largest 12,297). - With `time_budget`, the stages from the simplex-chain search on stop a fifth of the budget early when the final generator heaviest-term bound can run (`generator_heaviest_term`, not Wyner, at most 14 causal states), and that stage gets the rest. The stages before the chain search still share the whole budget. Every stage takes a share diff --git a/docs/generators/generative_models.rst b/docs/generators/generative_models.rst index 4c8e594..7a43f9c 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -307,7 +307,10 @@ support, so the search least-entropy exact cover by product rectangles, whose value is the functional common information :math:`\op{F}{S^+ : S^-}` :cite:`james2017multivariate`, checks the lifting conditions, and excludes failed covers until one generates. The result is exact, with a certified lower bound if -``max_covers`` runs out. On the :math:`(2, \infty)` process the first cover has entropy +``max_covers`` runs out. With a ``deadline`` (the pipeline's functional stage passes 30% of the +remaining budget) each solve is limited to the time left, and the search stops with ``exact`` False +when it passes; it is skipped above 20,000 product rectangles, where HiGHS runs far past its time +limit. On the :math:`(2, \infty)` process the first cover has entropy :math:`2 - \tfrac38 \log_2 3` but does not generate; the minimal functional generator has :math:`3/2` bits, equal to :math:`C_g`. diff --git a/sofic/generators/functional_generators.py b/sofic/generators/functional_generators.py index cc41152..95a5ed9 100644 --- a/sofic/generators/functional_generators.py +++ b/sofic/generators/functional_generators.py @@ -18,6 +18,7 @@ from __future__ import annotations +import time from dataclasses import dataclass from itertools import product @@ -30,6 +31,9 @@ from sofic.generators.epsilon_machine import EpsilonMachine _MAX_RECTANGLES = 200_000 +# HiGHS checks its time limit only after a presolve whose cost grows faster than the column count: with a 5 s limit, +# 20,000 rectangles stopped at 9 s and 132,103 at 343 s. +_DEADLINE_MAX_RECTANGLES = 20_000 _PRODUCT_RTOL = 1e-8 _PRODUCT_ATOL = 1e-12 _LIFT_ATOL = 1e-10 @@ -88,7 +92,8 @@ class FunctionalCoverSearch: ``labels[i]`` is the state of joint state ``i``; ``value`` its entropy; ``lower`` a certified lower bound on the least entropy of a functional generator (``lower == value`` when ``exact``); ``functional_common_information`` the first cover's entropy :math:`\\op{F}{S^+ : S^-}`; - ``rejected`` how many covers failed the lifting conditions. + ``rejected`` how many covers failed the lifting conditions; ``stopped`` why a deadline ended the + search (``None`` otherwise). """ labels: np.ndarray @@ -97,10 +102,19 @@ class FunctionalCoverSearch: exact: bool functional_common_information: float rejected: int + stopped: str | None = None -def functional_cover_search(problem: _GeneratorProblem, *, max_covers: int = 2000) -> FunctionalCoverSearch: - """Least-entropy functional generator by exact cover with no-good cuts; see the module docstring.""" +def functional_cover_search( + problem: _GeneratorProblem, *, max_covers: int = 2000, deadline: float | None = None +) -> FunctionalCoverSearch: + """Least-entropy functional generator by exact cover with no-good cuts; see the module docstring. + + ``deadline`` is a :func:`time.monotonic` value. Each solve gets the time left as its limit, and a solve + stopped there or a deadline passed between covers ends the search with ``exact`` False and the identity + cover; ``lower`` then counts only the covers solved to optimality. With a deadline the search is skipped + above 20,000 product rectangles, where HiGHS runs far past its time limit. + """ lifted = problem.lifted pairs, p = list(lifted.pairs), lifted.p n = len(pairs) @@ -115,12 +129,28 @@ def functional_cover_search(problem: _GeneratorProblem, *, max_covers: int = 200 cuts: list[np.ndarray] = [] lower = 0.0 first = None + + def stop(reason: str) -> FunctionalCoverSearch: + return FunctionalCoverSearch(best_labels, best_value, lower, False, first or best_value, len(cuts), reason) + + if deadline is not None and len(blocks) > _DEADLINE_MAX_RECTANGLES: + return stop(f"more than {_DEADLINE_MAX_RECTANGLES:,} product rectangles") for _ in range(max_covers): + options: dict[str, float] = {} + if deadline is not None: + left = deadline - time.monotonic() + if left <= 0.0: + return stop("deadline") + options["time_limit"] = left constraints = [LinearConstraint(cover, 1, 1)] if cuts: cut_rows = np.array(cuts) constraints.append(LinearConstraint(cut_rows, -np.inf, cut_rows.sum(axis=1) - 1)) - res = milp(costs, constraints=constraints, integrality=np.ones(len(blocks)), bounds=Bounds(0, 1)) + res = milp( + costs, constraints=constraints, integrality=np.ones(len(blocks)), bounds=Bounds(0, 1), options=options + ) + if res.status == 1: + return stop("time limit") if not res.success: return FunctionalCoverSearch(best_labels, best_value, best_value, True, first or best_value, len(cuts)) chosen = np.flatnonzero(res.x > 0.5) diff --git a/sofic/generators/generative_search.py b/sofic/generators/generative_search.py index 4148003..558271d 100644 --- a/sofic/generators/generative_search.py +++ b/sofic/generators/generative_search.py @@ -1079,7 +1079,7 @@ def maybe_return_early() -> GenerativeModelResult | None: if "functional" in stages and not out_of_time("functional cover search"): try: - cover = functional_cover_search(problem) + cover = functional_cover_search(problem, deadline=share(0.3)) except StochasticValidationError as exc: log.append({"stage": "functional cover search", "error": str(exc)}) else: @@ -1089,9 +1089,13 @@ def maybe_return_early() -> GenerativeModelResult | None: "value": cover.value, "exact": cover.exact, "rejected covers": cover.rejected, + "stopped": cover.stopped, } ) - offer("minimal functional generator", problem.channel_seed(np.eye(cover.labels.max() + 1)[cover.labels])) + if cover.stopped is None: + offer( + "minimal functional generator", problem.channel_seed(np.eye(cover.labels.max() + 1)[cover.labels]) + ) if "lifted" in stages and not out_of_time("lifted channel"): if small: diff --git a/tests/test_generative_objectives.py b/tests/test_generative_objectives.py index 1966ad9..3edb9c0 100644 --- a/tests/test_generative_objectives.py +++ b/tests/test_generative_objectives.py @@ -2,11 +2,15 @@ from __future__ import annotations +import time + import numpy as np import pytest +from scipy.optimize import OptimizeResult from sofic.examples.epsilon_machines import golden_mean_bidirectional from sofic.generators import coupled_generators as cg +from sofic.generators import functional_generators as fg from sofic.generators.functional_generators import ( functional_cover_search, minimal_functional_generator, @@ -71,6 +75,44 @@ def test_functional_cover_search_lower_bound_when_truncated() -> None: assert search.lower <= 1.5 <= search.value + 1e-12 +def test_functional_cover_search_stops_at_its_deadline() -> None: + problem = cg._GeneratorProblem(_rll()) + search = functional_cover_search(problem, deadline=time.monotonic() - 1.0) + assert search.stopped == "deadline" + assert not search.exact + assert search.lower == 0.0 + np.testing.assert_array_equal(search.labels, np.arange(len(problem.lifted.pairs))) + assert functional_cover_search(problem, deadline=time.monotonic() + 60.0).stopped is None + + +def test_functional_cover_search_time_limit_is_not_exhaustion(monkeypatch) -> None: + monkeypatch.setattr(fg, "milp", lambda *args, **kwargs: OptimizeResult(status=1, success=False, x=None)) + search = functional_cover_search(cg._GeneratorProblem(_rll()), deadline=time.monotonic() + 60.0) + assert search.stopped == "time limit" + assert not search.exact + + +def test_functional_cover_search_skips_many_rectangles_only_on_a_deadline(monkeypatch) -> None: + problem = cg._GeneratorProblem(_rll()) + monkeypatch.setattr(fg, "_DEADLINE_MAX_RECTANGLES", 1) + search = functional_cover_search(problem, deadline=time.monotonic() + 60.0) + assert search.stopped == "more than 1 product rectangles" + assert not search.exact + assert functional_cover_search(problem).exact + + +def test_generative_model_gives_the_functional_stage_a_deadline(monkeypatch) -> None: + from sofic.generators.generative_search import generative_model_from_bidirectional + + monkeypatch.setattr(fg, "_DEADLINE_MAX_RECTANGLES", 1) + result = generative_model_from_bidirectional( + golden_mean_bidirectional(0.5), stages=("machines", "functional"), time_budget=60.0, early_certified=False + ) + (stage,) = [s for s in result.stages if s["stage"] == "functional cover search"] + assert stage["stopped"] == "more than 1 product rectangles" + assert result.upper_source != "minimal functional generator" + + def test_functional_generator_certified_on_sixteen_pair_interleaved() -> None: result = minimal_functional_generator(_interleaved(0.1)) assert result.certified