From 31b2aa7bc118915e0f261b33cd6d2473adacbfd1 Mon Sep 17 00:00:00 2001 From: Ryan James Date: Sat, 28 Nov 2026 17:39:36 -0700 Subject: [PATCH] Bracket exploding builds from the forward machine When the bidirectional build explodes (the reverse mixed-state presentation does not close, after the retry ladder), generative_model now brackets C_g from the forward machine alone instead of raising: the future-window generator coverage bound (at most 30% of the budget) below, and the least state entropy among the forward epsilon-machine and the belief-free HMM search's generators, verified against the forward machine's words, above. The stages that need the reverse epsilon-machine are logged as skipped, and decomposition is None. Other failed builds still raise, as do minimal_wyner_model and minimal_functional_generator. --- CHANGELOG.md | 11 ++ docs/generators/generative_models.rst | 13 +- sofic/generators/generative_search.py | 188 ++++++++++++++++++++++++-- tests/test_generative_model.py | 83 ++++++++++++ 4 files changed, 285 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b607c3..9225ae0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,17 @@ brute-force reference or a closed-form value and has a regression test. truncated build with 69 reverse states the search ran 163 s past its share (`generative_model` took 392 s on a 300 s budget, 491 s on `main`). +### Exploding bidirectional builds + +- `generative_model` no longer raises when the bidirectional build explodes (`bidir_class` `"explosion"`: the reverse + mixed-state presentation does not close, after the retry ladder). It brackets `C_g` from the forward machine alone: + the lower bound is the future-window generator coverage bound (Löhr & Ay 2009), computed first with at most 30% of + the budget, and the upper bound the least state entropy among the forward ε-machine and the belief-free HMM + search's generators, word-verified against the forward machine. The stages that need the reverse ε-machine are + logged as skipped, and `decomposition` is `None`. On a binary 3-state process whose reverse presentation passes + 1,000 states, a 60 s run with `reverse_max_states=1000` and no ladder returns [0.8827307, 1.0795992]. Other failed + builds still raise, as do `minimal_wyner_model` and `minimal_functional_generator`. + ### Coverage bound: least entropy under the caps - `coverage_entropy_lower(caps)`, the last step of `coverage_bound`, `generator_coverage_bound` and the pipeline's diff --git a/docs/generators/generative_models.rst b/docs/generators/generative_models.rst index 7a43f9c..367eff8 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -452,7 +452,18 @@ the final heaviest-term bound. Its lower bound is the larger future-window gener :math:`L = 2` and 3 (1,000 and 2,000 boxes for the two explicit caps at :math:`L = 2`, 300 and 600 at :math:`L = 3`), computed first, with at most 30% of the time budget :cite:`LohrAy2009`. :func:`~sofic.generators.generative_search.minimal_wyner_model` reports ``lower`` 0 on a truncated build. -Machines whose bidirectional build fails still raise. + +When the reverse mixed-state presentation does not close (``bidir_class`` ``"explosion"``, after the retry +ladder), :func:`~sofic.generators.generative_search.generative_model` brackets :math:`C_g` from the forward +machine alone instead of raising. The lower bound is the same future-window bound, with at most 30% of the +budget :cite:`LohrAy2009`. The upper bound is the least state entropy among the forward ε-machine and the +generators of the belief-free HMM search (:func:`~sofic.generators.hmm_search.hmm_generator_search`, at +:math:`|S^+|` to :math:`|S^+| + 2` states with the rest of the budget split evenly between them; two state counts +and two starts without a budget), each verified against the forward machine's words. The stages that need the reverse ε-machine are logged as skipped +(``"needs the reverse ε-machine"``), ``decomposition`` is ``None``, and so are the ``functional``, +``lifting_residual`` and ``lifted`` entries of ``structure``. Other failed builds still raise, as do +:func:`~sofic.generators.generative_search.minimal_wyner_model` and +:func:`~sofic.generators.functional_generators.minimal_functional_generator`. Supports without 2 × 2 rectangles --------------------------------- diff --git a/sofic/generators/generative_search.py b/sofic/generators/generative_search.py index 558271d..c380a4a 100644 --- a/sofic/generators/generative_search.py +++ b/sofic/generators/generative_search.py @@ -58,8 +58,14 @@ the exact path, the heaviest-term bounds and the restricted global bound's) and reports the larger future-window generator coverage bound at :math:`L = 2` and 3 (:func:`~sofic.generators.generator_problem_spec.window_spec`), a lower bound on :math:`C_g` :cite:`LohrAy2009` that needs only the forward machine, computed first with at most 30% -of the budget. :func:`minimal_wyner_model` reports ``lower`` 0 there. Machines whose bidirectional build fails still -raise. +of the budget. :func:`minimal_wyner_model` reports ``lower`` 0 there. + +*Exploding builds.* When the reverse mixed-state presentation does not close (``bidir_class`` ``"explosion"``), +:func:`generative_model` brackets :math:`C_g` from the forward machine alone: ``lower`` is the same future-window +bound, and ``upper`` the least state entropy among the forward ε-machine and the belief-free HMM search's generators, +word-verified against the forward machine. The stages that need the reverse ε-machine are logged as skipped, and +``decomposition`` is ``None``. Other failed builds raise, as do :func:`minimal_wyner_model` and +:func:`~sofic.generators.functional_generators.minimal_functional_generator` on any failed build. Every candidate is word-verified. ``certified`` reports when ``lower`` meets ``upper``. :func:`minimal_wyner_model` runs the same stages ranked by :math:`\I{W : S^+, S^-}`; the functional @@ -77,7 +83,7 @@ import numpy as np -from sofic.exceptions import StochasticValidationError +from sofic.exceptions import MixedStateExplosionError, StochasticValidationError from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine from sofic.generators.coupled_generators import ( CoupledGenerativeModel, @@ -117,6 +123,7 @@ theorem_generator, ) from sofic.generators.simplex_chains import simplex_chain_search +from sofic.graph import ATTR_EMISSION, ATTR_PROB, TransitionGraph _MAX_RECTANGLES = 7 _FLOW_THRESHOLDS = ((0.6,), (0.55, 0.65)) @@ -144,6 +151,17 @@ # 3-state process without a deadline), and the share of a time budget it may use. _WINDOW_NODES = {2: (1000, 2000), 3: (300, 600)} _WINDOW_SHARE = 0.3 +# Stages of the bracket search that need the reverse ε-machine, skipped when its build explodes. +_REVERSE_STAGES = ( + "lower bounds", + "exact path", + "simplex-chain search", + "memory lifts", + "functional cover search", + "lifted channel", + "universal coupled search", + "generator heaviest-term bound (certified)", +) # The restricted global bound runs only on SCIP models up to this many variables (two-step flows included; # 3-state binary processes at 4 states have about 1,200), and for this many seconds when there is no budget. _GLOBAL_BOUND_MAX_VARS = 2_000 @@ -347,6 +365,15 @@ def _theorem_applies(problem: _GeneratorProblem, *, atol: float = 1e-10) -> bool return f_crit < atol and r_crit < atol +class _BuildExplosionError(MixedStateExplosionError): + """A bidirectional build that exploded, with the forward ε-machine and the build log.""" + + def __init__(self, message: str, forward: EpsilonMachine, meta: dict[str, Any]) -> None: + super().__init__(message) + self.forward = forward + self.meta = meta + + def resolve_bidirectional( machine: BidirectionalEpsilonMachine | EpsilonMachine, *, @@ -357,7 +384,9 @@ def resolve_bidirectional( """Build or accept a bidirectional ε-machine for generator search. A bidirectional input is classed as a build would be: ``"truncated"`` when the reverse ε-machine of its - forward machine is infinite, ``"finite"`` otherwise. + forward machine is infinite, ``"finite"`` otherwise. A failed build raises + :class:`~sofic.exceptions.StochasticValidationError` (a + :class:`~sofic.exceptions.MixedStateExplosionError` when it exploded). """ from sofic.generators.bidirectional_build import try_build_bidirectional @@ -379,7 +408,10 @@ def resolve_bidirectional( if built.preflight.error: meta["build_error"] = built.preflight.error if built.bidir is None: - raise StochasticValidationError(f"generative_model: bidirectional build failed ({built.preflight.bidir_class})") + message = f"generative_model: bidirectional build failed ({built.preflight.bidir_class})" + if built.preflight.bidir_class == "explosion": + raise _BuildExplosionError(message, forward, meta) + raise StochasticValidationError(message) return built.bidir, meta @@ -412,6 +444,129 @@ def _future_window_bound( return value, source, log +def _model_from_matrices( + symbols: Sequence[Any], matrices: Sequence[np.ndarray], pi: np.ndarray, alphabet: frozenset[Any], cutoff: float +) -> CoupledGenerativeModel: + """The generator with symbol matrices ``matrices`` (in ``symbols`` order), started from ``pi``; states of weight + at most ``cutoff`` are dropped and smaller entries cleared, as in + :func:`~sofic.generators.coupled_generators._model_from_kernel`.""" + pi = np.asarray(pi, dtype=float) + T = [np.asarray(M, dtype=float) for M in matrices] + active = [w for w in range(len(pi)) if pi[w] > cutoff] + names = {w: f"G{i}" for i, w in enumerate(active)} + graph = TransitionGraph() + for w in active: + graph.add_state(names[w]) + for w in active: + row = np.array([M[w, active] for M in T]) + row = np.where(row > cutoff, row, 0.0) + row /= row.sum() + for xi, x in enumerate(symbols): + for j, v in enumerate(active): + if row[xi, j] > 0: + graph.add_transition(names[w], names[v], **{ATTR_PROB: float(row[xi, j]), ATTR_EMISSION: x}) + mass = pi[active] / pi[active].sum() + model = CoupledGenerativeModel( + graph=graph, + initial_distribution={names[w]: float(m) for w, m in zip(active, mass, strict=True)}, + observation_alphabet=alphabet, + ) + model.validate() + return model + + +def _forward_only_result( + forward: EpsilonMachine, + build_meta: dict[str, Any], + *, + explicit: int, + k_max: int, + hmm_search: bool, + hmm_search_starts: int, + global_bound: bool, + reproduction_atol: float, + time_budget: float | None, + rng: np.random.Generator | None, +) -> GenerativeModelResult: + """The bracket on :math:`C_g` from the forward ε-machine alone, for a process whose bidirectional build exploded. + + ``lower`` is the future-window generator coverage bound, computed first with at most 30% of ``time_budget``. + ``upper`` is the least state entropy among the forward ε-machine and the belief-free HMM search's generators + (the rest of the budget, split evenly between the state counts), each word-verified against the forward machine. + The stages that need the reverse ε-machine are logged as skipped. + """ + from sofic.generators.hmm_search import _stationary + from sofic.generators.matrices import emission_tensors, symbol_matrices + from sofic.generators.minimal_generative_model import _reproduction_error, _reproduction_length + + log = _StageLog() + log.append({"stage": "bidirectional build", **build_meta}) + end = None if time_budget is None else log.start + time_budget + stop = None if time_budget is None else log.start + _WINDOW_SHARE * time_budget + lower, lower_source, window_log = _future_window_bound(forward, explicit=explicit, k_max=k_max, deadline=stop) + for entry in window_log: + log.append(entry) + for stage in (*_REVERSE_STAGES, *(("restricted global bound",) if global_bound else ())): + log.append({"stage": stage, "skipped": "needs the reverse ε-machine"}) + + mats = symbol_matrices(forward.to_mealy()) + symbols = list(mats) + T = [np.asarray(mats[x], dtype=float) for x in symbols] + pi = _stationary(np.sum(T, axis=0)) + candidates = [(_entropy(pi), "epsilon machine", T, pi)] + log.append({"stage": "epsilon machine", "value": candidates[0][0]}) + if hmm_search: + ks = range(len(pi), len(pi) + (3 if end is not None else 2)) + n_starts = hmm_search_starts if end is not None else 2 + found = 0 + for i, k in enumerate(ks): + now = time.monotonic() + if end is not None and now >= end: + break + deadline = None if end is None else now + (end - now) / (len(ks) - i) + for res in hmm_generator_search(forward, k, starts=n_starts, rng=rng, deadline=deadline)[:2]: + name = f"belief-free HMM k={k} (start {res.start})" + log.append({"stage": name, "value": res.entropy, "word_residual": res.word_residual}) + candidates.append((res.entropy, name, list(res.matrices), np.asarray(res.pi, dtype=float))) + found += 1 + log.append({"stage": "belief-free HMM search", "k": list(ks), "starts": n_starts, "generators": found}) + + length = _reproduction_length(forward) + for _, name, matrices, weights in sorted(candidates, key=lambda c: c[0]): + model = _model_from_matrices(symbols, matrices, weights, forward.observation_alphabet, 1e-9) + error = float(_reproduction_error(model, forward, max_length=length)) + if error > reproduction_atol: + continue + start, model_mats = emission_tensors(model) + start = np.asarray(start, dtype=float) + drift = start @ sum(np.asarray(M, dtype=float) for M in model_mats.values()) - start + if float(np.abs(drift).max()) > reproduction_atol: + continue + upper = _entropy(start) + return _finalize_result( + GenerativeModelResult( + model=model, + upper=upper, + lower=float(min(lower, upper)), + upper_source=name, + lower_source=lower_source, + exact_common_information_estimate=None, + separating_variables_generate=False, + stages=log, + budget_exhausted=end is not None and time.monotonic() >= end, + reproduction_error=error, + structure={ + "n_states": len(start), + "weights": sorted((float(w) for w in start), reverse=True), + "functional": None, + "lifting_residual": None, + "lifted": None, + }, + ) + ) + raise StochasticValidationError("generative_model: no generator of the forward ε-machine reproduces it") + + def _channel_matrix(problem: _GeneratorProblem, channel: dict) -> np.ndarray: states = sorted({w for row in channel.values() for w in row}, key=repr) return np.array([[channel[pair].get(w, 0.0) for w in states] for pair in problem.lifted.pairs]) @@ -1472,7 +1627,8 @@ def generative_model( 1. Build a bidirectional ε-machine (preflight / optional retry ladder). On a truncation (the reverse ε-machine is infinite) the future-window generator coverage bound replaces the lower bounds computed on it; see - "Truncated builds" in the module docstring. + "Truncated builds" in the module docstring. When the build explodes, the search falls back to the forward + machine alone ("Exploding builds" there). 2. Certified lower bounds and persistent-crypticity test on the edge. 3. When :math:`p.\\chi^+ \\approx p.\\chi^- \\approx 0` (cryptic order at most 1), the exact path writes down the generator of a least-entropy separating decomposition with at most :math:`K(P)` terms @@ -1494,9 +1650,23 @@ def generative_model( ``global_bound`` and ``global_bound_states`` are as in :func:`generative_model_from_bidirectional`. """ start = time.monotonic() - bidir, build_meta = resolve_bidirectional( - machine, reverse_max_states=reverse_max_states, use_ladder=use_ladder, time_budget=time_budget - ) + try: + bidir, build_meta = resolve_bidirectional( + machine, reverse_max_states=reverse_max_states, use_ladder=use_ladder, time_budget=time_budget + ) + except _BuildExplosionError as exc: + return _forward_only_result( + exc.forward, + exc.meta, + explicit=generator_caps, + k_max=coverage_k_max, + hmm_search=hmm_search, + hmm_search_starts=hmm_search_starts, + global_bound=global_bound, + reproduction_atol=reproduction_atol, + time_budget=None if time_budget is None else max(0.0, time_budget - (time.monotonic() - start)), + rng=rng, + ) window_lower, window_log = None, [] if build_meta["bidir_class"] == "truncated": stop = None diff --git a/tests/test_generative_model.py b/tests/test_generative_model.py index 62f91a8..5575853 100644 --- a/tests/test_generative_model.py +++ b/tests/test_generative_model.py @@ -73,6 +73,89 @@ def test_a_truncated_build_reports_the_future_window_bound() -> None: assert (wyner.lower, wyner.lower_source) == (0.0, "trivial lower bound") +def _fail_builds(monkeypatch, bidir_class: str = "explosion") -> None: + """Make every bidirectional build fail with ``bidir_class``.""" + from sofic.generators import bidirectional_build as bb + + failed = bb.BidirBuildResult(None, bb.BidirPreflightResult(bidir_class, reverse_max_states=10_000, error="test")) + monkeypatch.setattr(bb, "try_build_bidirectional", lambda forward, **kwargs: failed) + + +def _golden_mean_entropy() -> float: + return float(-(1 / 3) * np.log2(1 / 3) - (2 / 3) * np.log2(2 / 3)) + + +def test_an_exploding_build_is_bracketed_from_the_forward_machine(monkeypatch) -> None: + from sofic.generators.coupled_generators import CoupledGenerativeModel + + _fail_builds(monkeypatch) + monkeypatch.setattr(gs, "_future_window_bound", lambda forward, **kwargs: (0.5, "a bound", [{"stage": "a bound"}])) + result = generative_model(golden_mean(0.5), hmm_search=False, rng=np.random.default_rng(0)) + assert result.stages[0]["stage"] == "bidirectional build" + assert result.stages[0]["bidir_class"] == "explosion" + assert isinstance(result.model, CoupledGenerativeModel) + assert (result.lower, result.lower_source, result.lower_certified) == (0.5, "a bound", True) + assert result.upper_source == "epsilon machine" + assert result.upper == pytest.approx(_golden_mean_entropy(), abs=1e-12) + assert result.reproduction_error is not None and result.reproduction_error < 1e-12 + assert not result.certified + assert result.decomposition is None + assert result.structure is not None and result.structure["n_states"] == 2 + assert result.structure["weights"] == pytest.approx([2 / 3, 1 / 3]) + assert result.structure["lifted"] is None + skipped = [s["stage"] for s in result.stages if s.get("skipped") == "needs the reverse ε-machine"] + assert skipped == list(gs._REVERSE_STAGES) + assert result.stages[-1]["stage"] == "reliability summary" + + +def test_the_forward_only_bracket_keeps_to_its_budget(monkeypatch) -> None: + _fail_builds(monkeypatch) + start = time.monotonic() + result = generative_model(golden_mean(0.5), time_budget=4.0, rng=np.random.default_rng(0)) + assert time.monotonic() - start < 4.4 + window = max(s["value"] for s in result.stages if s["stage"].startswith("future-window")) + assert result.lower == window + assert result.lower <= result.upper <= _golden_mean_entropy() + 1e-6 + assert "belief-free HMM search" in {s["stage"] for s in result.stages} + + +def test_other_failed_builds_and_entry_points_still_raise(monkeypatch) -> None: + from sofic.exceptions import MixedStateExplosionError, StochasticValidationError + from sofic.generators.functional_generators import minimal_functional_generator + + _fail_builds(monkeypatch) + with pytest.raises(MixedStateExplosionError, match=r"failed \(explosion\)"): + gs.minimal_wyner_model(golden_mean(0.5)) + with pytest.raises(MixedStateExplosionError, match=r"failed \(explosion\)"): + minimal_functional_generator(golden_mean(0.5)) + _fail_builds(monkeypatch, "failed_build") + with pytest.raises(StochasticValidationError, match=r"failed \(failed_build\)"): + generative_model(golden_mean(0.5)) + + +def _exploding_forward(): + """n3-t059-d3 of the binary 3-state dataset; its reverse mixed-state presentation passes 1,000 states.""" + mats = { + 0: np.array([[0.6326610218842386, 0.0, 0.0], [0.6594864914964855, 0.0, 0.0], [0.0, 0.04355642859348044, 0.0]]), + 1: np.array([[0.0, 0.3673389781157614, 0.0], [0.0, 0.0, 0.34051350850351453], [0.0, 0.0, 0.9564435714065196]]), + } + return from_symbol_matrices((0, 1, 2), (0, 1), mats) + + +@pytest.mark.slow +def test_an_exploding_build_reports_the_future_window_bound() -> None: + start = time.monotonic() + result = generative_model( + _exploding_forward(), reverse_max_states=1000, use_ladder=False, time_budget=60.0, rng=np.random.default_rng(0) + ) + assert time.monotonic() - start < 66.0 + assert result.stages[0]["bidir_class"] == "explosion" + window = max(s["value"] for s in result.stages if s["stage"].startswith("future-window")) + # without a deadline the window bounds are 0.8828032 (L = 2) and 0.8827307 (L = 3); C_mu^+ is 1.0795992 + assert result.lower == window > 0.85 + assert result.lower < result.upper <= 1.0795992 + 1e-6 + + def test_generative_model_from_forward_epsilon_machine_certifies_golden_mean() -> None: forward = golden_mean(0.5) rng = np.random.default_rng(0)