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
35 changes: 35 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,41 @@ brute-force reference or a closed-form value and has a regression test.
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`.

### Time budgets kept

- With `time_budget`, `generative_model`'s first bidirectional build stops at half the budget. The mixed-state
enumeration, the ε-machine minimization and the bidirectional construction check a deadline (new `deadline`
keyword on `build_mixed_state_presentation`, `MealyHMM.mixed_state_presentation`, `EpsilonMachine.from_hmm`,
`infer_reverse_epsilon_machine` and `build_bidirectional_epsilon_machine`) and raise `MixedStateDeadlineError`, a
`MixedStateExplosionError`, so a stopped build is classed as an explosion with `budget_exhausted` set, and the
forward-only bracket gets the rest of the budget. The retry ladder skips the caps up to one that has exploded
(it built at 10,000 reverse states again) and forecasts from that build's time. On a binary 3-state process whose
default build is a truncation with 1,261 reverse states, the build took 46.6 s of a 60 s budget (16.4 s
minimizing, 23.3 s building the bidirectional machine) and `generative_model` 72 to 78 s; it now takes 60.0 s and
returns [0.8827307, 1.0795992].
- The cryptic orders and the block persistent crypticities take a deadline (`cryptic_order`,
`cryptic_order_from_graph` and `power_automaton` raise `TimeoutError` past it); the pipeline gives them a tenth
of the time left, past which the cryptic orders are unknown.
- Once the budget is spent only the ε-machine is offered among the candidate machines; it always generates the
process, so the bracket keeps an upper bound.
- `separating_optima` checks its deadline before every start after the first, whether or not a start has
succeeded, and inside its SLSQP objective, so a start in progress stops at it; the first start still runs to
the end. It checked only before a start, once some start had found an exact decomposition.
- With a budget, simplex chains whose entropy is not below the forward ε-machine's are no longer offered (nor
passed on as coupled-search seeds). On the process above, lifting a 78-state reverse chain with the reverse
ε-machine's entropy took 23 s past the stage's deadline.
- The dit fallbacks of the exact stage and the dit run of the lifted channel stage stop at their deadlines (their
objective raises `TimeoutError`). Once the earlier stages kept to their shares, `minimal_wyner_model` on a 2-state
ternary truncation with a 20 s budget ran over 30 minutes in dit's Wyner basin hopping.
- With a budget, a bracket still open after the searches gets a second future-window pass with the time left:
after the HMM search on an exploding build, and on a truncated build in the fifth of the budget the searches now
leave. The branch and bound of the window length with the larger bound resumes from its open boxes for ten
times as many, so the bound only rises; resumed, it branches exactly as one longer search would.
- On six binary 3-state processes whose reverse machines explode at 1,000 states, at 300 s with the default caps
and with 1,000 reverse states, every run now ends by 310 s (up to 800 s before) and no bound is worse. One of
them certifies in both settings, in 97 s and 91 s, and nine lower bounds rise, seven through the second window
pass.

### 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
3 changes: 3 additions & 0 deletions docs/core/exceptions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Exceptions
* :class:`NonDeterministicError` — DFA determinism violated
* :class:`StochasticValidationError` — invalid probability masses
* :class:`MixedStateExplosionError` — mixed-state presentation did not close
* :class:`MixedStateDeadlineError` — mixed-state presentation did not close by its deadline (a
:class:`MixedStateExplosionError`)
* :class:`UnifilarityError` — unifilarity invariant violated
* :class:`QuasiStochasticValidationError` — quasi-stochastic invariant violated

Expand Down Expand Up @@ -44,5 +46,6 @@ API
.. autoclass:: NonDeterministicError
.. autoclass:: StochasticValidationError
.. autoclass:: MixedStateExplosionError
.. autoclass:: MixedStateDeadlineError
.. autoclass:: UnifilarityError
.. autoclass:: QuasiStochasticValidationError
41 changes: 28 additions & 13 deletions docs/generators/generative_models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -243,14 +243,24 @@ drawing its states independently at both ends of each bidirectional edge also ge
coupled generators such as the interleaved product flag do not.

With ``time_budget`` every stage gets a share of the time left and stops at its deadline; the stages from
the simplex-chain search on, except the final generator heaviest-term bound, stop a fifth of the budget
early, so that this bound keeps that time, and the stages before them share the whole budget. The universal
coupled search (:func:`~sofic.generators.universal_optimizer.universal_generative_optimizer`) builds no seeds
and tries no larger :math:`k` once its deadline passes; inside it, the coupled search stops every start but the
ε-machine seed at the deadline, and that seed runs to the end so that some generator can be verified. The
lifted channel stage begins no start, dit run or refinement after its deadline, and the targeted line-split
search stops its running local search there and polishes only the best decomposition it has. Those polishes,
the ε-machine seed, an optimizer iteration or a linear program can still carry a run past its budget.
the simplex-chain search on, except the final generator heaviest-term bound (on a truncated build, the second
future-window pass below), stop a fifth of the budget early, so that this bound keeps that time, and the
stages before them share the whole budget. The bidirectional build counts against the budget. The first
build stops at half of it, checked in the mixed-state enumeration, the ε-machine minimization and the
bidirectional construction; a build stopped there counts as an explosion, so the forward-only bracket below
gets the rest. The retry ladder skips the caps up to one that has exploded and stops at the end of the
budget. The persistent criteria (the cryptic orders and the block persistent crypticities) get a tenth of
the time left, past which the cryptic orders are unknown. Of the candidate machines the ε-machine is always
offered, so the bracket keeps an upper bound at any budget, and the other four only while time is left;
simplex chains no lighter than the ε-machine are not offered. The exact common information search (:func:`~sofic.generators.coupled_generators.separating_optima`) runs its
first start to the end; no later start begins after its deadline, and one in progress stops at it. The
universal coupled search (:func:`~sofic.generators.universal_optimizer.universal_generative_optimizer`)
builds no seeds and tries no larger :math:`k` once its deadline passes; inside it, the coupled search stops
every start but the ε-machine seed at the deadline, and that seed runs to the end so that some generator can
be verified. The lifted channel stage begins no start or refinement after its deadline, and its dit run stops
there, as do the dit fallbacks of the exact stage; the targeted line-split search stops its running local
search there and polishes only the best decomposition it has. Those polishes, the ε-machine seed, the first
exact start, an optimizer iteration or a linear program can still carry a run past its budget.

The coupled searches parameterize states by their causal-state beliefs :math:`(Q_w, R_w)`, which favours
generators whose states' pasts and futures are belief-mixtures of the causal states'. Some processes have
Expand Down Expand Up @@ -447,16 +457,21 @@ mixed states merge within numerical tolerance, and the build is a finite truncat
are verified against the forward machine's words, so the upper bound holds for the process, but the excess
entropy, the support-type, flow and coverage bounds, SCIP's dual bound on the exact path, the heaviest-term
bounds and the restricted global bound would bound the truncation, not the process.
:func:`~sofic.generators.generative_search.generative_model` therefore skips them, and keeps no budget for
the final heaviest-term bound. Its lower bound is the larger future-window generator coverage bound at
:func:`~sofic.generators.generative_search.generative_model` therefore skips them, including the final
heaviest-term bound. Its lower bound is the larger future-window generator coverage bound at
: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`.
:math:`L = 3`), computed first, with at most 30% of the time budget :cite:`LohrAy2009`. With a budget the
searches stop a fifth of it early, and when the bracket is still open the time left goes to a second pass:
the branch and bound of the window length with the larger bound resumes from its open boxes, for ten times
as many, so the bound only rises.
:func:`~sofic.generators.generative_search.minimal_wyner_model` reports ``lower`` 0 on a truncated build.

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
ladder), or with a budget the first build does not finish within half of it,
: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
budget :cite:`LohrAy2009`, and the same second pass on the time the HMM search leaves when the bracket is
still open. 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
Expand Down
3 changes: 2 additions & 1 deletion docs/generators/mixed_state_presentation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ mixed-state presentation used for nonunifilar hidden processes and
time-symmetric computational mechanics :cite:`Ellison2009`.

This constructor enumerates beliefs and raises ``MixedStateExplosionError``
if they do not close within the state cap. Numeric equality tolerances are
if they do not close within the state cap, or ``MixedStateDeadlineError`` (an
explosion too) if they do not close by its ``deadline``. Numeric equality tolerances are
not approximation-error budgets. For an opt-in finite approximation of a
known positive-transition Moore HMM, see :doc:`quantized_filter`
:cite:`feng2026recursive`.
Expand Down
9 changes: 9 additions & 0 deletions sofic/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ class MixedStateExplosionError(StochasticValidationError):
"""


class MixedStateDeadlineError(MixedStateExplosionError):
"""Raised when a mixed-state presentation, or an ε-machine or bidirectional machine built from one, reaches
its ``deadline`` before it is finished.

Callers that handle :class:`MixedStateExplosionError` treat it as an explosion: the construction did
not finish within the time it was given.
"""


class UnifilarityError(SoficValidationError):
"""Raised when a unifilarity invariant is violated."""

Expand Down
67 changes: 49 additions & 18 deletions sofic/generators/bidirectional_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
When the reverse mixed-state presentation does not close at the default cap,
``build_bidirectional_with_ladder`` raises ``max_states`` until the edge tensor
``Pe`` of :class:`~sofic.generators.coupled_generators._GeneratorProblem` stabilizes.
With a time budget every build has a deadline, checked in the mixed-state enumeration and in the ε-machine and
bidirectional constructions built on it.
"""

from __future__ import annotations
Expand All @@ -13,7 +15,7 @@

import numpy as np

from sofic.exceptions import MixedStateExplosionError, StochasticValidationError
from sofic.exceptions import MixedStateDeadlineError, MixedStateExplosionError, StochasticValidationError
from sofic.generators.bidirectional_construction import (
build_bidirectional_epsilon_machine,
infer_reverse_epsilon_machine,
Expand All @@ -28,13 +30,17 @@

@dataclass(frozen=True)
class BidirPreflightResult:
"""Classification before or after attempting a bidirectional build."""
"""Classification before or after attempting a bidirectional build.

``deadline_reached`` marks an ``"explosion"`` that is a build stopped at its deadline, not at its cap.
"""

bidir_class: BidirClass
reverse_max_states: int | None = None
reverse_recurrence_finite: bool | None = None
reverse_twins_finite: bool | None = None
error: str | None = None
deadline_reached: bool = False


@dataclass(frozen=True)
Expand Down Expand Up @@ -67,21 +73,23 @@ def preflight_bidir(forward: EpsilonMachine, *, reverse_max_states: int = 10_000


def _preflight(
forward: EpsilonMachine, reverse_max_states: int
forward: EpsilonMachine, reverse_max_states: int, deadline: float | None = None
) -> tuple[BidirPreflightResult, BidirectionalEpsilonMachine | None]:
""":func:`preflight_bidir` plus the bidirectional machine it built (``None`` unless it built)."""
""":func:`preflight_bidir` plus the bidirectional machine it built (``None`` unless it built). The build stops
at ``deadline`` (a :func:`time.monotonic` value), which counts as an explosion."""
twins = forward.reverse_is_finite()
recurrence = forward.reverse_epsilon_machine_is_finite()
try:
reverse = infer_reverse_epsilon_machine(forward, max_states=reverse_max_states)
bidir = build_bidirectional_epsilon_machine(forward, reverse)
reverse = infer_reverse_epsilon_machine(forward, max_states=reverse_max_states, deadline=deadline)
bidir = build_bidirectional_epsilon_machine(forward, reverse, deadline=deadline)
except MixedStateExplosionError as exc:
return BidirPreflightResult(
"explosion",
reverse_max_states=reverse_max_states,
reverse_recurrence_finite=recurrence,
reverse_twins_finite=twins,
error=str(exc)[:300],
deadline_reached=isinstance(exc, MixedStateDeadlineError),
), None
except (StochasticValidationError, ValueError) as exc:
return BidirPreflightResult(
Expand Down Expand Up @@ -113,32 +121,43 @@ def build_bidirectional_with_ladder(
edge_tol: float = 1e-8,
time_budget: float | None = None,
max_reverse_states: int | None = None,
exploded: tuple[BidirPreflightResult, float] | None = None,
) -> BidirBuildResult:
"""Build a bidirectional machine, increasing reverse ``max_states`` until ``Pe`` stabilizes.

With ``time_budget`` (seconds) the ladder stops before a cap whose forecast cost would overrun
the budget, and ``budget_exhausted`` is set on the result. A single mixed-state construction
cannot be interrupted, so the forecast scales the previous cap's time by the square of the cap
ratio (construction time grows faster than linearly in the cap); the first cap always runs.
A build whose reverse machine has more than ``max_reverse_states`` states is classified as an
explosion: such truncated machines are far too large for any generator search.
the budget, and ``budget_exhausted`` is set on the result. The forecast scales the previous cap's
time by the square of the cap ratio (construction time grows faster than linearly in the cap), and
every build stops at the end of the budget, which ends the ladder. A build whose reverse machine has
more than ``max_reverse_states`` states is classified as an explosion: such truncated machines are far
too large for any generator search.
``exploded`` is ``(preflight, seconds)`` of a build that already exploded: caps at or below its cap are
not tried again, its time is the first forecast's, and its preflight is returned if no cap runs.
"""
start = time.monotonic()
end = None if time_budget is None else start + time_budget
last_pe: np.ndarray | None = None
last_bidir: BidirectionalEpsilonMachine | None = None
last_preflight: BidirPreflightResult | None = None
previous: tuple[int, float] | None = None
last_preflight: BidirPreflightResult | None = None if exploded is None else exploded[0]
ceiling = None if exploded is None else exploded[0].reverse_max_states
previous = None if exploded is None or ceiling is None else (ceiling, exploded[1])
exhausted = False

for cap in caps:
if ceiling is not None and cap <= ceiling:
continue
if time_budget is not None and previous is not None:
prev_cap, prev_seconds = previous
forecast = prev_seconds * (cap / prev_cap) ** 2
if time.monotonic() - start + forecast > time_budget:
exhausted = True
break
attempt = time.monotonic()
pre, bidir = _preflight(forward, cap)
pre, bidir = _preflight(forward, cap, deadline=end)
if pre.deadline_reached:
last_preflight = last_preflight if last_bidir is not None else pre
exhausted = True
break
if bidir is not None and max_reverse_states is not None:
size = len(list(bidir.reverse_machine.states()))
if size > max_reverse_states:
Expand All @@ -147,6 +166,7 @@ def build_bidirectional_with_ladder(
last_preflight = pre
if bidir is None:
previous = (cap, time.monotonic() - attempt)
ceiling = cap if ceiling is None else max(ceiling, cap)
continue
pe = _edge_tensor(bidir)
previous = (cap, time.monotonic() - attempt)
Expand Down Expand Up @@ -190,14 +210,25 @@ def try_build_bidirectional(
"""Single-cap build, or ladder when ``use_ladder`` and the default cap explodes.

``time_budget`` (seconds, including the first preflight) and ``max_reverse_states`` are passed on
to :func:`build_bidirectional_with_ladder`.
to :func:`build_bidirectional_with_ladder`, which skips the caps up to ``reverse_max_states``. With a
budget the first build stops at half of it; a build stopped there counts as an explosion with
``budget_exhausted`` set and gets no ladder, so the caller keeps the rest of the budget.
"""
start = time.monotonic()
pre, bidir = _preflight(forward, reverse_max_states)
first = None if time_budget is None else start + 0.5 * time_budget
pre, bidir = _preflight(forward, reverse_max_states, deadline=first)
if pre.deadline_reached:
return BidirBuildResult(None, pre, budget_exhausted=True)
if pre.bidir_class == "explosion" and use_ladder:
remaining = None if time_budget is None else max(0.0, time_budget - (time.monotonic() - start))
elapsed = time.monotonic() - start
remaining = None if time_budget is None else max(0.0, time_budget - elapsed)
return build_bidirectional_with_ladder(
forward, caps=caps, edge_tol=edge_tol, time_budget=remaining, max_reverse_states=max_reverse_states
forward,
caps=caps,
edge_tol=edge_tol,
time_budget=remaining,
max_reverse_states=max_reverse_states,
exploded=(pre, elapsed),
)
if bidir is None:
return BidirBuildResult(None, pre)
Expand Down
Loading
Loading