Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,13 @@ brute-force reference or a closed-form value and has a regression test.

### Generator caps

- `generator_weight_cap`, and the coverage and heaviest-term bounds built on it, dropped every box LP that HiGHS
called infeasible, and HiGHS's presolve calls feasible box LPs infeasible: on `((1,0),(2,2),(1,0))` it dropped the
box holding a 3-state generator's heaviest state, and the coverage bound came out at 1.0459, above that
generator's entropy 1.0420. An infeasible verdict is now solved again without presolve, and a box is dropped only
with an exact Farkas certificate; the bound meets the generator's entropy to `3e-10`. `certified_lp_minimum`
also retries without presolve when its Farkas test fails.

- With a deadline, each branch-and-bound child LP of `generator_weight_cap` gets the time left as a
HiGHS `time_limit`; a cut-off LP keeps its parent's bound, so the cap stays valid. On a 4-state
survey process (4 × 36 causal states) one degenerate node LP had run more than 8 minutes past a
Expand Down
9 changes: 9 additions & 0 deletions docs/generators/generative_models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,15 @@ cheaper bounds meet the entropy of an ε-machine, which then certifies. At crypt
runs only if the exact path leaves it open; on the 510 dataset processes of that class it had taken about
17 s each and never supplied the lower bound.

The branch and bound drops a box only when HiGHS calls its LP infeasible with and without presolve and an
exact Farkas certificate verifies (:mod:`sofic.generators.certificates`). HiGHS's presolve calls feasible box
LPs infeasible: on ``((1,0),(2,2),(1,0))`` it did so 3,101 times at 1,000 and 2,000 boxes, dropping the box
that holds a 3-state generator's heaviest state at depth 81, and the coverage bound came out at
:math:`C_\mu = 1.0459`, above that generator's entropy :math:`1.0420`. Without presolve every one of those LPs
is feasible, and the bound meets the generator's entropy to :math:`3 \times 10^{-10}`. With float data a nonempty box is always feasible (the explicit
states can have weight 0 and the aggregate the whole generator), so the certificate only guards against
rationalized data.

Coverage only sees the top weights. :func:`~sofic.generators.exact_ci_bounds.heaviest_term_bound`
uses the whole decomposition: with heaviest term :math:`T = t\, q r^\top`, any exact decomposition has
entropy :math:`h(t) + (1 - t) H(\lambda')`, where :math:`\lambda'` decomposes the remainder
Expand Down
33 changes: 20 additions & 13 deletions sofic/generators/certificates.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

import numpy as np
import scipy.sparse as sp
from scipy.optimize import linprog
from scipy.optimize import OptimizeResult, linprog

Vector = Sequence[Any] | np.ndarray

Expand Down Expand Up @@ -211,24 +211,22 @@ def certified_lp_minimum(
certificate is checked against the exact ones. The HiGHS duals are rationalized at each of
``denominators`` and the best exact bound is kept. If HiGHS reports infeasibility, the duals of the
elastic LP (minimize the total violation of the equalities and inequalities) are tested as a Farkas
certificate.
certificate; if that test fails, the LP is solved again without presolve, since HiGHS's presolve can call a
feasible LP infeasible.
"""
c = np.asarray(c, dtype=float)
lo, hi = np.asarray(lo, dtype=float), np.asarray(hi, dtype=float)
data = {"A_eq": A_eq, "b_eq": b_eq, "A_ub": A_ub, "b_ub": b_ub}
b_eq_f = None if b_eq is None else np.array([float(v) for v in b_eq])
b_ub_f = None if b_ub is None else np.array([float(v) for v in b_ub])
res = linprog(
c, A_ub=A_ub, b_ub=b_ub_f, A_eq=A_eq, b_eq=b_eq_f, bounds=list(zip(lo, hi, strict=True)), method="highs"
)
if res.status == 0:
duals = {
"y_eq": res.eqlin.marginals if A_eq is not None else None,
"y_ub": res.ineqlin.marginals if A_ub is not None else None,
}
bound, exact_eq, exact_ub = _best_bound(c, lo, hi, denominators, **data, **duals)
status = "optimal" if bound is not None else "failed"
return CertifiedLPResult(status, bound, float(res.fun), exact_eq, exact_ub)

def solve(options: dict | None = None) -> OptimizeResult:
bounds = list(zip(lo, hi, strict=True))
return linprog(
c, A_ub=A_ub, b_ub=b_ub_f, A_eq=A_eq, b_eq=b_eq_f, bounds=bounds, method="highs", options=options
)

res = solve()
if res.status == 2:
y_eq, y_ub = _elastic_duals(lo, hi, A_eq, b_eq_f, A_ub, b_ub_f)
if y_eq is not None or y_ub is not None:
Expand All @@ -237,6 +235,15 @@ def certified_lp_minimum(
)
if proof is not None and proof > 0:
return CertifiedLPResult("infeasible", None, None, exact_eq, exact_ub)
res = solve({"presolve": False})
if res.status == 0:
duals = {
"y_eq": res.eqlin.marginals if A_eq is not None else None,
"y_ub": res.ineqlin.marginals if A_ub is not None else None,
}
bound, exact_eq, exact_ub = _best_bound(c, lo, hi, denominators, **data, **duals)
status = "optimal" if bound is not None else "failed"
return CertifiedLPResult(status, bound, float(res.fun), exact_eq, exact_ub)
return CertifiedLPResult("failed", None, None)


Expand Down
33 changes: 22 additions & 11 deletions sofic/generators/generator_caps.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

import numpy as np
import scipy.sparse as sp
from scipy.optimize import linprog
from scipy.optimize import OptimizeResult, linprog

from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine
from sofic.generators.certificates import CertifiedLPResult, certified_lp_minimum, dual_bound
Expand Down Expand Up @@ -177,23 +177,32 @@ def envelope(prod: int, factor: int, e: int, is_q: bool, i: int) -> None:
def bound(self, boxes: tuple[tuple[np.ndarray, ...], ...], time_limit: float | None = None) -> float | None:
"""Max total weight of the explicit states with beliefs in ``boxes``; ``None`` if the box is infeasible.

An LP stopped by ``time_limit`` (seconds) returns the trivial bound 1.
HiGHS's presolve can call a feasible box LP infeasible, so an infeasible verdict is re-solved without
presolve, and ``None`` needs an exact Farkas certificate (:meth:`certified_bound`); an infeasible
verdict without one returns the trivial bound 1, as does an LP stopped by ``time_limit`` (seconds).
"""
res = linprog(
A_ub = self.inequalities(boxes)
options = {} if time_limit is None else {"time_limit": max(time_limit, 1e-3)}
res = self._solve(A_ub, options)
if res.status == _HIGHS_INFEASIBLE:
res = self._solve(A_ub, {**options, "presolve": False})
if res.status == _HIGHS_INFEASIBLE:
return None if self.certified_bound(boxes).status == "infeasible" else 1.0
if not res.success:
return 1.0
return float(-res.fun)

def _solve(self, A_ub: sp.csr_matrix, options: dict) -> OptimizeResult:
return linprog(
self.c,
A_ub=self.inequalities(boxes),
A_ub=A_ub,
b_ub=np.zeros(self.n_ub),
A_eq=self.A_eq,
b_eq=self.b_eq,
bounds=(0, 1),
method="highs",
options=None if time_limit is None else {"time_limit": max(time_limit, 1e-3)},
options=options or None,
)
if res.status == _HIGHS_INFEASIBLE:
return None
if not res.success:
return 1.0
return float(-res.fun)

def certified_bound(self, boxes: tuple[tuple[np.ndarray, ...], ...]) -> CertifiedLPResult:
""":meth:`bound` with an exact dual certificate (the LP minimizes minus the weight)."""
Expand Down Expand Up @@ -327,7 +336,9 @@ def generator_weight_cap(

Branches on the widest belief coordinate of any explicit state; the result is valid at any
``max_nodes`` and decreases as it grows. Branching also stops at ``deadline`` (a
:func:`time.monotonic` value), which leaves a valid but looser cap. It is valid up to the LP tolerance (``1e-7`` is added);
:func:`time.monotonic` value), which leaves a valid but looser cap. A box is dropped only when HiGHS calls
its LP infeasible with and without presolve and an exact Farkas certificate verifies; the open boxes' LP
optima are floating point, so the cap is valid up to the LP tolerance (``1e-7`` is added), and
:func:`certified_generator_weight_cap` removes that caveat.
"""
problem = bidir if isinstance(bidir, _GeneratorProblem) else _GeneratorProblem(bidir)
Expand Down
21 changes: 21 additions & 0 deletions tests/test_certificates.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,27 @@ def test_infeasibility_is_certified() -> None:
assert result.status == "infeasible"


def test_a_false_infeasible_verdict_is_solved_again_without_presolve(monkeypatch: pytest.MonkeyPatch) -> None:
from types import SimpleNamespace

import sofic.generators.certificates as certificates

real = certificates.linprog
seen: list[dict | None] = []

def fake(c, *args, options=None, **kwargs):
if len(c) == 1: # the LP itself; the elastic LP has a slack column too
seen.append(options)
if options is None:
return SimpleNamespace(status=2)
return real(c, *args, options=options, **kwargs)

monkeypatch.setattr(certificates, "linprog", fake)
result = certified_lp_minimum([1.0], [0.0], [1.0], A_ub=np.array([[-1.0]]), b_ub=[-0.25])
assert seen == [None, {"presolve": False}]
assert result.status == "optimal" and result.bound == Fraction(1, 4)


def test_unbounded_box_with_bad_sign_gives_none() -> None:
assert dual_bound([1.0], [-np.inf], [1.0]) is None

Expand Down
66 changes: 66 additions & 0 deletions tests/test_generator_caps.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,72 @@ def fake(*args, options=None, **kwargs):
assert max(b for b, _, _ in leaves) == pytest.approx(root)


def test_a_box_highs_presolve_calls_infeasible_keeps_its_generator_state() -> None:
"""A belief box holding the heaviest state (weight 0.4976862) of a 3-state generator of a 3-state process.

scipy 1.17's HiGHS with presolve calls the box's one-explicit-state LP infeasible, which dropped the box at
depth 81 of the branch and bound; without presolve the LP's optimum is 0.4976867.
"""
import sofic.generators.generator_caps as gc

mats = {
0: np.array([[0.0, 0.10369669321827639, 0.0], [0.0, 0.0, 0.67213678972452], [0.0, 0.9987816335358809, 0.0]]),
1: np.array(
[[0.8963033067817237, 0.0, 0.0], [0.0, 0.0, 0.32786321027548004], [0.0012183664641191093, 0.0, 0.0]]
),
}
machine = BidirectionalEpsilonMachine.from_forward(
from_symbol_matrices((0, 1, 2), (0, 1), mats), reverse_max_states=1000
)
u = 2.0**-10
box = (
np.array([u, 0.0, 1 - 2 * u]),
np.array([2 * u, u, 1 - u]),
np.array([0.0, 0.0, 0.0, 0.0, 1 - 6 * u, 0.0, 0.0, 0.0, 2 * u]),
np.array([2 * u, 2 * u, 2 * u, 2 * u, 1 - 4 * u, 2 * u, 2 * u, 2 * u, 4 * u]),
)
relaxation = gc._HeaviestStatesRelaxation(cg._GeneratorProblem(machine), 1)
assert relaxation.bound((box,)) >= 0.4976862 - 1e-7


def test_infeasible_verdicts_are_solved_again_without_presolve(monkeypatch: pytest.MonkeyPatch) -> None:
from types import SimpleNamespace

import sofic.generators.generator_caps as gc

relaxation = gc._HeaviestStatesRelaxation(cg._GeneratorProblem(golden_mean_bidirectional(0.5)), 1)
root = gc._root(relaxation)
expected = relaxation.bound(root)
real = gc.linprog
seen: list[dict | None] = []

def fake(*args, options=None, **kwargs):
seen.append(options)
if options is None:
return SimpleNamespace(status=2, success=False, fun=None)
return real(*args, options=options, **kwargs)

monkeypatch.setattr(gc, "linprog", fake)
assert relaxation.bound(root) == pytest.approx(expected)
assert seen == [None, {"presolve": False}]


def test_a_box_is_dropped_only_with_a_farkas_certificate(monkeypatch: pytest.MonkeyPatch) -> None:
from types import SimpleNamespace

import sofic.generators.generator_caps as gc
from sofic.generators.certificates import CertifiedLPResult

relaxation = gc._HeaviestStatesRelaxation(cg._GeneratorProblem(golden_mean_bidirectional(0.5)), 1)
root = gc._root(relaxation)
monkeypatch.setattr(gc, "linprog", lambda *args, **kwargs: SimpleNamespace(status=2, success=False, fun=None))
# the certificate's own solves are not patched; they find the LP feasible, so the box stays with the trivial bound
assert relaxation.bound(root) == 1.0
infeasible = CertifiedLPResult("infeasible", None, None)
monkeypatch.setattr(gc._HeaviestStatesRelaxation, "certified_bound", lambda self, boxes: infeasible)
assert relaxation.bound(root) is None


@settings(max_examples=300, deadline=None)
@given(st.integers(1, 6).flatmap(lambda n: st.tuples(*[st.tuples(st.floats(0, 1), st.floats(0, 1))] * n)))
def test_tighten_matches_exact_rational_arithmetic(bounds):
Expand Down
Loading