From 74686c77b58149304cb7f42141d2ab94b20d47bd Mon Sep 17 00:00:00 2001 From: Ryan James Date: Tue, 24 Nov 2026 13:56:18 -0700 Subject: [PATCH 1/2] Keep generative_model inside its budget - hmm_generator_search checks its deadline after every L-BFGS-B iteration (StopIteration from the optimizer callback; SciPy >= 1.11), so one start no longer runs far past it (19 s past a 0.5 s deadline at k = 6 before). - Sparse word distributions extend only prefixes with nonzero mass, and the reproduction check uses them: on the butterfly process the check ran about 1900 s of a 60 s budget; generative_model now certifies C_g = log2 5 in ~4 s. - generative_model skips the coverage stages once the cheaper lower bounds meet an epsilon-machine's entropy, and at cryptic order <= 1 runs the generator coverage bound only when the exact path leaves the bracket open (on 233 dataset processes of that class it took ~17 s each and never supplied the lower bound). --- CHANGELOG.md | 13 ++++++ docs/generators/generative_models.rst | 9 +++- pyproject.toml | 2 +- sofic/generators/generative_search.py | 43 +++++++++++++++----- sofic/generators/hmm_search.py | 26 ++++++++++-- sofic/generators/minimal_generative_model.py | 4 +- sofic/generators/words.py | 11 ++--- tests/test_generative_model.py | 28 +++++++++++++ tests/test_hmm_search.py | 9 ++++ tests/test_words.py | 43 ++++++++++++++++++++ uv.lock | 2 +- 11 files changed, 163 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6370840..ceba935 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -236,6 +236,19 @@ brute-force reference or a closed-form value and has a regression test. - The line-split seeds' ALM polish (`_optimize`, `_optimize_coupled`) stops at the pipeline deadline and returns its last finished step; one polish had run more than 10 minutes past the budget on a 144-pair joint. +- `hmm_generator_search` checks its `deadline` after every L-BFGS-B iteration, not only between starts and + rounds, so a run stops within one iteration of it (an end point cut short is kept if it is feasible). One + uninterrupted start at `k = 6` on a 3-state binary process ran 19 s past a 0.5 s deadline. The stop is a + `StopIteration` raised in the optimizer callback, which needs SciPy 1.11, now the minimum. +- Sparse word distributions (`word_probabilities`, the default) extend only prefixes of positive probability, + so their cost follows the number of allowed words instead of `|X|^L`, and `generative_model`'s reproduction + check uses them. On the butterfly process (8 symbols, 1088 allowed words of length 8) the check ran about + 1900 s of a 60 s budget; `generative_model(butterfly_process(), time_budget=60)` now certifies + `C_g = log2 5` in about 4 s. +- `generative_model` skips both coverage stages once the cheaper lower bounds meet the entropy of an + ε-machine, which then certifies, and at cryptic order at most 1 runs the generator coverage bound only when + the exact path leaves the bracket open. On 233 dataset processes of cryptic order at most 1 the generator + coverage bound took about 17 s each, 96% of the pipeline's time, and never supplied the lower bound. ### Support-type bound speed diff --git a/docs/generators/generative_models.rst b/docs/generators/generative_models.rst index c96fab9..9b22555 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -245,7 +245,8 @@ generators whose states' pasts and futures are belief-mixtures of the causal sta lower-entropy generators that are not. :func:`~sofic.generators.hmm_search.hmm_generator_search` optimizes the symbol matrices of a :math:`k`-state HMM directly, minimizing :math:`H[\pi]` subject to exact word probabilities up to length :math:`k + |S^+|`, which implies equality on all words :cite:`Tzeng1992`. It uses an -augmented Lagrangian with analytic gradients: first feasibility from a random start, then entropy descent. Direct +augmented Lagrangian with analytic gradients: first feasibility from a random start, then entropy descent. Its +``deadline`` is checked after every L-BFGS-B iteration, so a run stops within one iteration of it. Direct parameter search for minimal generators of binary Markov processes is the approach of :cite:`Ruebeck2018`. The pipeline runs it after the coupled search (``hmm_search=True``) for :math:`k = |S^+|, \ldots, |S^+| + 2` with half the remaining budget, or for two values of :math:`k` and two starts without a budget, and offers the @@ -308,7 +309,11 @@ consistency for the group moments, and branching over boxes of the explicit stat beliefs with McCormick envelopes :cite:`mccormick1976computability`. Coverage with these caps (:func:`~sofic.generators.generator_caps.generator_coverage_bound`, the ``generator_caps`` stage of the pipeline) exceeds :math:`\op{G}{S^+ : S^-}` on most -survey processes with positive persistent crypticity. +survey processes with positive persistent crypticity. The pipeline skips both coverage stages once the +cheaper bounds meet the entropy of an ε-machine, which then certifies. At cryptic order at most 1, where +:math:`C_g = \op{G}{S^+ : S^-}` and the exact path usually closes the bracket, the generator coverage bound +runs only if the exact path leaves it open; on 233 dataset processes of that class it had taken about 17 s +each and never supplied the lower bound. 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 diff --git a/pyproject.toml b/pyproject.toml index acf1e4b..f18f920 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,7 +31,7 @@ dependencies = [ "networkx>=2.6", "numpy>=1.22", "pyyaml>=6.0", - "scipy>=1.7", + "scipy>=1.11", ] [project.urls] diff --git a/sofic/generators/generative_search.py b/sofic/generators/generative_search.py index f8f5a35..6cfa64a 100644 --- a/sofic/generators/generative_search.py +++ b/sofic/generators/generative_search.py @@ -10,7 +10,9 @@ the certified coverage bound (:mod:`~sofic.generators.coverage_bound`), the informative one on full supports, where the support-type bound vanishes; and coverage with caps on the heaviest generator states from the generator equations (:mod:`~sofic.generators.generator_caps`, - ``generator_caps`` explicit states), which can exceed :math:`\op{G}{S^+ : S^-}`. + ``generator_caps`` explicit states), which can exceed :math:`\op{G}{S^+ : S^-}`. Both coverage stages are + skipped once the cheaper bounds meet the smaller ε-machine entropy, and at cryptic order at most 1 the + generator coverage bound waits for the exact path and runs only if that leaves the bracket open. 2. *Persistent crypticity.* Logs the cryptic orders :math:`\kappa^\pm` and the persistent crypticities of the block processes, :math:`\H{S^+_L \mid X_{0:}}` and :math:`\H{S^-_0 \mid X_{:L}}`, which vanish exactly from :math:`L = \kappa`. When both :math:`p.\chi^\pm` vanish on the bidirectional edge (cryptic order at most 1), @@ -565,7 +567,27 @@ def share(fraction: float) -> float | None: lower, lower_source = fb.value, f"flow bound {thresholds}" lower_certified = fb.certified - if not wyner and coverage in ("heuristic", "certified") and not out_of_time("coverage bound"): + # Both ε-machines generate the process, so once the lower bound meets the smaller of their entropies the + # machines stage certifies and the coverage stages cannot help. + settled = not wyner and lower >= min(_entropy(problem.p_plus), _entropy(problem.p_minus)) - _CERT_TOL + if settled: + log.append({"stage": "coverage bounds", "skipped": "the lower bound meets an ε-machine's entropy"}) + f_crit, r_crit = _persistent_criteria(problem) + theorem = f_crit < 1e-10 and r_crit < 1e-10 + + def generator_coverage() -> None: + nonlocal lower, lower_source, lower_certified + from sofic.generators.generator_caps import generator_coverage_bound + + gen = generator_coverage_bound(problem, k_max=coverage_k_max, explicit=generator_caps, deadline=share(0.3)) + log.append({"stage": "generator coverage bound (certified)", "value": gen.value, "caps": gen.caps}) + if gen.value > lower + 1e-9: + lower, lower_source, lower_certified = gen.value, "generator coverage bound (certified)", True + + # With p.chi+- = 0 the exact path below usually certifies C_g = G, so the generator coverage bound runs after it. + want_generator_coverage = not wyner and coverage == "certified" and generator_caps > 0 and not settled + + if not settled and not wyner and coverage in ("heuristic", "certified") and not out_of_time("coverage bound"): try: use_certified = coverage == "certified" cov, meta, caps_ok = _coverage_lower_bound( @@ -589,16 +611,9 @@ def share(fraction: float) -> float | None: except Exception as exc: # pragma: no cover - defensive log.append({"stage": "coverage bound", "error": str(exc)}) - if not wyner and coverage == "certified" and generator_caps > 0 and not out_of_time("generator coverage bound"): - from sofic.generators.generator_caps import generator_coverage_bound + if want_generator_coverage and not theorem and not out_of_time("generator coverage bound"): + generator_coverage() - gen = generator_coverage_bound(problem, k_max=coverage_k_max, explicit=generator_caps, deadline=share(0.3)) - log.append({"stage": "generator coverage bound (certified)", "value": gen.value, "caps": gen.caps}) - if gen.value > lower + 1e-9: - lower, lower_source, lower_certified = gen.value, "generator coverage bound (certified)", True - - f_crit, r_crit = _persistent_criteria(problem) - theorem = f_crit < 1e-10 and r_crit < 1e-10 kappa = _cryptic_orders(bidir) log.append( { @@ -694,6 +709,12 @@ def maybe_return_early() -> GenerativeModelResult | None: if early is not None and early.certified: return _finalize_result(early) + if want_generator_coverage and theorem and not out_of_time("generator coverage bound"): + generator_coverage() + early = maybe_return_early() + if early is not None and early.certified: + return _finalize_result(early) + kappa_plus = kappa[0] if kappa is not None else math.inf if ( not wyner diff --git a/sofic/generators/hmm_search.py b/sofic/generators/hmm_search.py index 084db00..7271804 100644 --- a/sofic/generators/hmm_search.py +++ b/sofic/generators/hmm_search.py @@ -142,6 +142,16 @@ def _objective(theta, k, ns, tree, target, lam, mu, weight): return value, grad.ravel() +def _stop_at(deadline: float): + """An optimizer callback that ends the run (``StopIteration``) once :func:`time.monotonic` passes ``deadline``.""" + + def callback(intermediate_result: Any) -> None: + if time.monotonic() >= deadline: + raise StopIteration + + return callback + + def hmm_generator_search( machine: Any, k: int, @@ -163,7 +173,8 @@ def hmm_generator_search( moves to a nearby generator instead of descending (from a near-generator, the descent stalls at an infeasible point). A result's ``start`` counts the initial starts first. Only end points whose largest word residual is at most ``feasibility_tol`` are returned; callers should still verify them exactly (the pipeline does). - ``deadline`` is a :func:`time.monotonic` value checked between starts and rounds. + ``deadline`` is a :func:`time.monotonic` value checked between starts and rounds and after every L-BFGS-B + iteration, so a run stops within one iteration of it; an end point cut short is kept if it is feasible. """ from sofic.generators.matrices import symbol_matrices @@ -174,6 +185,7 @@ def hmm_generator_search( tree = _WordTree(ns, k + n) target = _target_words(machine, tree) opts = {"maxiter": 3000, "ftol": 1e-16, "gtol": 1e-12} + stop = None if deadline is None else _stop_at(deadline) out = [] for start in range(len(given) + starts): if deadline is not None and time.monotonic() >= deadline: @@ -182,13 +194,21 @@ def hmm_generator_search( weight = 0.0 if start < len(given) else 1.0 lam = np.zeros(len(target)) args = (k, ns, tree, target) - theta = minimize(_objective, theta, args=(*args, lam, 10.0, 0.0), jac=True, method="L-BFGS-B", options=opts).x + theta = minimize( + _objective, theta, args=(*args, lam, 10.0, 0.0), jac=True, method="L-BFGS-B", options=opts, callback=stop + ).x mu = 1e3 for _ in range(rounds): if deadline is not None and time.monotonic() >= deadline: break theta = minimize( - _objective, theta, args=(*args, lam, mu, weight), jac=True, method="L-BFGS-B", options=opts + _objective, + theta, + args=(*args, lam, mu, weight), + jac=True, + method="L-BFGS-B", + options=opts, + callback=stop, ).x T, _ = _unpack(theta, k, ns) pi = _stationary(sum(T)) diff --git a/sofic/generators/minimal_generative_model.py b/sofic/generators/minimal_generative_model.py index 481a90b..8998722 100644 --- a/sofic/generators/minimal_generative_model.py +++ b/sofic/generators/minimal_generative_model.py @@ -898,8 +898,8 @@ def _reproduction_error(model: Any, reference: Any, *, max_length: int) -> float """ error = 0.0 for length in range(max_length + 1): - model_words = model.word_probabilities(length, sparse=False) - reference_words = reference.word_probabilities(length, sparse=False) + model_words = model.word_probabilities(length) + reference_words = reference.word_probabilities(length) for word in set(model_words) | set(reference_words): error = max(error, abs(model_words.get(word, 0.0) - reference_words.get(word, 0.0))) return max(error, _equivalence_error(model, reference)) diff --git a/sofic/generators/words.py b/sofic/generators/words.py index 4e0f14b..a0c3067 100644 --- a/sofic/generators/words.py +++ b/sofic/generators/words.py @@ -151,15 +151,12 @@ def _hmm_word_probabilities( mealy = hmm.to_mealy() alphabet = sorted(mealy.observation_alphabet, key=repr) + mass = np.asarray(start_vector(mealy, start), dtype=float) + step = _matrix_step(symbol_matrices(mealy), len(mass), prune=sparse) distribution: dict[tuple[Any, ...], float] = {} for length in requested: - if length == 0: - probability = _hmm_word_probability(mealy, (), start=start) - if not sparse or abs(probability) > _TOL: - distribution[()] = probability - continue - for word, _ in _enumerate_words(alphabet, length): - probability = _hmm_word_probability(mealy, word, start=start) + for word, prefix_mass in _enumerate_words(alphabet, length, mass, step): + probability = float(prefix_mass.sum()) if not sparse or abs(probability) > _TOL: distribution[word] = probability return distribution diff --git a/tests/test_generative_model.py b/tests/test_generative_model.py index 9c9d739..4d237b3 100644 --- a/tests/test_generative_model.py +++ b/tests/test_generative_model.py @@ -166,6 +166,34 @@ def test_unlimited_budget_is_not_reported_as_exhausted() -> None: assert not result.budget_exhausted +def test_settled_bracket_skips_the_coverage_stages() -> None: + import time + + from sofic.examples.epsilon_machines import butterfly_process + + start = time.monotonic() + result = generative_model(butterfly_process(), time_budget=60.0, rng=np.random.default_rng(0)) + assert time.monotonic() - start < 60.0 # took about 1900 s when words were enumerated over all 8**8 + stages = {s["stage"]: s for s in result.stages} + assert result.certified and result.upper == pytest.approx(np.log2(5), abs=1e-9) + assert stages["coverage bounds"]["skipped"] == "the lower bound meets an ε-machine's entropy" + assert "generator coverage bound (certified)" not in stages + + +def test_generator_coverage_waits_for_the_exact_path_in_the_theorem_class() -> None: + from sofic.examples.epsilon_machines import from_symbol_matrices + from sofic.generators.epsilon_machine import EpsilonMachine + from tests.test_separating_generators import SCIP_KAPPA_1, SCIP_KAPPA_1_G + + m = from_symbol_matrices((0, 1), (0, 1), {x: np.array(M) for x, M in SCIP_KAPPA_1.items()}) + machine = m if isinstance(m, EpsilonMachine) else EpsilonMachine.from_hmm(m) + result = generative_model(machine, time_budget=60.0, rng=np.random.default_rng(0)) + names = [s["stage"] for s in result.stages] + assert result.persistent_crypticity_theorem_applies and result.certified + assert result.upper == pytest.approx(SCIP_KAPPA_1_G, abs=1e-7) + assert "exact path" in names and "generator coverage bound (certified)" not in names + + def test_dit_fallbacks_are_skipped_on_large_joints(monkeypatch) -> None: import sofic.generators.generative_search as gs import sofic.generators.lifted_common_information as lci diff --git a/tests/test_hmm_search.py b/tests/test_hmm_search.py index f5c1e0d..443bab2 100644 --- a/tests/test_hmm_search.py +++ b/tests/test_hmm_search.py @@ -98,6 +98,15 @@ def test_initial_start_recovers_a_perturbed_generator() -> None: hs.hmm_generator_search(forward, 3, starts=0, initial=[T]) +def test_deadline_stops_inside_an_optimizer_run() -> None: + import time + + forward = _dataset_n3_t122_d2() + start = time.monotonic() + hs.hmm_generator_search(forward, 6, starts=1, rng=np.random.default_rng(0), deadline=start + 0.5) + assert time.monotonic() - start < 5.0 # one uninterrupted L-BFGS-B run at k = 6 takes far longer + + @pytest.mark.slow def test_search_beats_the_epsilon_machine_on_n3_t122_d2() -> None: forward = _dataset_n3_t122_d2() diff --git a/tests/test_words.py b/tests/test_words.py index 40b0193..7599411 100644 --- a/tests/test_words.py +++ b/tests/test_words.py @@ -1,6 +1,8 @@ """Tests for finite-word distributions.""" import pytest +from hypothesis import given, settings +from hypothesis import strategies as st from sofic.examples import bernoulli, golden_mean from sofic.generators.markov import MarkovChain @@ -87,6 +89,47 @@ def test_hmm_word_probability_helpers(): } +@settings(max_examples=25, deadline=None) +@given(st.integers(0, 2**31 - 1), st.integers(0, 4), st.booleans()) +def test_word_probabilities_agree_with_word_probability(seed, length, from_state): + import numpy as np + + from sofic.generators.mealy import MealyHMM + + rng = np.random.default_rng(seed) + k, symbols = 3, ("a", "b", "c") + hmm = MealyHMM( + initial_distribution=dict(enumerate(rng.dirichlet(np.ones(k)))), observation_alphabet=frozenset(symbols) + ) + for w in range(k): + hmm.graph.add_state(w) + for w in range(k): + mask = rng.random((len(symbols), k)) < 0.4 + mask[rng.integers(len(symbols)), rng.integers(k)] = True + weights = np.where(mask, rng.random(mask.shape), 0.0) + weights /= weights.sum() + for (xi, v), p in np.ndenumerate(weights): + if p > 0: + hmm.graph.add_transition(w, v, **{ATTR_PROB: float(p), ATTR_EMISSION: symbols[xi]}) + start = 0 if from_state else None + dense = hmm.word_probabilities(length, start=start, sparse=False) + assert len(dense) == len(symbols) ** length + for word, p in dense.items(): + assert p == pytest.approx(hmm.word_probability(word, start=start), abs=1e-15) + assert hmm.word_probabilities(length, start=start) == {w: p for w, p in dense.items() if abs(p) > 1e-15} + + +def test_sparse_word_probabilities_prune_forbidden_prefixes(): + import time + + from sofic.examples.epsilon_machines import butterfly_process + + start = time.monotonic() + words = butterfly_process().word_probabilities(8) + assert time.monotonic() - start < 10.0 # 8**8 words over the alphabet, 1088 of them allowed + assert len(words) == 1088 and sum(words.values()) == pytest.approx(1.0) + + def test_hmm_word_probability_rejects_zero_condition(): with pytest.raises(ZeroDivisionError): _mealy_like_pfa().to_mealy().conditional_word_probability(("0",), ("missing",)) diff --git a/uv.lock b/uv.lock index 46e1ce1..f04b5d0 100644 --- a/uv.lock +++ b/uv.lock @@ -2638,7 +2638,7 @@ requires-dist = [ { name = "python-sat", marker = "extra == 'sat'", specifier = ">=1.8" }, { name = "pyyaml", specifier = ">=6.0" }, { name = "ruff", marker = "extra == 'dev'" }, - { name = "scipy", specifier = ">=1.7" }, + { name = "scipy", specifier = ">=1.11" }, { name = "sphinx", marker = "extra == 'dev'" }, { name = "sphinx", marker = "extra == 'docs'" }, { name = "sphinx-rtd-theme", marker = "extra == 'dev'" }, From 3e3f11b1f49524a7a9ab0dbef3d26b1f9b41d617 Mon Sep 17 00:00:00 2001 From: Ryan James Date: Tue, 24 Nov 2026 14:25:05 -0700 Subject: [PATCH 2/2] Use the full kappa <= 1 run in the budget notes The coverage-stage figures came from the first 233 processes; the full run covers 510, with the same share of time, and the branch takes 2.6 minutes on it instead of 2.5 hours. --- CHANGELOG.md | 5 +++-- docs/generators/generative_models.rst | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ceba935..10757c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -247,8 +247,9 @@ brute-force reference or a closed-form value and has a regression test. `C_g = log2 5` in about 4 s. - `generative_model` skips both coverage stages once the cheaper lower bounds meet the entropy of an ε-machine, which then certifies, and at cryptic order at most 1 runs the generator coverage bound only when - the exact path leaves the bracket open. On 233 dataset processes of cryptic order at most 1 the generator - coverage bound took about 17 s each, 96% of the pipeline's time, and never supplied the lower bound. + the exact path leaves the bracket open. On the 510 dataset processes of cryptic order at most 1 the + generator coverage bound took about 17 s each, 96% of the pipeline's time, and never supplied the lower + bound; with these changes the 510 runs take 2.6 minutes instead of 2.5 hours, with the same brackets. ### Support-type bound speed diff --git a/docs/generators/generative_models.rst b/docs/generators/generative_models.rst index 9b22555..4c83aa4 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -312,8 +312,8 @@ caps (:func:`~sofic.generators.generator_caps.generator_coverage_bound`, the survey processes with positive persistent crypticity. The pipeline skips both coverage stages once the cheaper bounds meet the entropy of an ε-machine, which then certifies. At cryptic order at most 1, where :math:`C_g = \op{G}{S^+ : S^-}` and the exact path usually closes the bracket, the generator coverage bound -runs only if the exact path leaves it open; on 233 dataset processes of that class it had taken about 17 s -each and never supplied the lower bound. +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. 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