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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion docs/generators/generative_models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
---------------------------------
Expand Down
188 changes: 179 additions & 9 deletions sofic/generators/generative_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
*,
Expand All @@ -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

Expand All @@ -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


Expand Down Expand Up @@ -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])
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading