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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@
A second correctness review: every fix below was reproduced against a
brute-force reference or a closed-form value and has a regression test.

### Belief-free generator search

- New `sofic.generators.hmm_search`: `hmm_generator_search(machine, k)` optimizes the symbol matrices of a
`k`-state HMM directly (softmax rows), minimizing the state entropy subject to exact word probabilities up
to length `k + |S+|`, which implies equality on all words (Tzeng 1992). It uses an augmented Lagrangian with
analytic gradients (forward recursion over the word tree, stationary law differentiated through the
fundamental matrix): feasibility first, then entropy descent. `coupled_seed_from_hmm` recovers the coupled
form `(pi, Q, R, K)` from the product chains with the causal states.
- `generative_model` runs it after the coupled search (`hmm_search=True`, `hmm_search_starts=8`) for
`k = |S+| .. |S+| + 2` with half the remaining budget, or two values of `k` and two starts without a budget.
The coupled searches parameterize states by their beliefs and miss generators whose states' pasts or futures
are not belief-mixtures of the causal states'. On the 96 open brackets of the binary 3-state dataset this
search lowered seven upper bounds, e.g. `n3-t122-d2` from `C_mu = 0.9037` to `0.7956` and `n3-t140-d3`
from `1.5142` to `1.4010`.

### Generator heaviest-term bound by default

- `generative_model` now runs `generator_heaviest_term_bound` last, once the best generator is
Expand Down
15 changes: 15 additions & 0 deletions docs/generators/generative_models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,19 @@ source to the same tolerance (for example the golden mean, where the support bou
drawing its states independently at both ends of each bidirectional edge also generates the process;
coupled generators such as the interleaved product flag do not.

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
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
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
results through :func:`~sofic.generators.hmm_search.coupled_seed_from_hmm`. On the binary 3-state dataset it
lowered seven open upper bounds, for example from :math:`C_\mu = 0.9037` to :math:`0.7956` with a 4-state
generator that the belief-parameterized searches never reached.

Wyner and functional generators
-------------------------------

Expand Down Expand Up @@ -382,6 +395,8 @@ Coupled generators and bounds
.. autofunction:: sofic.generators.functional_generators.functional_cover_search
.. autofunction:: sofic.generators.functional_generators.product_rectangles
.. autofunction:: sofic.generators.generative_search.resolve_bidirectional
.. autofunction:: sofic.generators.hmm_search.hmm_generator_search
.. autofunction:: sofic.generators.hmm_search.coupled_seed_from_hmm
.. autoclass:: sofic.generators.generative_search.GenerativeModelResult
:members: certified, gap, g_optima_generate
.. autofunction:: sofic.generators.coverage_bound.coverage_entropy_lower
Expand Down
22 changes: 22 additions & 0 deletions docs/references.bib
Original file line number Diff line number Diff line change
Expand Up @@ -1843,3 +1843,25 @@ @incollection{LombardySakarovitch2008
publisher = {Amsterdam University Press},
year = {2008},
}

@article{Tzeng1992,
author = {Tzeng, Wen-Guey},
title = {A Polynomial-Time Algorithm for the Equivalence of Probabilistic Automata},
journal = {SIAM Journal on Computing},
volume = {21},
number = {2},
pages = {216--227},
year = {1992},
doi = {10.1137/0221017},
}

@article{Ruebeck2018,
author = {Ruebeck, Joshua B. and James, Ryan G. and Mahoney, John R. and Crutchfield, James P.},
title = {Prediction and Generation of Binary {Markov} Processes: Can a Finite-State Fox Catch a {Markov} Mouse?},
journal = {Chaos},
volume = {28},
number = {1},
pages = {013109},
year = {2018},
doi = {10.1063/1.5003041},
}
36 changes: 32 additions & 4 deletions sofic/generators/generative_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
4. *Upper bounds:* ε-machines, line-split seeds from the exact optima
(:func:`~sofic.generators.coupled_generators.line_split_seeds`), memory lifts, the exact minimal functional generator
(:func:`~sofic.generators.functional_generators.functional_cover_search`), lifted channels
(small joints), coupled search.
(small joints), coupled search, and a belief-free search over HMM symbol matrices
(:func:`~sofic.generators.hmm_search.hmm_generator_search`, ``hmm_search``), which reaches generators the
belief-parameterized searches miss.
5. *Final lower bound.* While the bracket is open, the generator heaviest-term bound
(:func:`~sofic.generators.exact_ci_bounds.generator_heaviest_term_bound`, ``generator_heaviest_term``)
aims at the verified upper bound with the rest of the budget, on joints with at most 14 causal states
Expand Down Expand Up @@ -71,6 +73,7 @@
support_exact_cover_bound,
support_type_bound,
)
from sofic.generators.hmm_search import coupled_seed_from_hmm, hmm_generator_search

_MAX_RECTANGLES = 7
_FLOW_THRESHOLDS = ((0.6,), (0.55, 0.65))
Expand Down Expand Up @@ -399,7 +402,7 @@ def _bracket_search(
memory_starts: int = 10,
residual_atol: float = 1e-7,
reproduction_atol: float = 1e-5,
stages: Sequence[str] = ("machines", "exact", "memory", "functional", "lifted", "coupled"),
stages: Sequence[str] = ("machines", "exact", "memory", "functional", "lifted", "coupled", "hmm"),
large: int = 9,
exact_starts: int = 30,
dit_fallback: bool = True,
Expand All @@ -408,6 +411,8 @@ def _bracket_search(
coverage_k_max: int = 8,
coverage_certified_only: bool = False,
generator_heaviest_term: bool = True,
hmm_search: bool = True,
hmm_search_starts: int = 8,
generator_caps: int = 2,
targeted: bool = True,
entropy_sweep_starts: int = 80,
Expand Down Expand Up @@ -865,6 +870,21 @@ def maybe_return_early() -> GenerativeModelResult | None:
)[: None if wyner else 2]:
offer(f"coupled k={k} ({res.start})", (res.pi, res.Q, res.R, res.K))

if hmm_search and "hmm" in stages and not wyner and not out_of_time("belief-free HMM search"):
stage_deadline = share(0.5)
ks = range(problem.n_plus, problem.n_plus + (3 if stage_deadline is not None else 2))
n_starts = hmm_search_starts if stage_deadline is not None else 2
found = 0
for k in ks:
if out_of_time("belief-free HMM search") or (
stage_deadline is not None and time.monotonic() >= stage_deadline
):
break
for res in hmm_generator_search(reference, k, starts=n_starts, rng=rng, deadline=stage_deadline)[:2]:
offer(f"belief-free HMM k={k} (start {res.start})", coupled_seed_from_hmm(problem, res.matrices))
found += 1
log.append({"stage": "belief-free HMM search", "k": list(ks), "starts": n_starts, "generators": found})

best_value = min((c[0] for c in candidates), default=np.inf)
if targeted and optima and best_value - lower > _TARGETED_GAP and not out_of_time("targeted line-split search"):
seeds = targeted_line_split_seeds(problem, optima, residual_atol=residual_atol, deadline=share(0.8), rng=rng)
Expand Down Expand Up @@ -931,7 +951,7 @@ def generative_model_from_bidirectional(
memory_starts: int = 10,
residual_atol: float = 1e-7,
reproduction_atol: float = 1e-5,
stages: Sequence[str] = ("machines", "exact", "memory", "functional", "lifted", "coupled"),
stages: Sequence[str] = ("machines", "exact", "memory", "functional", "lifted", "coupled", "hmm"),
large: int = 9,
exact_starts: int = 30,
dit_fallback: bool = True,
Expand All @@ -940,6 +960,8 @@ def generative_model_from_bidirectional(
coverage_k_max: int = 8,
coverage_certified_only: bool = False,
generator_heaviest_term: bool = True,
hmm_search: bool = True,
hmm_search_starts: int = 8,
generator_caps: int = 2,
targeted: bool = True,
entropy_sweep_starts: int = 80,
Expand Down Expand Up @@ -970,6 +992,8 @@ def generative_model_from_bidirectional(
coverage_k_max=coverage_k_max,
coverage_certified_only=coverage_certified_only,
generator_heaviest_term=generator_heaviest_term,
hmm_search=hmm_search,
hmm_search_starts=hmm_search_starts,
generator_caps=generator_caps,
targeted=targeted,
entropy_sweep_starts=entropy_sweep_starts,
Expand Down Expand Up @@ -1066,6 +1090,8 @@ def generative_model(
coverage_k_max: int = 8,
coverage_certified_only: bool = False,
generator_heaviest_term: bool = True,
hmm_search: bool = True,
hmm_search_starts: int = 8,
generator_caps: int = 2,
targeted: bool = True,
entropy_sweep_starts: int = 80,
Expand Down Expand Up @@ -1106,7 +1132,7 @@ def generative_model(
memory_starts=memory_starts,
residual_atol=residual_atol,
reproduction_atol=reproduction_atol,
stages=("machines", "exact", "memory", "functional", "lifted", "coupled"),
stages=("machines", "exact", "memory", "functional", "lifted", "coupled", "hmm"),
large=large,
exact_starts=exact_starts,
dit_fallback=dit_fallback,
Expand All @@ -1115,6 +1141,8 @@ def generative_model(
coverage_k_max=coverage_k_max,
coverage_certified_only=coverage_certified_only,
generator_heaviest_term=generator_heaviest_term,
hmm_search=hmm_search,
hmm_search_starts=hmm_search_starts,
generator_caps=generator_caps,
targeted=targeted,
entropy_sweep_starts=entropy_sweep_starts,
Expand Down
208 changes: 208 additions & 0 deletions sofic/generators/hmm_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
r"""Belief-free search for low-entropy generators: optimize an HMM's symbol matrices directly.

The coupled searches of :mod:`~sofic.generators.coupled_generators` parameterize a generator's states by their
causal-state beliefs :math:`(Q_w, R_w)`. That parameterization favours generators whose states' pasts and futures
are belief-mixtures of the causal states', and on some processes it misses lower-entropy generators that are not.
:func:`hmm_generator_search` instead optimizes the :math:`k`-state symbol matrices :math:`T^{(x)}` (softmax over
:math:`(x, w')` for each row), minimizing the state entropy :math:`H[\pi]` subject to exact word probabilities
for all words up to length :math:`k + n`, where :math:`n` is the number of forward causal states. Two weighted
automata with :math:`k` and :math:`n` states that agree on all words of length up to :math:`k + n - 1` agree on all
words :cite:`Tzeng1992`, so feasible points are generators. The constraints enter an augmented Lagrangian, first
without the entropy term (to reach a generator from a random start) and then with it. Gradients are analytic:
forward and backward vectors over the word tree, and the stationary distribution differentiated through the
fundamental matrix. Direct parameter search for minimal generators of binary Markov processes is the approach of
:cite:`Ruebeck2018`; the word-equality constraints and the use as a pipeline stage are ours.
"""

from __future__ import annotations

import itertools
import time
from dataclasses import dataclass
from typing import Any

import numpy as np
from scipy.optimize import minimize

__all__ = ["HMMSearchResult", "coupled_seed_from_hmm", "hmm_generator_search"]


@dataclass(frozen=True)
class HMMSearchResult:
"""A generator found by :func:`hmm_generator_search`: symbol matrices, stationary law, and fit."""

matrices: tuple[np.ndarray, ...]
pi: np.ndarray
entropy: float
word_residual: float
k: int
start: int


def _entropy(p: np.ndarray) -> float:
p = p[p > 1e-15]
return float(-(p * np.log2(p)).sum())


def _stationary(M: np.ndarray) -> np.ndarray:
"""A stationary law of the stochastic matrix ``M`` (least squares, so defined for reducible chains too)."""
k = M.shape[0]
A = np.vstack([M.T - np.eye(k), np.ones(k)])
b = np.zeros(k + 1)
b[-1] = 1.0
return np.linalg.lstsq(A, b, rcond=None)[0]


def _fundamental(M: np.ndarray, pi: np.ndarray) -> np.ndarray:
"""``(I - M + 1 pi)^{-1}``, so that ``d pi = pi dM Z``; a pseudo-inverse when the chain is reducible."""
A = np.eye(M.shape[0]) - M + np.outer(np.ones(M.shape[0]), pi)
try:
return np.linalg.inv(A)
except np.linalg.LinAlgError:
return np.linalg.pinv(A)


class _WordTree:
"""All words of length 1 .. L over ``ns`` symbols, in breadth-first order (parents before children)."""

def __init__(self, ns: int, L: int) -> None:
self.words = [w for n in range(1, L + 1) for w in itertools.product(range(ns), repeat=n)]
index = {w: i for i, w in enumerate(self.words)}
self.parent = np.array([index.get(w[:-1], -1) for w in self.words])
self.last = np.array([w[-1] for w in self.words])

def forward(self, T: list[np.ndarray], pi: np.ndarray) -> np.ndarray:
"""Row vectors pi T^{(w)} for every word."""
alpha = np.empty((len(self.words), len(pi)))
for i, (p, x) in enumerate(zip(self.parent, self.last, strict=True)):
alpha[i] = (pi if p < 0 else alpha[p]) @ T[x]
return alpha


def _target_words(machine: Any, tree: _WordTree) -> np.ndarray:
from sofic.generators.matrices import symbol_matrices

mats = symbol_matrices(machine.to_mealy() if hasattr(machine, "to_mealy") else machine)
T = [np.asarray(mats[x], float) for x in sorted(mats)]
pi = _stationary(sum(T))
return tree.forward(T, pi).sum(axis=1)


def _unpack(theta: np.ndarray, k: int, ns: int) -> tuple[list[np.ndarray], np.ndarray]:
L = theta.reshape(k, ns * k)
E = np.exp(L - L.max(axis=1, keepdims=True))
E /= E.sum(axis=1, keepdims=True)
return [E[:, x * k : (x + 1) * k] for x in range(ns)], E


def _objective(theta, k, ns, tree, target, lam, mu, weight):
"""Augmented Lagrangian value and gradient in the softmax logits."""
T, E = _unpack(theta, k, ns)
M = sum(T)
pi = _stationary(M)
Z = _fundamental(M, pi)
alpha = tree.forward(T, pi)
r = alpha.sum(axis=1) - target
pi_c = np.clip(pi, 1e-300, None)
h = float(-(pi_c * np.log2(pi_c)).sum())
value = weight * h + float(lam @ r) + 0.5 * mu * float(r @ r)
g_word = lam + mu * r # d value / d P(w)
# reverse-mode through alpha(w) = alpha(parent) T^{(last)}, P(w) = alpha(w) . 1; children come after parents
adj = np.outer(g_word, np.ones(k))
gT = [np.zeros((k, k)) for _ in range(ns)]
g_pi = np.zeros(k)
for i in range(len(tree.words) - 1, -1, -1):
p, x = tree.parent[i], tree.last[i]
prev = pi if p < 0 else alpha[p]
gT[x] += np.outer(prev, adj[i])
back = T[x] @ adj[i]
if p < 0:
g_pi += back
else:
adj[p] += back
g_pi += weight * (-(np.log2(pi_c) + 1.0 / np.log(2)))
# pi = stationary(M): d pi = pi dM Z, so d value / d M = pi^T (Z g_pi)^T
gM = np.outer(pi, Z @ g_pi)
G = np.concatenate([gT[x] + gM for x in range(ns)], axis=1) # d value / d E
grad = E * (G - (G * E).sum(axis=1, keepdims=True))
return value, grad.ravel()


def hmm_generator_search(
machine: Any,
k: int,
*,
starts: int = 8,
rng: np.random.Generator | None = None,
deadline: float | None = None,
rounds: int = 12,
feasibility_tol: float = 1e-7,
) -> list[HMMSearchResult]:
"""Low-entropy ``k``-state generators of the process of ``machine`` (its forward ε-machine), best first.

Each of ``starts`` random starts reaches a generator with no entropy term, then descends in :math:`H[\\pi]`
under the augmented Lagrangian (``rounds`` outer updates). 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.
"""
from sofic.generators.matrices import symbol_matrices

rng = rng if rng is not None else np.random.default_rng()
mats = symbol_matrices(machine.to_mealy() if hasattr(machine, "to_mealy") else machine)
ns, n = len(mats), next(iter(mats.values())).shape[0]
tree = _WordTree(ns, k + n)
target = _target_words(machine, tree)
opts = {"maxiter": 3000, "ftol": 1e-16, "gtol": 1e-12}
out = []
for start in range(starts):
if deadline is not None and time.monotonic() >= deadline:
break
theta = rng.normal(size=k * ns * k)
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
mu = 1e3
for _ in range(rounds):
if deadline is not None and time.monotonic() >= deadline:
break
theta = minimize(_objective, theta, args=(*args, lam, mu, 1.0), jac=True, method="L-BFGS-B", options=opts).x
T, _ = _unpack(theta, k, ns)
pi = _stationary(sum(T))
lam = lam + mu * (tree.forward(T, pi).sum(axis=1) - target)
mu = min(mu * 3.0, 1e7)
T, _ = _unpack(theta, k, ns)
pi = _stationary(sum(T))
resid = float(np.abs(tree.forward(T, pi).sum(axis=1) - target).max())
if resid <= feasibility_tol:
out.append(HMMSearchResult(tuple(T), pi, _entropy(pi), resid, k, start))
return sorted(out, key=lambda r: r.entropy)


def coupled_seed_from_hmm(problem: Any, matrices: tuple[np.ndarray, ...]) -> tuple[np.ndarray, ...]:
"""The coupled form ``(pi, Q, R, K)`` of an HMM generator relative to ``problem``'s causal states.

``Q_w = Pr(S+_0 | W_0 = w)`` from the stationary law of the forward product chain (S+, W), ``R_w`` from the
reverse-time product chain (S-, W), ``K[w, x, w'] = T^{(x)}[w, w']``. States of zero stationary weight are
dropped.
"""
T = [np.asarray(M, float) for M in matrices]
pi = _stationary(sum(T))
keep = np.flatnonzero(pi > 1e-12)
T = [M[np.ix_(keep, keep)] / 1.0 for M in T]
rows = sum(T).sum(axis=1, keepdims=True)
T = [M / rows for M in T]
pi = _stationary(sum(T))
k = len(pi)
na, nb = problem.n_plus, problem.n_minus
Pf = np.zeros((na * k, na * k))
for a, x, a2 in zip(*np.nonzero(problem.F), strict=True):
Pf[a * k : (a + 1) * k, a2 * k : (a2 + 1) * k] += T[x]
J = _stationary(Pf).reshape(na, k)
Q = (J / np.maximum(J.sum(axis=0), 1e-300)).T
Pr = np.zeros((nb * k, nb * k))
for x, c, b in zip(*np.nonzero(problem.G), strict=True):
Pr[c * k : (c + 1) * k, b * k : (b + 1) * k] += (pi[:, None] * T[x] / np.maximum(pi[None, :], 1e-300)).T
J = _stationary(Pr).reshape(nb, k)
R = (J / np.maximum(J.sum(axis=0), 1e-300)).T
K = np.stack(T, axis=1)
return pi, np.clip(Q, 0, None), np.clip(R, 0, None), K
Loading
Loading