Skip to content
Merged
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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,20 @@ 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 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

Expand Down
9 changes: 7 additions & 2 deletions docs/generators/generative_models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ dependencies = [
"networkx>=2.6",
"numpy>=1.22",
"pyyaml>=6.0",
"scipy>=1.7",
"scipy>=1.11",
]

[project.urls]
Expand Down
43 changes: 32 additions & 11 deletions sofic/generators/generative_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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(
Expand All @@ -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(
{
Expand Down Expand Up @@ -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
Expand Down
26 changes: 23 additions & 3 deletions sofic/generators/hmm_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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

Expand All @@ -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:
Expand All @@ -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))
Expand Down
4 changes: 2 additions & 2 deletions sofic/generators/minimal_generative_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
11 changes: 4 additions & 7 deletions sofic/generators/words.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 28 additions & 0 deletions tests/test_generative_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions tests/test_hmm_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
43 changes: 43 additions & 0 deletions tests/test_words.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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",))
Expand Down
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading