diff --git a/CHANGELOG.md b/CHANGELOG.md index a62cddd..352067f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,31 @@ A second correctness review: every fix below was reproduced against a brute-force reference or a closed-form value and has a regression test. +### Truncated bidirectional machines + +- `generative_model` no longer reports lower bounds of a truncation as bounds on the process. When the reverse + ε-machine is infinite but its mixed states merge within numerical tolerance, the bidirectional machine is a finite + truncation (`bidir_class` `"truncated"`). Its generators are verified against the forward machine, so the upper + bound holds, 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 were computed on the truncation, and their sources + read "(certified)": on a 2-state ternary process the generator coverage bound of the truncation came within + `1.5e-6` of the best generator's entropy, 0.9982954, where the future-window bound is 0.9981857. These stages are + now skipped, as is the share of the budget held back for the final heaviest-term bound. The lower bound is the + larger future-window generator coverage bound at `L = 2` and 3 (`window_spec`, Löhr & Ay 2009), computed first + from the forward machine with at most 30% of the budget. `minimal_wyner_model` reports `lower` 0 on a truncated build. +- `resolve_bidirectional` classes a bidirectional input `"truncated"` when the reverse ε-machine of its forward + machine is infinite (was: always `"finite"`), as the build does. +- The simplex-chain search treats a Gauss-Newton step whose SVD does not converge (`numpy.linalg.LinAlgError`) as a + failed snap; on a binary 3-state process the error ended `generative_model` after 116 s. +- The simplex-chain search checks its deadline inside an atom step. The reverse side of a truncated build can have + ~100 states, and one wall tangent there (a finite-difference Jacobian over every atom coordinate) took minutes: with + the truncation's lower bounds skipped the search ran, and `generative_model` on a 2-state ternary process with 90 + reverse states was still running at 1,020 s on a 300 s budget. On a 53-state reverse side a 2 s search took 95 s. +- `bilevel_search` checks its deadline at every evaluation of its objective, keeping the best channel scored, where + Powell's callback checked it once an iteration. An iteration line-searches every logit of the channel, and on a + 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`). + ### Coverage bound: least entropy under the caps - `coverage_entropy_lower(caps)`, the last step of `coverage_bound`, `generator_coverage_bound` and the pipeline's diff --git a/docs/generators/generative_models.rst b/docs/generators/generative_models.rst index db2635a..4c8e594 100644 --- a/docs/generators/generative_models.rst +++ b/docs/generators/generative_models.rst @@ -438,6 +438,19 @@ feeds them to :func:`~sofic.generators.generator_caps.generator_coverage_bound` on :math:`C_g` from the forward ε-machine alone. On the :math:`(2, \infty)` process a two-symbol window already gives :math:`C_g \ge 3/2`. +Some processes with infinite reverse ε-machines still build a bidirectional machine: the reverse +mixed states merge within numerical tolerance, and the build is a finite truncation (``bidir_class`` +``"truncated"``; a bidirectional machine passed in is classed the same way). The generators found on it +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 +: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. + Supports without 2 × 2 rectangles --------------------------------- diff --git a/sofic/generators/coupled_generators.py b/sofic/generators/coupled_generators.py index 8ba9112..80af736 100644 --- a/sofic/generators/coupled_generators.py +++ b/sofic/generators/coupled_generators.py @@ -729,36 +729,41 @@ def bilevel_search( """Outer search over channels ``c[pair, w]`` scoring ``H[W] + weight * t(c)``, where ``t`` is the linear-programming violation of :func:`generator_kernel`, from the given starting channels (derivative-free; small problems). Returns ``(entropy, violation, channel)`` per start, best feasible first. Past - ``deadline`` (a :func:`time.monotonic` value) the current start stops and no new one begins. + ``deadline`` (a :func:`time.monotonic` value) the current start stops, keeping the best channel it has + scored, and no new one begins. """ problem = _GeneratorProblem(bidir) n = len(problem.lifted.p) out = [] for c0 in starts: k = c0.shape[1] + best: dict[str, Any] = {"score": np.inf, "z": None} def channel(z: np.ndarray, k: int = k) -> np.ndarray: z = z.reshape(n, k) z = np.exp(z - z.max(axis=1, keepdims=True)) return z / z.sum(axis=1, keepdims=True) - def score(z: np.ndarray, channel=channel) -> float: + # checked per evaluation: one Powell iteration line-searches every logit, minutes on a large problem + def score(z: np.ndarray, channel=channel, best=best) -> float: + if deadline is not None and time.monotonic() > deadline: + raise _DeadlineReachedError c = channel(z) pi = problem.lifted.p @ c p = pi[pi > 1e-15] - return float(-(p * np.log2(p)).sum()) + weight * generator_kernel(problem, c)[0] + value = float(-(p * np.log2(p)).sum()) + weight * generator_kernel(problem, c)[0] + if value < best["score"]: + best.update(score=value, z=z.copy()) + return value if deadline is not None and out and time.monotonic() > deadline: break - def stop(intermediate_result: Any) -> None: - if deadline is not None and time.monotonic() > deadline: - raise StopIteration - z0 = np.log(np.maximum(c0, 1e-6)).ravel() - z = minimize( - score, z0, method="Powell", callback=stop, options={"maxiter": maxiter, "xtol": 1e-6, "ftol": 1e-10} - ).x + try: + z = minimize(score, z0, method="Powell", options={"maxiter": maxiter, "xtol": 1e-6, "ftol": 1e-10}).x + except _DeadlineReachedError: + z = z0 if best["z"] is None else best["z"] c = channel(z) pi = problem.lifted.p @ c p = pi[pi > 1e-15] diff --git a/sofic/generators/generative_search.py b/sofic/generators/generative_search.py index 57299ad..4148003 100644 --- a/sofic/generators/generative_search.py +++ b/sofic/generators/generative_search.py @@ -51,6 +51,16 @@ Otherwise it does not: no bound on the number of states of a minimal generator is known when :math:`p.\chi` is positive. SCIP's solution, polished by the belief-free search, is offered as a candidate. +*Truncated builds.* When the reverse ε-machine is infinite, the bidirectional machine is a finite truncation +(``bidir_class`` ``"truncated"`` in the build stage, for bidirectional input as well). Its generators are +word-verified against the forward machine, so ``upper`` holds for the process, but the lower bounds computed on it +bound the truncation. :func:`generative_model` skips those stages (the excess entropy, stage 1, SCIP's dual bound on +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. + 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 variant lives in :mod:`~sofic.generators.functional_generators`. @@ -130,6 +140,10 @@ _GENERATOR_HEAVIEST_TERM_MAX_DIMS = 14 # Share of a time budget kept for that stage: the upper-bound searches stop this much early. _GENERATOR_HEAVIEST_TERM_SHARE = 0.2 +# Future-window coverage bound on truncated builds: boxes per explicit cap by window length (2 to 9 minutes per +# 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 # 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 @@ -340,11 +354,16 @@ def resolve_bidirectional( use_ladder: bool = True, time_budget: float | None = None, ) -> tuple[BidirectionalEpsilonMachine, dict[str, Any]]: - """Build or accept a bidirectional ε-machine for generator search.""" + """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. + """ from sofic.generators.bidirectional_build import try_build_bidirectional if isinstance(machine, BidirectionalEpsilonMachine): - return machine, {"bidir_class": "finite", "source": "bidirectional input"} + finite = machine.forward_machine.reverse_epsilon_machine_is_finite() + return machine, {"bidir_class": "finite" if finite else "truncated", "source": "bidirectional input"} forward = machine if isinstance(machine, EpsilonMachine) else EpsilonMachine.from_hmm(machine) built = try_build_bidirectional( forward, reverse_max_states=reverse_max_states, use_ladder=use_ladder, time_budget=time_budget @@ -364,6 +383,35 @@ def resolve_bidirectional( return built.bidir, meta +def _future_window_bound( + forward: EpsilonMachine, *, explicit: int, k_max: int, deadline: float | None +) -> tuple[float, str, list[dict[str, Any]]]: + """The larger future-window generator coverage bound over the lengths of ``_WINDOW_NODES``, its source and + its log; a lower bound on :math:`C_g` from the forward machine alone. ``deadline`` is split evenly between + the lengths; the bounds stay valid past it, only looser.""" + from sofic.generators.generator_caps import generator_coverage_bound + from sofic.generators.generator_problem_spec import window_spec + + value, source, log = 0.0, "trivial lower bound", [] + for i, (length, nodes) in enumerate(_WINDOW_NODES.items()): + stop = None + if deadline is not None: + now = time.monotonic() + stop = now + max(0.0, deadline - now) / (len(_WINDOW_NODES) - i) + stage = f"future-window generator coverage bound (L={length})" + cov = generator_coverage_bound( + _GeneratorProblem.from_spec(window_spec(forward, length)), + k_max=k_max, + explicit=explicit, + max_nodes=nodes, + deadline=stop, + ) + log.append({"stage": stage, "value": cov.value, "caps": cov.caps}) + if cov.value > value: + value, source = cov.value, stage + return value, source, log + + 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]) @@ -505,8 +553,13 @@ def _bracket_search( coupled_dual_strategy: bool = True, time_budget: float | None = None, rng: np.random.Generator | None = None, + window_lower: tuple[float, str] | None = None, ) -> GenerativeModelResult: - """Generator search ranked by state entropy or by ``I[W : S+, S-]``; see the module docstring.""" + """Generator search ranked by state entropy or by ``I[W : S+, S-]``; see the module docstring. + + ``window_lower`` is ``(value, source)`` of a lower bound on the process when ``bidir`` is a truncation; it + replaces every lower bound computed on ``bidir``. + """ from sofic.generators.functional_generators import functional_cover_search from sofic.generators.lifted_common_information import _unconstrained_channel from sofic.generators.minimal_generative_model import ( @@ -516,6 +569,7 @@ def _bracket_search( ) wyner = objective == "wyner" + truncated = window_lower is not None rng = rng or np.random.default_rng() problem = _GeneratorProblem(bidir) lifted = problem.lifted @@ -526,6 +580,7 @@ def _bracket_search( if time_budget is not None and generator_heaviest_term and not wyner + and not truncated and problem.n_plus + problem.n_minus <= _GENERATOR_HEAVIEST_TERM_MAX_DIMS else 0.0 ) @@ -557,14 +612,18 @@ def share(fraction: float) -> float | None: n_rect = len(maximal_rectangles(set(joint))) # ---- lower bounds ------------------------------------------------------------------------------- - excess = _entropy(problem.p_plus) + _entropy(problem.p_minus) - _entropy(problem.p_pair) - lower, lower_source = excess, "excess entropy" + if truncated: + lower, lower_source = window_lower + log.append({"stage": "lower bounds", "skipped": "the bidirectional machine is a truncation", "lower": lower}) + else: + excess = _entropy(problem.p_plus) + _entropy(problem.p_minus) - _entropy(problem.p_pair) + lower, lower_source = excess, "excess entropy" + log.append({"stage": "excess entropy", "value": excess}) lower_certified = True - log.append({"stage": "excess entropy", "value": excess}) if wyner: log.append({"stage": "entropy lower bounds", "skipped": "they bound H[W], not I[W : S+, S-]"}) - if not wyner and n_rect <= _MAX_RECTANGLES: + if not wyner and not truncated and n_rect <= _MAX_RECTANGLES: exact_cover = support_exact_cover_bound(joint) if exact_cover is not None: log.append( @@ -591,7 +650,9 @@ def share(fraction: float) -> float | None: # 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 + settled = ( + not wyner and not truncated 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) @@ -607,7 +668,12 @@ def generator_coverage() -> None: lower, lower_source, lower_certified = gen.value, "generator coverage bound (certified)", True def heaviest_term_wanted() -> bool: - return not wyner and coverage == "certified" and problem.n_plus + problem.n_minus <= _HEAVIEST_TERM_MAX_DIMS + return ( + not wyner + and not truncated + and coverage == "certified" + and problem.n_plus + problem.n_minus <= _HEAVIEST_TERM_MAX_DIMS + ) def heaviest_term(aim: float) -> None: nonlocal lower, lower_source, lower_certified @@ -625,9 +691,17 @@ def heaviest_term(aim: float) -> None: lower, lower_source, lower_certified = htb.value, "heaviest-term 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 + want_generator_coverage = ( + not wyner and not truncated 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"): + if ( + not settled + and not wyner + and not truncated + and coverage in ("heuristic", "certified") + and not out_of_time("coverage bound") + ): try: use_certified = coverage == "certified" cov, meta, caps_ok = _coverage_lower_bound( @@ -741,7 +815,7 @@ def maybe_return_early() -> GenerativeModelResult | None: } ) offer("theorem generator (cryptic order at most 1)", seed) - if dec.lower > lower + 1e-9: + if not truncated and dec.lower > lower + 1e-9: lower = dec.lower lower_source = "exact separating decomposition" if dec.exact else "separating global bound (numerical)" lower_certified = dec.exact @@ -1120,7 +1194,8 @@ def maybe_return_early() -> GenerativeModelResult | None: except ImportError as exc: log.append({"stage": "restricted global bound", "k": k, "skipped": str(exc)}) else: - restricted_lower, restricted_states = gb.lower, k + if not truncated: + restricted_lower, restricted_states = gb.lower, k log.append( { "stage": "restricted global bound", @@ -1133,7 +1208,7 @@ def maybe_return_early() -> GenerativeModelResult | None: "seconds": gb.seconds, } ) - if theorem and k >= K_P and gb.lower > lower + 1e-9: + if theorem and not truncated and k >= K_P and gb.lower > lower + 1e-9: lower, lower_source, lower_certified = ( gb.lower, "restricted global bound at K(P) (numerical)", @@ -1184,6 +1259,7 @@ def maybe_return_early() -> GenerativeModelResult | None: if ( generator_heaviest_term and not wyner + and not truncated and result.lower < result.upper - _CERT_TOL and problem.n_plus + problem.n_minus <= max_dims and not out_of_time("generator heaviest-term bound") @@ -1250,7 +1326,8 @@ def generative_model_from_bidirectional( ``global_bound`` (needs PySCIPOpt, ``pip install sofic[global]``) adds the restricted global bound for generators with at most ``global_bound_states`` states, reported as ``restricted_lower``; see :class:`GenerativeModelResult`. The default, :math:`\\min(|S^+|, |S^-|) + 1`, is a convention, not a bound: - minimal generators can need more states. + minimal generators can need more states. The lower bounds are computed on ``bidir``, so on a truncation they + bound the truncation, not the process; :func:`generative_model` handles that case. """ return _bracket_search( bidir, @@ -1320,7 +1397,8 @@ def minimal_wyner_model( Wyner model and the unconstrained Wyner optimum when it passes the generator kernel. They are ranked by :math:`\I{W : S^+, S^-} = \H{S^+, S^-} - \sum_w \pi_w (\H{S^+ \mid w} + \H{S^- \mid w})` and word-verified. The state-entropy lower bounds do not apply, so ``lower`` is the excess entropy and - the bracket is certified only when a candidate attains it. + the bracket is certified only when a candidate attains it. On a truncated build (the reverse ε-machine is + infinite) that would be the truncation's excess entropy, so ``lower`` is 0. """ start = time.monotonic() bidir, build_meta = resolve_bidirectional( @@ -1347,6 +1425,7 @@ def minimal_wyner_model( coupled_dual_strategy=coupled_dual_strategy, time_budget=time_budget, rng=rng, + window_lower=(0.0, "trivial lower bound") if build_meta["bidir_class"] == "truncated" else None, ) result.stages.insert(0, {"stage": "bidirectional build", **build_meta}) return result @@ -1387,7 +1466,9 @@ def generative_model( ) -> GenerativeModelResult: """Full generative-complexity search from a forward ε-machine or bidirectional presentation. - 1. Build a bidirectional ε-machine (preflight / optional retry ladder). + 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. 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 @@ -1412,10 +1493,20 @@ def generative_model( bidir, build_meta = resolve_bidirectional( machine, reverse_max_states=reverse_max_states, use_ladder=use_ladder, time_budget=time_budget ) + window_lower, window_log = None, [] + if build_meta["bidir_class"] == "truncated": + stop = None + if time_budget is not None: + stop = time.monotonic() + _WINDOW_SHARE * max(0.0, time_budget - (time.monotonic() - start)) + value, source, window_log = _future_window_bound( + bidir.forward_machine, explicit=generator_caps, k_max=coverage_k_max, deadline=stop + ) + window_lower = (value, source) if time_budget is not None: time_budget = max(0.0, time_budget - (time.monotonic() - start)) - result = generative_model_from_bidirectional( + result = _bracket_search( bidir, + objective="entropy", max_states=max_states, starts=starts, memory_starts=memory_starts, @@ -1446,8 +1537,9 @@ def generative_model( coupled_dual_strategy=coupled_dual_strategy, time_budget=time_budget, rng=rng, + window_lower=window_lower, ) - result.stages.insert(0, {"stage": "bidirectional build", **build_meta}) + result.stages[:0] = [{"stage": "bidirectional build", **build_meta}, *window_log] return result diff --git a/sofic/generators/simplex_chains.py b/sofic/generators/simplex_chains.py index 733393b..a85e252 100644 --- a/sofic/generators/simplex_chains.py +++ b/sofic/generators/simplex_chains.py @@ -481,8 +481,11 @@ def lift(theta: np.ndarray) -> np.ndarray: ) / (2 * h) if not (np.isfinite(J).all() and np.isfinite(r).all()): # LAPACK's SVD can hang on NaN input return lift(theta), math.inf - theta = theta - np.linalg.lstsq(J, r, rcond=None)[0] - r = _wall_residuals(side, lift(theta), assign, none) + try: + theta = theta - np.linalg.lstsq(J, r, rcond=None)[0] + r = _wall_residuals(side, lift(theta), assign, none) + except np.linalg.LinAlgError: # the SVD can fail to converge on finite input too + return lift(theta), math.inf return lift(theta), float(np.abs(r).max()) if len(r) else 0.0 @@ -646,10 +649,15 @@ def _chamber_gradient(side: _Side, atoms: np.ndarray, assign: Assignment, pi: np def _wall_tangent( - side: _Side, atoms: np.ndarray, assign: Assignment, tol: float = 1e-12, h: float = 1e-7 -) -> np.ndarray: + side: _Side, + atoms: np.ndarray, + assign: Assignment, + tol: float = 1e-12, + h: float = 1e-7, + deadline: float = math.inf, +) -> np.ndarray | None: """Orthonormal basis of the directions that keep every wall equation, zero coordinate and unit sum to first - order.""" + order, or ``None`` if ``deadline`` (a :func:`time.monotonic` value) passes first.""" N, n = atoms.shape faces = [tuple(int(c) for c in np.flatnonzero(a <= tol)) for a in atoms] @@ -660,6 +668,9 @@ def eqs(flat: np.ndarray) -> np.ndarray: flat = atoms.ravel() J = np.empty((len(eqs(flat)), flat.size)) for j in range(flat.size): + # ~10^4 columns of two wall solves each on the ~100-state reverse side of a truncated build + if time.monotonic() > deadline: + return None d = np.zeros_like(flat) d[j] = h J[:, j] = (eqs(flat + d) - eqs(flat - d)) / (2 * h) @@ -669,19 +680,25 @@ def eqs(flat: np.ndarray) -> np.ndarray: def _atom_step( - side: _Side, problem: _GeneratorProblem, chain: dict[str, Any], max_iter: int = 15 + side: _Side, + problem: _GeneratorProblem, + chain: dict[str, Any], + max_iter: int = 15, + deadline: float = math.inf, ) -> tuple[dict[str, Any], list[np.ndarray]]: - """Projected gradient descent with the assignment held. Returns the improved exact chain (or the input) and the - moved atoms of steps that crossed a wall.""" + """Projected gradient descent with the assignment held, stopping at ``deadline``. Returns the improved exact + chain (or the input) and the moved atoms of steps that crossed a wall.""" atoms, assign, H = chain["atoms"], chain["assign"], chain["entropy"] crossed = [] for _ in range(max_iter): + if time.monotonic() > deadline: + break try: grad = _chamber_gradient(side, atoms, assign, chain["pi"]) except np.linalg.LinAlgError: break - B = _wall_tangent(side, atoms, assign) - if not B.shape[1]: + B = _wall_tangent(side, atoms, assign, deadline=deadline) + if B is None or not B.shape[1]: break g = B @ (B.T @ grad.ravel()) norm = np.linalg.norm(g) @@ -722,10 +739,12 @@ def _descend( if time.monotonic() > deadline: break improved = False - moved, crossed = _atom_step(side, problem, chain) + moved, crossed = _atom_step(side, problem, chain, deadline=deadline) if moved["entropy"] < chain["entropy"] - 1e-13: chain, improved = moved, True log.append(("atoms", chain["entropy"], len(chain["atoms"]), time.monotonic() - t0)) + if time.monotonic() > deadline: + break extra = [*chain["atoms"], *_images(side, chain["atoms"]), *[a for c in crossed[-3:] for a in c]] extra += _ray_exits(list(chain["atoms"]), _images(side, chain["atoms"]), faces, _N_RAYS // 2, rng) extra += _random_points(faces, 4, rng, side.n) diff --git a/tests/test_coupled_generators.py b/tests/test_coupled_generators.py index e27fee4..0fb8ec6 100644 --- a/tests/test_coupled_generators.py +++ b/tests/test_coupled_generators.py @@ -425,6 +425,29 @@ def counted(*args, **kwargs): assert calls["n"] <= 6 +def test_bilevel_search_stops_inside_an_iteration_at_the_deadline(monkeypatch: pytest.MonkeyPatch) -> None: + """Powell's callback comes once an iteration, after a line search along every logit; on a truncated build + with 69 reverse states the search ran 163 s past its share.""" + _, optima = cg.separating_optima(cg._GeneratorProblem(_rll()), starts=5, rng=np.random.default_rng(0)) + clock = {"now": 0.0} + calls = {"n": 0} + real = cg.generator_kernel + + def tick() -> float: + clock["now"] += 1.0 + return clock["now"] + + def counted(*args, **kwargs): + calls["n"] += 1 + return real(*args, **kwargs) + + monkeypatch.setattr(cg.time, "monotonic", tick) + monkeypatch.setattr(cg, "generator_kernel", counted) + out = cg.bilevel_search(_rll(), optima[:1], deadline=5.0) + assert len(out) == 1 + assert calls["n"] <= 6 + + def test_alm_polish_returns_at_an_expired_deadline() -> None: import time diff --git a/tests/test_generative_model.py b/tests/test_generative_model.py index 036669e..62f91a8 100644 --- a/tests/test_generative_model.py +++ b/tests/test_generative_model.py @@ -2,13 +2,76 @@ from __future__ import annotations +import time + import numpy as np import pytest from sofic.examples import golden_mean, golden_mean_bidirectional +from sofic.examples.epsilon_machines import from_symbol_matrices +from sofic.generators import generative_search as gs +from sofic.generators.bidirectional_build import try_build_bidirectional from sofic.generators.bidirectional_epsilon_machine import BidirectionalEpsilonMachine from sofic.generators.generative_search import generative_model, generative_model_from_bidirectional +# Lower bounds of the truncation that must not reach the result of a truncated build. +_TRUNCATION_BOUNDS = { + "excess entropy", + "exact rectangle partition", + "support bound", + "coverage bound (certified)", + "generator coverage bound (certified)", + "heaviest-term bound (certified)", + "generator heaviest-term bound (certified)", +} + + +def _truncated_forward(): + """A 2-state ternary process whose reverse ε-machine is infinite (s3-n2-t0022-d2 of the ternary survey).""" + mats = { + 0: np.array([[0.0, 0.0], [0.8718949197791982, 0.0]]), + 1: np.array([[0.2089291369568694, 0.0], [0.0, 0.05375082082018049]]), + 2: np.array([[0.0, 0.7910708630431306], [0.0, 0.07435425940062132]]), + } + return from_symbol_matrices((0, 1), (0, 1, 2), mats) + + +def test_a_prebuilt_truncation_is_classed_truncated() -> None: + built = try_build_bidirectional(_truncated_forward()) + assert built.preflight.bidir_class == "truncated" + bidir, meta = gs.resolve_bidirectional(built.bidir) + assert bidir is built.bidir + assert meta == {"bidir_class": "truncated", "source": "bidirectional input"} + + +def test_a_window_lower_bound_replaces_the_lower_bounds_of_the_machine() -> None: + result = gs._bracket_search( + golden_mean_bidirectional(), + objective="entropy", + stages=("machines",), + window_lower=(0.5, "a bound"), + rng=np.random.default_rng(0), + ) + assert (result.lower, result.lower_source, result.lower_certified) == (0.5, "a bound", True) + assert not result.certified + assert not {s["stage"] for s in result.stages} & _TRUNCATION_BOUNDS + + +@pytest.mark.slow +def test_a_truncated_build_reports_the_future_window_bound() -> None: + start = time.monotonic() + result = generative_model(_truncated_forward(), time_budget=60.0, rng=np.random.default_rng(0)) + assert time.monotonic() - start < 66.0 + assert result.stages[0]["bidir_class"] == "truncated" + assert result.lower_source.startswith("future-window generator coverage bound (L=") + # without a deadline the window bounds are 0.9978545 (L = 2) and 0.9981857 (L = 3); the best generator known + # has entropy 0.9982954 + assert 0.99 < result.lower < result.upper + assert not result.certified + assert not {s["stage"] for s in result.stages} & _TRUNCATION_BOUNDS + wyner = gs.minimal_wyner_model(_truncated_forward(), time_budget=20.0, rng=np.random.default_rng(0)) + assert (wyner.lower, wyner.lower_source) == (0.0, "trivial lower bound") + def test_generative_model_from_forward_epsilon_machine_certifies_golden_mean() -> None: forward = golden_mean(0.5) diff --git a/tests/test_simplex_chains.py b/tests/test_simplex_chains.py index 10f3694..a95f829 100644 --- a/tests/test_simplex_chains.py +++ b/tests/test_simplex_chains.py @@ -5,6 +5,7 @@ import functools import itertools import math +import time import numpy as np import pytest @@ -87,6 +88,25 @@ def test_chain_lemma_on_random_pools(seed, extra): assert ex["word_error"] < 1e-8 +def test_a_failed_least_squares_step_is_a_failed_snap(monkeypatch): + """LAPACK's SVD can fail to converge; the snap then reports an infinite residual instead of raising.""" + side = _sides()["forward"] + atoms = np.eye(side.n) + # one successor per block, so the wall residuals need no least squares and only the Gauss-Newton step does + assign = { + (s, x): (int(np.argmax(atoms[s] @ side.P[x])),) + for s, x in itertools.product(range(side.n), range(side.n_sym)) + if (atoms[s] @ side.P[x]).sum() > 1e-14 + } + + def fail(*args, **kwargs): + raise np.linalg.LinAlgError("SVD did not converge in Linear Least Squares") + + monkeypatch.setattr(np.linalg, "lstsq", fail) + _, res = sc._snap(side, 0.9 * atoms + 0.1 / side.n, assign) + assert res == math.inf + + def test_every_closed_class_of_the_full_vertex_chain_generates(): """The chain lemma with every block on all the vertices: ``T^x[s, .] = m_x(s) f_x(s)``.""" problem = _problem() @@ -157,21 +177,42 @@ def test_the_search_stops_at_the_target(): assert results[0].log[-1][0] == "restart vertices" # no restarts after the ε-machine's descent -@pytest.mark.filterwarnings("ignore:the reverse ε-machine of this process is infinite:RuntimeWarning") -def test_the_search_starts_from_the_epsilon_machine(): - """Two forward causal states and an infinite reverse ε-machine (53 states at the merge tolerance); the generative - complexity is the forward ε-machine's entropy.""" +@functools.cache +def _infinite_reverse_problem() -> _GeneratorProblem: + """Two forward causal states and an infinite reverse ε-machine (53 states at the merge tolerance).""" mats = { 0: np.array([[0.1317773554901893, 0.0], [0.3703792631454206, 0.0]]), 1: np.array([[0.1449685489375078, 0.0], [0.0, 0.39404348038124015]]), 2: np.array([[0.0, 0.7232540955723029], [0.0, 0.23557725647333932]]), } - problem = _GeneratorProblem(BidirectionalEpsilonMachine.from_forward(from_symbol_matrices((0, 1), (0, 1, 2), mats))) + return _GeneratorProblem(BidirectionalEpsilonMachine.from_forward(from_symbol_matrices((0, 1), (0, 1, 2), mats))) + + +@pytest.mark.filterwarnings("ignore:the reverse ε-machine of this process is infinite:RuntimeWarning") +def test_the_search_starts_from_the_epsilon_machine(): + """The generative complexity of this process is the forward ε-machine's entropy.""" + problem = _infinite_reverse_problem() (result,) = sc.simplex_chain_search(problem, sides=("forward",), seconds=0.0, restarts=0) assert result.entropy == pytest.approx(sc._entropy(_own_law(problem, "forward")), abs=1e-9) assert result.word_error < 1e-10 +def test_the_wall_tangent_stops_at_its_deadline(): + side = _sides()["forward"] + atoms, assign = np.eye(side.n), _full_blocks(side) + assert sc._wall_tangent(side, atoms, assign, deadline=time.monotonic() - 1.0) is None + assert sc._wall_tangent(side, atoms, assign) is not None + + +@pytest.mark.filterwarnings("ignore:the reverse ε-machine of this process is infinite:RuntimeWarning") +def test_the_search_keeps_its_time_on_a_large_side(): + """On the 53 reverse states one wall tangent took about a minute, past a 2 s budget (95 s in all).""" + problem = _infinite_reverse_problem() + start = time.monotonic() + sc.simplex_chain_search(problem, sides=("reverse",), seconds=2.0, rng=np.random.default_rng(0)) + assert time.monotonic() - start < 20.0 + + def test_the_pipeline_offers_the_simplex_chain_generators(): bidir = _problem().bidir kwargs = {"stages": ("machines", "chains"), "coverage": "off", "generator_heaviest_term": False}