diff --git a/CHANGELOG.md b/CHANGELOG.md index 0854a59..9db1746 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ A second correctness review: every fix below was reproduced against a brute-force reference or a closed-form value and has a regression test. +### Bidirectional state pairing + +- `BidirectionalEpsilonMachine.from_forward` (and `to_bidirectional()`) no longer pairs forward and reverse causal + states according to `PYTHONHASHSEED`. For the alternating biased coins the Eq. (15) graph has two closed components + with the right marginals and the same anatomy gap: the true joint, and the one with the forward labels swapped. The + tie fell to the `repr` of the reverse state labels, which vary with the hash seed, and five of the seeds 0–7 gave the + swapped joint. Information measures were unaffected, but the joint's forward coordinate no longer matched + `forward_machine`: started from `π(A, ·) / π⁺(A)`, the bidirectional machine emitted with state `B`'s coin, and + word probabilities given a forward state were off by up to 0.3. The selector now keeps only components whose + forward states emit as the forward machine does, `Σ_γ π(α, γ) Pr(x | (α, γ)) = π⁺(α) Pr(x | α)`, before the + anatomy-gap and support tie-breaks. + ### Strassen bound on one-sided generators - New `sofic.generators.strassen_bound`: `strassen_lower_bound(bidir)` bounds from below the state entropy of every diff --git a/sofic/generators/bidirectional_construction.py b/sofic/generators/bidirectional_construction.py index 5a5d5f8..e006464 100644 --- a/sofic/generators/bidirectional_construction.py +++ b/sofic/generators/bidirectional_construction.py @@ -396,6 +396,42 @@ def _joint_marginal_mismatch( return error +def _forward_emission_mismatch( + graph: TransitionGraph, + joint: dict[tuple[Hashable, Hashable], Any], + forward: EpsilonMachine, + pi_plus: dict[Hashable, Any], +) -> float: + """Max abs deviation of ``joint``'s forward-state emissions from the forward machine's. + + On the true joint class ``Σ_γ π(α, γ) Pr(x | (α, γ)) = π⁺(α) Pr(x | α)``. The Eq. (15) + weights come from the reverse machine alone, so a closed component can match both + stationary marginals while pairing the forward and reverse states out of phase (the + alternating biased coins); its forward states then emit with the reverse machine's + probabilities and fail this check. + """ + joint_mass: dict[tuple[Hashable, Any], list[Any]] = defaultdict(list) + for state, mass in joint.items(): + for transition in graph.out_transitions(state): + symbol = transition.data.get(ATTR_EMISSION) + joint_mass[(state[0], symbol)].append(as_prob(mass) * as_prob(transition.data.get(ATTR_PROB, 0.0))) + + forward_mass: dict[tuple[Hashable, Any], list[Any]] = defaultdict(list) + for alpha in {state[0] for state in joint}: + weight = as_prob(pi_plus.get(alpha, 0)) + for transition in forward.graph.out_transitions(alpha): + symbol = transition.data.get(ATTR_EMISSION) + forward_mass[(alpha, symbol)].append(weight * as_prob(transition.data.get(ATTR_PROB, 0.0))) + + error = 0.0 + for key in set(joint_mass) | set(forward_mass): + error = max( + error, + _abs_marginal_error(sum_probs(joint_mass.get(key, [])), sum_probs(forward_mass.get(key, []))), + ) + return error + + def _joint_pi_minimum_support( graph: TransitionGraph, forward: EpsilonMachine, @@ -412,9 +448,13 @@ def _joint_pi_minimum_support( closed recurrent component (e.g. the Nemo process, which admits a spurious all-``0`` period-3 cycle alongside the genuine 6-state machine), the correct class is the one whose forward/reverse marginals equal the forward/reverse - causal-state stationary distributions. Among marginal-matching components the - information-anatomy identity ``h_μ = b_μ + r_μ`` and then the support size break - remaining ties; if none match we fall back to the smallest-mismatch component. + causal-state stationary distributions. Among marginal-matching components we + keep those whose forward states emit as the forward machine does + (:func:`_forward_emission_mismatch`), which rejects out-of-phase pairings with + the right marginals; the information-anatomy identity ``h_μ = b_μ + r_μ`` and + then the support size break remaining ties. If no component matches we fall + back to the smallest-mismatch component, and if none emits consistently, to the + marginal-matching pool. """ pairs = [state for state in graph.states() if isinstance(state, tuple) and len(state) == 2] if not pairs: @@ -447,6 +487,14 @@ class is the one whose forward/reverse marginals equal the forward/reverse else: matching = [candidate for candidate in candidates if candidate[0] <= marginal_tol] pool = matching or [min(candidates, key=lambda candidate: candidate[0])] + emission_errors = [_forward_emission_mismatch(graph, candidate[3], forward, pi_plus) for candidate in pool] + if all_symbolic: + consistent = [candidate for candidate, error in zip(pool, emission_errors, strict=True) if error == 0.0] + else: + consistent = [ + candidate for candidate, error in zip(pool, emission_errors, strict=True) if error <= marginal_tol + ] + pool = consistent or pool # Anatomy gaps that agree to round-off are ties; comparing them exactly made # the choice depend on the platform's floating-point kernels. best_gap = min(candidate[1] for candidate in pool) diff --git a/tests/test_bidirectional_construction.py b/tests/test_bidirectional_construction.py index 54344a1..0ad82e9 100644 --- a/tests/test_bidirectional_construction.py +++ b/tests/test_bidirectional_construction.py @@ -3,14 +3,20 @@ from __future__ import annotations import math +import os +import subprocess +import sys +from pathlib import Path import pytest -from sofic.examples import even_process, golden_mean +from sofic.examples import alternating_biased_coins, even_process, golden_mean from sofic.exceptions import StochasticValidationError from sofic.generators import bidirectional_construction as bc from sofic.generators.bidirectional_construction import infer_reverse_epsilon_machine +from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine from sofic.generators.epsilon_machine import EpsilonMachine +from sofic.generators.reversal import time_reverse_stochastic from sofic.graph import ATTR_EMISSION, ATTR_FUTURE_SYMBOL, ATTR_PROB, TransitionGraph @@ -127,3 +133,56 @@ def test_symbolic_stationary_state_probabilities(): ) probs = bc._stationary_state_probabilities(machine) assert sp.simplify(probs["A"] - 1 / (1 + p)) == 0 + + +def _forward_word_error(length: int) -> float: + """Largest gap, over words of ``length``, between ``Pr(w | S⁺ = α)`` from the forward + machine and from the bidirectional machine started in ``π(α, ·) / π⁺(α)``.""" + forward = alternating_biased_coins(0.5, 0.2) + bidir = BidirectionalEpsilonMachine.from_forward(forward) + joint = bidir.joint_distribution() + error = 0.0 + for alpha in forward.states(): + mass = {state: p for state, p in joint.items() if state[0] == alpha} + start = {state: p / sum(mass.values()) for state, p in mass.items()} + expected = forward.word_probabilities(length, start=alpha) + actual = bidir.word_probabilities(length, start=start) + for word in expected.keys() | actual.keys(): + error = max(error, abs(expected.get(word, 0.0) - actual.get(word, 0.0))) + return error + + +def test_forward_emission_mismatch_rejects_the_out_of_phase_component(): + """The alternating biased coins have two closed Eq. (15) components with the right + marginals; in the out-of-phase one, each forward state emits with the other coin.""" + forward = alternating_biased_coins(0.5, 0.2) + reverse = bc._relabel_collision_free(infer_reverse_epsilon_machine(forward), forward) + graph = bc._build_eq15_graph( + forward, time_reverse_stochastic(reverse), sources=bc._compatible_pairs(forward, reverse) + ) + pi_plus = bc._stationary_state_probabilities(forward) + joints = [ + bc._joint_pi_on_pair_subset(graph, sorted(component, key=repr)) + for component in bc._undirected_components(graph) + ] + errors = sorted(bc._forward_emission_mismatch(graph, joint, forward, pi_plus) for joint in joints if joint) + assert errors == [pytest.approx(0.0, abs=1e-12), pytest.approx(0.15)] + + +def test_bidirectional_machine_reproduces_forward_words(): + assert _forward_word_error(6) < 1e-12 + + +def test_bidirectional_pairing_does_not_depend_on_the_hash_seed(): + """The out-of-phase component used to win on the ``repr`` of the reverse state labels, + which depend on ``PYTHONHASHSEED``.""" + script = f"import runpy; print(runpy.run_path({str(Path(__file__))!r})['_forward_word_error'](6))" + for seed in range(8): + out = subprocess.run( + [sys.executable, "-c", script], + env={**os.environ, "PYTHONHASHSEED": str(seed)}, + capture_output=True, + text=True, + check=True, + ) + assert float(out.stdout.strip()) < 1e-12, f"PYTHONHASHSEED={seed}"