omnibias.struct
Differentiable dynamic programs for sequences and parses, structured distributions, and finite-temperature bounds.
import omnibias.structUse struct for a supported sequence, path, alignment, or parsing dynamic program. State, transition, batch, length, and label axes differ across Viterbi, shortest-path, CTC, and inside-style operations; follow the selected module's layout exactly.
A soft dynamic program replaces a hard max or min with a finite-temperature operation. The value, marginals, and decoded hard structure answer different questions. Padding, unreachable states, empty inputs, and tie conventions can change both values and gradients.
Temperature hardening and the derivative tower used to differentiate the smooth relaxation are distinct mechanisms. Any soft-to-hard gap bound depends on the supported recurrence and its path-count or local-branching assumptions. Validate tiny cases against the included exhaustive references before scaling. This alpha package uses AGPL-or-commercial licensing.
Module contract & mathematical conventions
omnibias-struct: certified differentiable dynamic programming (Viterbi / shortest-path / CTC).
Exact hard DP is not differentiable -- its argmax gradient is a.e. zero -- so the
sound differentiable object is a **relaxation plus a certified gap**, never an exactness
claim. This package keeps two limits rigorously apart (conflating them is the contagious
mistake):
- **
beta -> inf(the temperature / relaxation axis).** The hardmaxcombine is replaced bylse_beta(a) = beta^-1 log sum_i exp(beta a_i); sincelse_beta >= maxandlse_beta -> maxasbeta -> inf, the soft DP anneals to exact hard DP. This is the *feasibility / temperature* sense of "collapse", the same axis asomnibias-discrete/omnibias-qubo/omnibias-routing-- **not** bias collapse. - **
delta -> 0(the founding bias collapse tower): the exact differentiation engine.** Pairwiselse_beta(a, b) = a + beta^-1 softplus(beta (b - a)), andsoftplusis Riccati with the closed-form towersoftplus^(n) = sigma^(n-1)inomnibias.core. Its beta-tempered tower propagated throughcompose_jet(omnibias.torch.jet/omnibias.jax.jet) yields the closed-form log-sum-exp / softmax jets; the first-order sensitivity is the softmax marginal, and the soft-DP gradient is the forward-backward path marginal assembled from it.
This module exposes the backend-agnostic surface (problem containers, exact hard DP,
brute-force oracles, and the closed-form gap certificate). The differentiable soft-DP
layers live under omnibias.struct.torch and omnibias.struct.jax
(algebraically corresponding twins).
Relation to omnibias-graph (decided: intentionally divergent). The beta-scaled
logsumexp_beta soft-DP here is a *different* operator from the tau-scaled
SoftSort / Sinkhorn / soft-top-k relaxations in omnibias.graph, not a shared
substrate: those relax *uncoupled* sorting / assignment / selection on a flat score
vector, whereas these relax the *coupled* marginals of an exponentially large
structured state space (a trellis / grammar / lattice) and carry a log(N)/beta gap
certificate. The two surfaces meet only at the trivial single-choice softmax case
and are deliberately kept apart.
important:
**Bit-parity with the PyTorch twin requires 64-bit JAX** -- jax.config.update("jax_enable_x64", True) before the first JAX array is created (or JAX_ENABLE_X64=1). JAX otherwise truncates to float32 while PyTorch uses float64, so the twins stay internally consistent but agree only to float32 tolerance. Where a value feeds a threshold, a rounding step or an argmax, that is enough to change the decision rather than just the last digits. See omnibias.jax.precision.
Numerical scope: shared coefficients and formulas do not establish universal floating-point identity across backends, devices, compiler transforms, or reduction orders. Compare the chosen path with dtype-appropriate tolerances; even float64 is not a general bitwise-equality guarantee. Algebraic initialization identities likewise need a numerical check for the selected coefficients and reduction order.
Shared formulas do not imply universal floating-point identity. Verify dtype, shape, derivative-order support, and the stated numerical assumptions for the path you use.
AlignmentLattice
omnibias.struct.AlignmentLatticeSource ↗class AlignmentLatticeDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
The (len_a + 1) x (len_b + 1) Needleman-Wunsch edit grid (diag / down / right).
Parameters
| Name | Type & default | Contract |
|---|---|---|
len_adataclass field | intRequired | See the operation contract and implementation below. |
len_bdataclass field | intRequired | See the operation contract and implementation below. |
Executed regression · hard align matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_align_matches_brute_force() -> None:
rng = np.random.default_rng(0)
sub = _blosum_like(4, rng)
gap = -1.0
for _ in range(5):
a = rng.integers(0, 4, size=int(rng.integers(2, 5)))
b = rng.integers(0, 4, size=int(rng.integers(2, 5)))
assert abs(hard_align(a, b, sub, gap) - brute_force_align(a, b, sub, gap)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_align.py::test_hard_align_matches_brute_force" -qRegression example · soft align certified gap
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_align_certified_gap() -> None:
rng = np.random.default_rng(2)
sub = _blosum_like(4, rng)
gap = -1.0
a = np.array([0, 1, 2, 3])
b = np.array([0, 2, 3])
st, gt = torch.tensor(sub), torch.tensor(gap)
hard = hard_align(a, b, sub, gap)
num_paths = AlignmentLattice(len(a), len(b)).build_dag()[0].count_paths()
prev = np.inf
for beta in (1.0, 2.0, 4.0, 8.0):
soft = float(talign.soft_align(a, b, st, gt, beta))
cert = certify_soft_dp(hard, soft, num_paths, beta, brute_force_value=brute_force_align(a, b, sub, gap))
assert cert.is_sound and cert.agrees_with_bruteforce
assert cert.absolute_gap <= prev + 1e-12
prev = cert.absolute_gappython -m pytest packages/omnibias-struct/tests/test_align.py -k test_soft_align_certified_gap -qFields & methods
len_afield
len_a: intDeclared int field on AlignmentLattice. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗len_bfield
len_b: intDeclared int field on AlignmentLattice. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
self.len_a < 1 or self.len_b < 1, raisesValueError(f'sequences must be non-empty, got {self.len_a}, {self.len_b}').
Executed regression · hard align matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_align_matches_brute_force() -> None:
rng = np.random.default_rng(0)
sub = _blosum_like(4, rng)
gap = -1.0
for _ in range(5):
a = rng.integers(0, 4, size=int(rng.integers(2, 5)))
b = rng.integers(0, 4, size=int(rng.integers(2, 5)))
assert abs(hard_align(a, b, sub, gap) - brute_force_align(a, b, sub, gap)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_align.py::test_hard_align_matches_brute_force" -qMethod implementation
def __post_init__(self) -> None:
if self.len_a < 1 or self.len_b < 1:
raise ValueError(f"sequences must be non-empty, got {self.len_a}, {self.len_b}")num_nodesproperty
num_nodes(self) -> intNumber of grid cells (len_a + 1) (len_b + 1).
Returns: int
Executed regression · hard align matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_align_matches_brute_force() -> None:
rng = np.random.default_rng(0)
sub = _blosum_like(4, rng)
gap = -1.0
for _ in range(5):
a = rng.integers(0, 4, size=int(rng.integers(2, 5)))
b = rng.integers(0, 4, size=int(rng.integers(2, 5)))
assert abs(hard_align(a, b, sub, gap) - brute_force_align(a, b, sub, gap)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_align.py::test_hard_align_matches_brute_force" -qMethod implementation
def num_nodes(self) -> int:
"""Number of grid cells ``(len_a + 1) (len_b + 1)``."""
return (self.len_a + 1) * (self.len_b + 1)nodemethod
node(self, i: int, j: int) -> intLinear (topological) index of grid cell (i, j).
Parameters
| Name | Type & default | Contract |
|---|---|---|
ipositional-or-keyword | intRequired | See the operation contract and implementation below. |
jpositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: int
Executed regression · hard align matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_align_matches_brute_force() -> None:
rng = np.random.default_rng(0)
sub = _blosum_like(4, rng)
gap = -1.0
for _ in range(5):
a = rng.integers(0, 4, size=int(rng.integers(2, 5)))
b = rng.integers(0, 4, size=int(rng.integers(2, 5)))
assert abs(hard_align(a, b, sub, gap) - brute_force_align(a, b, sub, gap)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_align.py::test_hard_align_matches_brute_force" -qMethod implementation
def node(self, i: int, j: int) -> int:
"""Linear (topological) index of grid cell ``(i, j)``."""
return i * (self.len_b + 1) + jbuild_dagmethod
build_dag(self) -> tuple[DAG, dict[tuple[int, int], EdgeLabel]]Return the alignment DAG (placeholder weights) + its edge-label map.
Returns: tuple[DAG, dict[tuple[int, int], EdgeLabel]]
Executed regression · hard align matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_align_matches_brute_force() -> None:
rng = np.random.default_rng(0)
sub = _blosum_like(4, rng)
gap = -1.0
for _ in range(5):
a = rng.integers(0, 4, size=int(rng.integers(2, 5)))
b = rng.integers(0, 4, size=int(rng.integers(2, 5)))
assert abs(hard_align(a, b, sub, gap) - brute_force_align(a, b, sub, gap)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_align.py::test_hard_align_matches_brute_force" -qMethod implementation
def build_dag(self) -> tuple[DAG, dict[tuple[int, int], EdgeLabel]]:
"""Return the alignment :class:`DAG` (placeholder weights) + its edge-label map."""
n, m = self.len_a, self.len_b
edges: dict[tuple[int, int], float] = {}
labels: dict[tuple[int, int], EdgeLabel] = {}
for i in range(n + 1):
for j in range(m + 1):
u = self.node(i, j)
if i < n and j < m:
e = (u, self.node(i + 1, j + 1))
edges[e], labels[e] = 0.0, ("sub", i, j)
if i < n:
e = (u, self.node(i + 1, j))
edges[e], labels[e] = 0.0, ("gap", i, -1)
if j < m:
e = (u, self.node(i, j + 1))
edges[e], labels[e] = 0.0, ("gap", -1, j)
dag = DAG(self.num_nodes, edges, source=self.node(0, 0), sink=self.node(n, m))
return dag, labelsedge_scoremethod
edge_score(self, label: EdgeLabel, a: NDArray[np.int_], b: NDArray[np.int_], sub: FloatArray, gap: float) -> floatScore of one edge given the substitution matrix and gap penalty.
Parameters
| Name | Type & default | Contract |
|---|---|---|
labelpositional-or-keyword | EdgeLabelRequired | See the operation contract and implementation below. |
apositional-or-keyword | NDArray[np.int_]Required | See the operation contract and implementation below. |
bpositional-or-keyword | NDArray[np.int_]Required | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gappositional-or-keyword | floatRequired | See the operation contract and implementation below. |
Returns: float
Executed regression · hard align matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_align_matches_brute_force() -> None:
rng = np.random.default_rng(0)
sub = _blosum_like(4, rng)
gap = -1.0
for _ in range(5):
a = rng.integers(0, 4, size=int(rng.integers(2, 5)))
b = rng.integers(0, 4, size=int(rng.integers(2, 5)))
assert abs(hard_align(a, b, sub, gap) - brute_force_align(a, b, sub, gap)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_align.py::test_hard_align_matches_brute_force" -qMethod implementation
def edge_score(self, label: EdgeLabel, a: NDArray[np.int_], b: NDArray[np.int_], sub: FloatArray, gap: float) -> float:
"""Score of one edge given the substitution matrix and gap penalty."""
kind, i, j = label
if kind == "sub":
return float(sub[int(a[i]), int(b[j])])
return float(gap)path_scoremethod
path_score(self, path: object, a: NDArray[np.int_], b: NDArray[np.int_], sub: FloatArray, gap: float) -> floatTotal alignment score of a source -> sink node path.
Parameters
| Name | Type & default | Contract |
|---|---|---|
pathpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
apositional-or-keyword | NDArray[np.int_]Required | See the operation contract and implementation below. |
bpositional-or-keyword | NDArray[np.int_]Required | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gappositional-or-keyword | floatRequired | See the operation contract and implementation below. |
Returns: float
Executed regression · hard align matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_align_matches_brute_force() -> None:
rng = np.random.default_rng(0)
sub = _blosum_like(4, rng)
gap = -1.0
for _ in range(5):
a = rng.integers(0, 4, size=int(rng.integers(2, 5)))
b = rng.integers(0, 4, size=int(rng.integers(2, 5)))
assert abs(hard_align(a, b, sub, gap) - brute_force_align(a, b, sub, gap)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_align.py::test_hard_align_matches_brute_force" -qMethod implementation
def path_score(self, path: object, a: NDArray[np.int_], b: NDArray[np.int_], sub: FloatArray, gap: float) -> float:
"""Total alignment score of a ``source -> sink`` node path."""
nodes = [int(x) for x in np.asarray(path, dtype=int).reshape(-1)]
_, labels = self.build_dag()
return float(sum(self.edge_score(labels[(nodes[k], nodes[k + 1])], a, b, sub, gap) for k in range(len(nodes) - 1)))Read the implementation
class AlignmentLattice:
r"""The ``(len_a + 1) x (len_b + 1)`` Needleman-Wunsch edit grid (diag / down / right)."""
len_a: int
len_b: int
def __post_init__(self) -> None:
if self.len_a < 1 or self.len_b < 1:
raise ValueError(f"sequences must be non-empty, got {self.len_a}, {self.len_b}")
@property
def num_nodes(self) -> int:
"""Number of grid cells ``(len_a + 1) (len_b + 1)``."""
return (self.len_a + 1) * (self.len_b + 1)
def node(self, i: int, j: int) -> int:
"""Linear (topological) index of grid cell ``(i, j)``."""
return i * (self.len_b + 1) + j
def build_dag(self) -> tuple[DAG, dict[tuple[int, int], EdgeLabel]]:
"""Return the alignment :class:`DAG` (placeholder weights) + its edge-label map."""
n, m = self.len_a, self.len_b
edges: dict[tuple[int, int], float] = {}
labels: dict[tuple[int, int], EdgeLabel] = {}
for i in range(n + 1):
for j in range(m + 1):
u = self.node(i, j)
if i < n and j < m:
e = (u, self.node(i + 1, j + 1))
edges[e], labels[e] = 0.0, ("sub", i, j)
if i < n:
e = (u, self.node(i + 1, j))
edges[e], labels[e] = 0.0, ("gap", i, -1)
if j < m:
e = (u, self.node(i, j + 1))
edges[e], labels[e] = 0.0, ("gap", -1, j)
dag = DAG(self.num_nodes, edges, source=self.node(0, 0), sink=self.node(n, m))
return dag, labels
def edge_score(self, label: EdgeLabel, a: NDArray[np.int_], b: NDArray[np.int_], sub: FloatArray, gap: float) -> float:
"""Score of one edge given the substitution matrix and gap penalty."""
kind, i, j = label
if kind == "sub":
return float(sub[int(a[i]), int(b[j])])
return float(gap)
def path_score(self, path: object, a: NDArray[np.int_], b: NDArray[np.int_], sub: FloatArray, gap: float) -> float:
"""Total alignment score of a ``source -> sink`` node path."""
nodes = [int(x) for x in np.asarray(path, dtype=int).reshape(-1)]
_, labels = self.build_dag()
return float(sum(self.edge_score(labels[(nodes[k], nodes[k + 1])], a, b, sub, gap) for k in range(len(nodes) - 1)))brute_force_align
omnibias.struct.brute_force_alignSource ↗brute_force_align(a: object, b: object, sub: FloatArray, gap: float) -> floatExact optimal alignment score by enumerating every monotonic path (oracle).
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | objectRequired | See the operation contract and implementation below. |
bpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gappositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExecuted regression · hard align matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_align_matches_brute_force() -> None:
rng = np.random.default_rng(0)
sub = _blosum_like(4, rng)
gap = -1.0
for _ in range(5):
a = rng.integers(0, 4, size=int(rng.integers(2, 5)))
b = rng.integers(0, 4, size=int(rng.integers(2, 5)))
assert abs(hard_align(a, b, sub, gap) - brute_force_align(a, b, sub, gap)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_align.py::test_hard_align_matches_brute_force" -qRegression example · soft align certified gap
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_align_certified_gap() -> None:
rng = np.random.default_rng(2)
sub = _blosum_like(4, rng)
gap = -1.0
a = np.array([0, 1, 2, 3])
b = np.array([0, 2, 3])
st, gt = torch.tensor(sub), torch.tensor(gap)
hard = hard_align(a, b, sub, gap)
num_paths = AlignmentLattice(len(a), len(b)).build_dag()[0].count_paths()
prev = np.inf
for beta in (1.0, 2.0, 4.0, 8.0):
soft = float(talign.soft_align(a, b, st, gt, beta))
cert = certify_soft_dp(hard, soft, num_paths, beta, brute_force_value=brute_force_align(a, b, sub, gap))
assert cert.is_sound and cert.agrees_with_bruteforce
assert cert.absolute_gap <= prev + 1e-12
prev = cert.absolute_gappython -m pytest packages/omnibias-struct/tests/test_align.py -k test_soft_align_certified_gap -qRead the implementation
def brute_force_align(a: object, b: object, sub: FloatArray, gap: float) -> float:
r"""Exact optimal alignment score by enumerating every monotonic path (oracle)."""
ai = np.asarray(a, dtype=int).reshape(-1)
bj = np.asarray(b, dtype=int).reshape(-1)
lattice = AlignmentLattice(ai.shape[0], bj.shape[0])
dag, _ = lattice.build_dag()
return max(lattice.path_score(p, ai, bj, np.asarray(sub, dtype=float), gap) for p in dag.enumerate_paths())brute_force_gotoh
omnibias.struct.brute_force_gotohSource ↗brute_force_gotoh(a: object, b: object, sub: FloatArray, gap_open: float, gap_extend: float) -> floatExact affine-gap score by enumerating every source -> sink path of the Gotoh DAG.
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | objectRequired | See the operation contract and implementation below. |
bpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gap_openpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
gap_extendpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExecuted regression · alignment hard equals brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_alignment_hard_equals_brute(kind: str, seed: int) -> None:
assert probe_align_oracle(kind, seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_alignment_hard_equals_brute[0-affine]" -qRegression example · hard gotoh matches brute force
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_gotoh_matches_brute_force(seed: int) -> None:
rng = np.random.default_rng(seed)
sub = _sub(4, rng)
a, b = _seqs(rng)
go, ge = -1.5, -0.4
assert abs(hard_gotoh(a, b, sub, go, ge) - brute_force_gotoh(a, b, sub, go, ge)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_align_local_affine.py -k test_hard_gotoh_matches_brute_force -qRead the implementation
def brute_force_gotoh(a: object, b: object, sub: FloatArray, gap_open: float, gap_extend: float) -> float:
r"""Exact affine-gap score by enumerating every ``source -> sink`` path of the Gotoh DAG."""
return float(np.max(_gotoh_path_scores(a, b, sub, gap_open, gap_extend)))brute_force_local_align
omnibias.struct.brute_force_local_alignSource ↗brute_force_local_align(a: object, b: object, sub: FloatArray, gap: float) -> floatExact local-alignment score by enumerating every augmented source -> sink path.
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | objectRequired | See the operation contract and implementation below. |
bpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gappositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExecuted regression · alignment hard equals brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_alignment_hard_equals_brute(kind: str, seed: int) -> None:
assert probe_align_oracle(kind, seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_alignment_hard_equals_brute[0-local]" -qRegression example · hard local matches brute force
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_local_matches_brute_force(seed: int) -> None:
rng = np.random.default_rng(seed)
sub = _sub(4, rng)
gap = -1.0
a, b = _seqs(rng)
assert abs(hard_local_align(a, b, sub, gap) - brute_force_local_align(a, b, sub, gap)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_align_local_affine.py -k test_hard_local_matches_brute_force -qRead the implementation
def brute_force_local_align(a: object, b: object, sub: FloatArray, gap: float) -> float:
r"""Exact local-alignment score by enumerating every augmented ``source -> sink`` path."""
return float(np.max(_local_path_scores(a, b, sub, gap)))brute_force_soft_align
omnibias.struct.brute_force_soft_alignSource ↗brute_force_soft_align(a: object, b: object, sub: FloatArray, gap: float, beta: float) -> floatExact soft alignment beta^-1 log sum_paths exp(beta score) (global softmax).
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | objectRequired | See the operation contract and implementation below. |
bpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gappositional-or-keyword | floatRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · soft align matches flat softmax and anneals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_align_matches_flat_softmax_and_anneals() -> None:
rng = np.random.default_rng(1)
sub = _blosum_like(4, rng)
gap = -1.0
a = np.array([0, 1, 2, 1])
b = np.array([0, 2, 1])
st, gt = torch.tensor(sub), torch.tensor(gap)
hard = hard_align(a, b, sub, gap)
for beta in (0.5, 1.0, 4.0, 16.0):
soft = float(talign.soft_align(a, b, st, gt, beta))
assert abs(soft - brute_force_soft_align(a, b, sub, gap, beta)) < 1e-9
assert soft >= hard - 1e-9 # softmax >= maxpython -m pytest "packages/omnibias-struct/tests/test_align.py::test_soft_align_matches_flat_softmax_and_anneals" -qRegression example · align value iv encloses brute force over box
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_align_value_iv_encloses_brute_force_over_box() -> None:
rng = np.random.default_rng(11)
k = 3
sub0 = rng.standard_normal((k, k))
gap0, radius, beta = -1.0, 0.2, 2.0
a, b = np.array([0, 1, 2]), np.array([0, 2])
iv = align_value_iv(a, b, box(sub0, radius), Interval(gap0 - radius, gap0 + radius), beta)
for _ in range(150):
subp = sub0 + rng.uniform(-radius, radius, sub0.shape)
gapp = gap0 + float(rng.uniform(-radius, radius))
assert iv.lo - TOL <= brute_force_soft_align(a, b, subp, gapp, beta) <= iv.hi + TOLpython -m pytest packages/omnibias-struct/tests/test_verified.py -k test_align_value_iv_encloses_brute_force_over_box -qRead the implementation
def brute_force_soft_align(a: object, b: object, sub: FloatArray, gap: float, beta: float) -> float:
r"""Exact soft alignment ``beta^-1 log sum_paths exp(beta score)`` (global softmax)."""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
ai = np.asarray(a, dtype=int).reshape(-1)
bj = np.asarray(b, dtype=int).reshape(-1)
lattice = AlignmentLattice(ai.shape[0], bj.shape[0])
dag, _ = lattice.build_dag()
s = np.asarray(sub, dtype=float)
scores = np.array([lattice.path_score(p, ai, bj, s, gap) for p in dag.enumerate_paths()])
mx = float(np.max(scores))
return mx + math.log(float(np.sum(np.exp(beta * (scores - mx))))) / betabrute_force_soft_gotoh
omnibias.struct.brute_force_soft_gotohSource ↗brute_force_soft_gotoh(a: object, b: object, sub: FloatArray, gap_open: float, gap_extend: float, beta: float) -> floatExact soft affine-gap alignment lse_beta over the Gotoh-lattice paths.
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | objectRequired | See the operation contract and implementation below. |
bpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gap_openpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
gap_extendpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · soft gotoh matches brute and anneals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_gotoh_matches_brute_and_anneals(seed: int) -> None:
rng = np.random.default_rng(seed)
sub = _sub(4, rng)
a, b = _seqs(rng)
go, ge = -1.5, -0.4
st = torch.tensor(sub)
hard = hard_gotoh(a, b, sub, go, ge)
for beta in (0.5, 1.0, 4.0, 16.0):
soft = float(talign.soft_gotoh(a, b, st, torch.tensor(go), torch.tensor(ge), beta))
assert abs(soft - brute_force_soft_gotoh(a, b, sub, go, ge, beta)) < 1e-9
assert soft >= hard - 1e-9python -m pytest "packages/omnibias-struct/tests/test_align_local_affine.py::test_soft_gotoh_matches_brute_and_anneals[0]" -qRead the implementation
def brute_force_soft_gotoh(
a: object, b: object, sub: FloatArray, gap_open: float, gap_extend: float, beta: float
) -> float:
r"""Exact soft affine-gap alignment ``lse_beta`` over the Gotoh-lattice paths."""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
scores = _gotoh_path_scores(a, b, sub, gap_open, gap_extend)
mx = float(np.max(scores))
return mx + math.log(float(np.sum(np.exp(beta * (scores - mx))))) / betabrute_force_soft_local_align
omnibias.struct.brute_force_soft_local_alignSource ↗brute_force_soft_local_align(a: object, b: object, sub: FloatArray, gap: float, beta: float) -> floatExact soft local alignment lse_beta over the augmented lattice paths.
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | objectRequired | See the operation contract and implementation below. |
bpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gappositional-or-keyword | floatRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · soft local matches brute and anneals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_local_matches_brute_and_anneals(seed: int) -> None:
rng = np.random.default_rng(seed)
sub = _sub(4, rng)
gap = -1.0
a, b = _seqs(rng)
st, gt = torch.tensor(sub), torch.tensor(gap)
hard = hard_local_align(a, b, sub, gap)
for beta in (0.5, 1.0, 4.0, 16.0):
soft = float(talign.soft_local_align(a, b, st, gt, beta))
assert abs(soft - brute_force_soft_local_align(a, b, sub, gap, beta)) < 1e-9
assert soft >= hard - 1e-9 # softmax >= maxpython -m pytest "packages/omnibias-struct/tests/test_align_local_affine.py::test_soft_local_matches_brute_and_anneals[0]" -qRead the implementation
def brute_force_soft_local_align(a: object, b: object, sub: FloatArray, gap: float, beta: float) -> float:
r"""Exact soft local alignment ``lse_beta`` over the augmented lattice paths."""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
scores = _local_path_scores(a, b, sub, gap)
mx = float(np.max(scores))
return mx + math.log(float(np.sum(np.exp(beta * (scores - mx))))) / betabuild_gotoh_dag
omnibias.struct.build_gotoh_dagSource ↗build_gotoh_dag(len_a: int, len_b: int) -> tuple[DAG, dict[tuple[int, int], AffineLabel]]Gotoh affine-gap DAG over match / x-gap / y-gap states (arity-1, topological).
States M[i, j] (match a[i-1] with b[j-1]), Ix[i, j] (gap in b,
consuming a[i-1]), Iy[i, j] (gap in a). A gap costs open + extend to start
(an ("open",) edge, taken from M *or the other gap state*) and extend to
continue (an ("extend",) edge). A longest source -> sink path is the Gotoh optimum;
on the shared shortest-path substrate the soft twin / marginals come for free.
Parameters
| Name | Type & default | Contract |
|---|---|---|
len_apositional-or-keyword | intRequired | See the operation contract and implementation below. |
len_bpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[DAG, dict[tuple[int, int], AffineLabel]]Explicit validation & failure cases
- When
len_a < 1 or len_b < 1, raisesValueError(f'sequences must be non-empty, got {len_a}, {len_b}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · alignment hard equals brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_alignment_hard_equals_brute(kind: str, seed: int) -> None:
assert probe_align_oracle(kind, seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_alignment_hard_equals_brute[0-affine]" -qRegression example · soft gotoh certified gap
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_gotoh_certified_gap() -> None:
rng = np.random.default_rng(2)
sub = _sub(4, rng)
a = np.array([0, 1, 2, 3])
b = np.array([0, 2, 3])
go, ge = -1.5, -0.4
st = torch.tensor(sub)
hard = hard_gotoh(a, b, sub, go, ge)
num_paths = build_gotoh_dag(len(a), len(b))[0].count_paths()
prev = np.inf
for beta in (1.0, 2.0, 4.0, 8.0):
soft = float(talign.soft_gotoh(a, b, st, torch.tensor(go), torch.tensor(ge), beta))
cert = certify_soft_dp(
hard, soft, num_paths, beta, brute_force_value=brute_force_gotoh(a, b, sub, go, ge)
)
assert cert.is_sound and cert.agrees_with_bruteforce
assert cert.absolute_gap <= prev + 1e-12
prev = cert.absolute_gappython -m pytest packages/omnibias-struct/tests/test_align_local_affine.py -k test_soft_gotoh_certified_gap -qRead the implementation
def build_gotoh_dag(len_a: int, len_b: int) -> tuple[DAG, dict[tuple[int, int], AffineLabel]]:
r"""Gotoh affine-gap DAG over match / x-gap / y-gap states (arity-1, topological).
States ``M[i, j]`` (match ``a[i-1]`` with ``b[j-1]``), ``Ix[i, j]`` (gap in ``b``,
consuming ``a[i-1]``), ``Iy[i, j]`` (gap in ``a``). A gap costs ``open + extend`` to start
(an ``("open",)`` edge, taken from ``M`` *or the other gap state*) and ``extend`` to
continue (an ``("extend",)`` edge). A longest ``source -> sink`` path is the Gotoh optimum;
on the shared shortest-path substrate the soft twin / marginals come for free.
"""
if len_a < 1 or len_b < 1:
raise ValueError(f"sequences must be non-empty, got {len_a}, {len_b}")
n, m = len_a, len_b
nodes: dict[tuple[str, int, int], bool] = {}
def m_ok(i: int, j: int) -> bool:
return (i, j) == (0, 0) or (i >= 1 and j >= 1)
for i in range(n + 1):
for j in range(m + 1):
if m_ok(i, j):
nodes[("M", i, j)] = True
if i >= 1:
nodes[("Ix", i, j)] = True
if j >= 1:
nodes[("Iy", i, j)] = True
ordered = sorted(nodes, key=lambda k: (k[1] + k[2], {"M": 0, "Ix": 1, "Iy": 2}[k[0]], k[1]))
node_id: dict[tuple[str, int, int], int] = {}
idx = 1 # 0 reserved for the source
for key in ordered:
node_id[key] = idx
idx += 1
source = 0
sink = idx
edges: dict[tuple[int, int], float] = {}
labels: dict[tuple[int, int], AffineLabel] = {}
free: AffineLabel = ("free", -1, -1)
edges[(source, node_id[("M", 0, 0)])] = 0.0
labels[(source, node_id[("M", 0, 0)])] = free
for (state, i, j), nid in node_id.items():
if state == "M":
if (i, j) == (0, 0):
continue
lab: AffineLabel = ("sub", i - 1, j - 1)
for pred in (("M", i - 1, j - 1), ("Ix", i - 1, j - 1), ("Iy", i - 1, j - 1)):
if pred in node_id:
edges[(node_id[pred], nid)] = 0.0
labels[(node_id[pred], nid)] = lab
elif state == "Ix":
if ("M", i - 1, j) in node_id:
edges[(node_id[("M", i - 1, j)], nid)] = 0.0
labels[(node_id[("M", i - 1, j)], nid)] = ("open", -1, -1)
if ("Ix", i - 1, j) in node_id:
edges[(node_id[("Ix", i - 1, j)], nid)] = 0.0
labels[(node_id[("Ix", i - 1, j)], nid)] = ("extend", -1, -1)
if ("Iy", i - 1, j) in node_id:
edges[(node_id[("Iy", i - 1, j)], nid)] = 0.0
labels[(node_id[("Iy", i - 1, j)], nid)] = ("open", -1, -1)
else: # Iy
if ("M", i, j - 1) in node_id:
edges[(node_id[("M", i, j - 1)], nid)] = 0.0
labels[(node_id[("M", i, j - 1)], nid)] = ("open", -1, -1)
if ("Iy", i, j - 1) in node_id:
edges[(node_id[("Iy", i, j - 1)], nid)] = 0.0
labels[(node_id[("Iy", i, j - 1)], nid)] = ("extend", -1, -1)
if ("Ix", i, j - 1) in node_id:
edges[(node_id[("Ix", i, j - 1)], nid)] = 0.0
labels[(node_id[("Ix", i, j - 1)], nid)] = ("open", -1, -1)
for state in ("M", "Ix", "Iy"):
key = (state, n, m)
if key in node_id:
edges[(node_id[key], sink)] = 0.0
labels[(node_id[key], sink)] = free
dag = DAG(sink + 1, edges, source=source, sink=sink)
return dag, labelsbuild_local_dag
omnibias.struct.build_local_dagSource ↗build_local_dag(len_a: int, len_b: int) -> tuple[DAG, dict[tuple[int, int], EdgeLabel]]Smith-Waterman local-alignment DAG: the NW grid plus free source -> cell and
cell -> sink 0-edges (and an empty source -> sink edge, the score-0 floor).
A longest source -> sink path therefore starts and ends at *any* cell for free, i.e.
scores the best local (substring) alignment -- exactly Smith-Waterman -- on the same
shortest-path substrate as AlignmentLattice.
Parameters
| Name | Type & default | Contract |
|---|---|---|
len_apositional-or-keyword | intRequired | See the operation contract and implementation below. |
len_bpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[DAG, dict[tuple[int, int], EdgeLabel]]Explicit validation & failure cases
- When
len_a < 1 or len_b < 1, raisesValueError(f'sequences must be non-empty, got {len_a}, {len_b}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · alignment hard equals brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_alignment_hard_equals_brute(kind: str, seed: int) -> None:
assert probe_align_oracle(kind, seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_alignment_hard_equals_brute[0-local]" -qRegression example · soft local certified gap
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_local_certified_gap() -> None:
rng = np.random.default_rng(2)
sub = _sub(4, rng)
gap = -1.0
a = np.array([0, 1, 2, 3])
b = np.array([0, 2, 3])
st, gt = torch.tensor(sub), torch.tensor(gap)
hard = hard_local_align(a, b, sub, gap)
num_paths = build_local_dag(len(a), len(b))[0].count_paths()
prev = np.inf
for beta in (1.0, 2.0, 4.0, 8.0):
soft = float(talign.soft_local_align(a, b, st, gt, beta))
cert = certify_soft_dp(
hard, soft, num_paths, beta, brute_force_value=brute_force_local_align(a, b, sub, gap)
)
assert cert.is_sound and cert.agrees_with_bruteforce
assert cert.absolute_gap <= prev + 1e-12
prev = cert.absolute_gappython -m pytest packages/omnibias-struct/tests/test_align_local_affine.py -k test_soft_local_certified_gap -qRead the implementation
def build_local_dag(len_a: int, len_b: int) -> tuple[DAG, dict[tuple[int, int], EdgeLabel]]:
r"""Smith-Waterman local-alignment DAG: the NW grid plus free ``source -> cell`` and
``cell -> sink`` 0-edges (and an empty ``source -> sink`` edge, the score-``0`` floor).
A longest ``source -> sink`` path therefore starts and ends at *any* cell for free, i.e.
scores the best local (substring) alignment -- exactly Smith-Waterman -- on the same
shortest-path substrate as :class:`AlignmentLattice`.
"""
if len_a < 1 or len_b < 1:
raise ValueError(f"sequences must be non-empty, got {len_a}, {len_b}")
n, m = len_a, len_b
def cell(i: int, j: int) -> int:
return 1 + i * (m + 1) + j
source = 0
sink = 1 + (n + 1) * (m + 1)
edges: dict[tuple[int, int], float] = {}
labels: dict[tuple[int, int], EdgeLabel] = {}
free: EdgeLabel = ("free", -1, -1)
for i in range(n + 1):
for j in range(m + 1):
u = cell(i, j)
if i < n and j < m:
e = (u, cell(i + 1, j + 1))
edges[e], labels[e] = 0.0, ("sub", i, j)
if i < n:
e = (u, cell(i + 1, j))
edges[e], labels[e] = 0.0, ("gap", i, -1)
if j < m:
e = (u, cell(i, j + 1))
edges[e], labels[e] = 0.0, ("gap", -1, j)
edges[(source, u)], labels[(source, u)] = 0.0, free # free local start
edges[(u, sink)], labels[(u, sink)] = 0.0, free # free local end
edges[(source, sink)], labels[(source, sink)] = 0.0, free # empty alignment (score-0 floor)
dag = DAG(sink + 1, edges, source=source, sink=sink)
return dag, labelshard_align
omnibias.struct.hard_alignSource ↗hard_align(a: object, b: object, sub: FloatArray, gap: float) -> floatClassic Needleman-Wunsch optimal global-alignment score (max-score DP).
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | objectRequired | See the operation contract and implementation below. |
bpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gappositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExecuted regression · hard align matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_align_matches_brute_force() -> None:
rng = np.random.default_rng(0)
sub = _blosum_like(4, rng)
gap = -1.0
for _ in range(5):
a = rng.integers(0, 4, size=int(rng.integers(2, 5)))
b = rng.integers(0, 4, size=int(rng.integers(2, 5)))
assert abs(hard_align(a, b, sub, gap) - brute_force_align(a, b, sub, gap)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_align.py::test_hard_align_matches_brute_force" -qRegression example · soft align matches flat softmax and anneals
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_align_matches_flat_softmax_and_anneals() -> None:
rng = np.random.default_rng(1)
sub = _blosum_like(4, rng)
gap = -1.0
a = np.array([0, 1, 2, 1])
b = np.array([0, 2, 1])
st, gt = torch.tensor(sub), torch.tensor(gap)
hard = hard_align(a, b, sub, gap)
for beta in (0.5, 1.0, 4.0, 16.0):
soft = float(talign.soft_align(a, b, st, gt, beta))
assert abs(soft - brute_force_soft_align(a, b, sub, gap, beta)) < 1e-9
assert soft >= hard - 1e-9 # softmax >= maxpython -m pytest packages/omnibias-struct/tests/test_align.py -k test_soft_align_matches_flat_softmax_and_anneals -qRead the implementation
def hard_align(a: object, b: object, sub: FloatArray, gap: float) -> float:
r"""Classic Needleman-Wunsch optimal global-alignment score (max-score DP)."""
ai = np.asarray(a, dtype=int).reshape(-1)
bj = np.asarray(b, dtype=int).reshape(-1)
s = np.asarray(sub, dtype=float)
n, m = ai.shape[0], bj.shape[0]
h = np.full((n + 1, m + 1), -np.inf)
h[0, 0] = 0.0
for i in range(n + 1):
for j in range(m + 1):
if i == 0 and j == 0:
continue
best = -np.inf
if i > 0 and j > 0:
best = max(best, h[i - 1, j - 1] + s[ai[i - 1], bj[j - 1]])
if i > 0:
best = max(best, h[i - 1, j] + gap)
if j > 0:
best = max(best, h[i, j - 1] + gap)
h[i, j] = best
return float(h[n, m])hard_gotoh
omnibias.struct.hard_gotohSource ↗hard_gotoh(a: object, b: object, sub: FloatArray, gap_open: float, gap_extend: float) -> floatClassic Gotoh optimal global affine-gap alignment score (3-matrix max DP).
A gap of length L costs gap_open + L * gap_extend (one open per maximal run,
including runs that immediately follow a gap of the other type).
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | objectRequired | See the operation contract and implementation below. |
bpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gap_openpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
gap_extendpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExecuted regression · alignment hard equals brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_alignment_hard_equals_brute(kind: str, seed: int) -> None:
assert probe_align_oracle(kind, seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_alignment_hard_equals_brute[0-affine]" -qRegression example · hard gotoh matches brute force
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_gotoh_matches_brute_force(seed: int) -> None:
rng = np.random.default_rng(seed)
sub = _sub(4, rng)
a, b = _seqs(rng)
go, ge = -1.5, -0.4
assert abs(hard_gotoh(a, b, sub, go, ge) - brute_force_gotoh(a, b, sub, go, ge)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_align_local_affine.py -k test_hard_gotoh_matches_brute_force -qRead the implementation
def hard_gotoh(a: object, b: object, sub: FloatArray, gap_open: float, gap_extend: float) -> float:
r"""Classic Gotoh optimal global affine-gap alignment score (3-matrix max DP).
A gap of length ``L`` costs ``gap_open + L * gap_extend`` (one open per maximal run,
including runs that immediately follow a gap of the other type).
"""
ai = np.asarray(a, dtype=int).reshape(-1)
bj = np.asarray(b, dtype=int).reshape(-1)
s = np.asarray(sub, dtype=float)
n, m = ai.shape[0], bj.shape[0]
neg = -np.inf
o = gap_open + gap_extend
mm = np.full((n + 1, m + 1), neg)
ix = np.full((n + 1, m + 1), neg)
iy = np.full((n + 1, m + 1), neg)
mm[0, 0] = 0.0
for i in range(n + 1):
for j in range(m + 1):
if i >= 1 and j >= 1:
mm[i, j] = s[ai[i - 1], bj[j - 1]] + max(mm[i - 1, j - 1], ix[i - 1, j - 1], iy[i - 1, j - 1])
if i >= 1:
ix[i, j] = max(mm[i - 1, j] + o, ix[i - 1, j] + gap_extend, iy[i - 1, j] + o)
if j >= 1:
iy[i, j] = max(mm[i, j - 1] + o, iy[i, j - 1] + gap_extend, ix[i, j - 1] + o)
return float(max(mm[n, m], ix[n, m], iy[n, m]))hard_local_align
omnibias.struct.hard_local_alignSource ↗hard_local_align(a: object, b: object, sub: FloatArray, gap: float) -> floatClassic Smith-Waterman optimal local-alignment score (max-score DP with a 0 floor).
Parameters
| Name | Type & default | Contract |
|---|---|---|
apositional-or-keyword | objectRequired | See the operation contract and implementation below. |
bpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
subpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
gappositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExecuted regression · alignment hard equals brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_alignment_hard_equals_brute(kind: str, seed: int) -> None:
assert probe_align_oracle(kind, seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_alignment_hard_equals_brute[0-local]" -qRegression example · hard local matches brute force
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_local_matches_brute_force(seed: int) -> None:
rng = np.random.default_rng(seed)
sub = _sub(4, rng)
gap = -1.0
a, b = _seqs(rng)
assert abs(hard_local_align(a, b, sub, gap) - brute_force_local_align(a, b, sub, gap)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_align_local_affine.py -k test_hard_local_matches_brute_force -qRead the implementation
def hard_local_align(a: object, b: object, sub: FloatArray, gap: float) -> float:
r"""Classic Smith-Waterman optimal local-alignment score (max-score DP with a ``0`` floor)."""
ai = np.asarray(a, dtype=int).reshape(-1)
bj = np.asarray(b, dtype=int).reshape(-1)
s = np.asarray(sub, dtype=float)
n, m = ai.shape[0], bj.shape[0]
h = np.zeros((n + 1, m + 1))
best = 0.0
for i in range(1, n + 1):
for j in range(1, m + 1):
h[i, j] = max(
0.0,
h[i - 1, j - 1] + s[ai[i - 1], bj[j - 1]],
h[i - 1, j] + gap,
h[i, j - 1] + gap,
)
best = max(best, float(h[i, j]))
return bestDPGapCertificate
omnibias.struct.DPGapCertificateSource ↗class DPGapCertificateDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
A closed-form sandwich certificate for a soft-DP value against the hard optimum.
Attributes
hard_value: The hard DP optimum V* (max score, or min cost when sense == "min").
soft_value: The soft lse_beta value V_beta from the differentiable backend.
gap_bound: The rigorous closed-form gap log(num_paths) / beta.
beta: The inverse temperature used for the relaxation.
num_paths: The exact number N of complete paths / alignments.
sense: "max" (Viterbi / longest / CTC) or "min" (shortest path).
method: Always "logsumexp_gap" -- the closed-form bound (no optimization).
agrees_with_bruteforce: True / False if a brute-force optimum was supplied and matched (the exact-DP self-check), else None.
tol: Numerical tolerance for the sandwich checks.
Parameters
| Name | Type & default | Contract |
|---|---|---|
hard_valuedataclass field | floatRequired | The hard DP optimum V* (max score, or min cost when sense == "min"). |
soft_valuedataclass field | floatRequired | The soft lse_beta value V_beta from the differentiable backend. |
gap_bounddataclass field | floatRequired | The rigorous closed-form gap log(num_paths) / beta. |
betadataclass field | floatRequired | The inverse temperature used for the relaxation. |
num_pathsdataclass field | intRequired | The exact number N of complete paths / alignments. |
sensedataclass field | strDefault: 'max' | "max" (Viterbi / longest / CTC) or "min" (shortest path). |
methoddataclass field | strDefault: 'logsumexp_gap' | Always "logsumexp_gap" -- the closed-form bound (no optimization). |
agrees_with_bruteforcedataclass field | bool | NoneDefault: None | True / False if a brute-force optimum was supplied and matched (the exact-DP self-check), else None. |
toldataclass field | floatDefault: 1e-09 | Numerical tolerance for the sandwich checks. |
Executed regression · family gap sandwich is sound
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_family_gap_sandwich_is_sound(probe) -> None: # noqa: ANN001
pytest.importorskip("torch")
rec = probe(0, BETA, "torch")
assert rec.ok
assert rec.metrics["realized_gap"] <= rec.metrics["bound"] + 1e-9python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_family_gap_sandwich_is_sound[probe_eisner_gap]" -qFields & methods
hard_valuefield
hard_value: floatThe hard DP optimum V* (max score, or min cost when sense == "min").
soft_valuefield
soft_value: floatThe soft lse_beta value V_beta from the differentiable backend.
methodfield
method: str = 'logsumexp_gap'Always "logsumexp_gap" -- the closed-form bound (no optimization).
agrees_with_bruteforcefield
agrees_with_bruteforce: bool | None = NoneTrue / False if a brute-force optimum was supplied and matched (the exact-DP self-check), else None.
lse_ge_max_holdsproperty
lse_ge_max_holds(self) -> boolWhether the lse_beta >= max side holds (<= for the min sense).
Returns: bool
Executed regression · family gap sandwich is sound
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_family_gap_sandwich_is_sound(probe) -> None: # noqa: ANN001
pytest.importorskip("torch")
rec = probe(0, BETA, "torch")
assert rec.ok
assert rec.metrics["realized_gap"] <= rec.metrics["bound"] + 1e-9python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_family_gap_sandwich_is_sound[probe_eisner_gap]" -qMethod implementation
def lse_ge_max_holds(self) -> bool:
"""Whether the ``lse_beta >= max`` side holds (``<=`` for the ``min`` sense)."""
if self.sense == "min":
return self.soft_value <= self.hard_value + self.tol
return self.soft_value >= self.hard_value - self.tolgap_bound_holdsproperty
gap_bound_holds(self) -> boolWhether the soft value stays within gap_bound of the hard optimum.
Returns: bool
Executed regression · family gap sandwich is sound
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_family_gap_sandwich_is_sound(probe) -> None: # noqa: ANN001
pytest.importorskip("torch")
rec = probe(0, BETA, "torch")
assert rec.ok
assert rec.metrics["realized_gap"] <= rec.metrics["bound"] + 1e-9python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_family_gap_sandwich_is_sound[probe_eisner_gap]" -qMethod implementation
def gap_bound_holds(self) -> bool:
"""Whether the soft value stays within ``gap_bound`` of the hard optimum."""
if self.sense == "min":
return self.soft_value >= self.hard_value - self.gap_bound - self.tol
return self.soft_value <= self.hard_value + self.gap_bound + self.tolabsolute_gapproperty
absolute_gap(self) -> floatThe realized |V_beta - V*| (<= gap_bound when sound).
Returns: float
Executed regression · family gap sandwich is sound
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_family_gap_sandwich_is_sound(probe) -> None: # noqa: ANN001
pytest.importorskip("torch")
rec = probe(0, BETA, "torch")
assert rec.ok
assert rec.metrics["realized_gap"] <= rec.metrics["bound"] + 1e-9python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_family_gap_sandwich_is_sound[probe_eisner_gap]" -qMethod implementation
def absolute_gap(self) -> float:
"""The realized ``|V_beta - V*|`` (``<= gap_bound`` when sound)."""
return abs(self.soft_value - self.hard_value)is_soundproperty
is_sound(self) -> boolWhether the full closed-form sandwich holds for the measured values.
Returns: bool
Executed regression · family gap sandwich is sound
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_family_gap_sandwich_is_sound(probe) -> None: # noqa: ANN001
pytest.importorskip("torch")
rec = probe(0, BETA, "torch")
assert rec.ok
assert rec.metrics["realized_gap"] <= rec.metrics["bound"] + 1e-9python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_family_gap_sandwich_is_sound[probe_eisner_gap]" -qMethod implementation
def is_sound(self) -> bool:
"""Whether the full closed-form sandwich holds for the measured values."""
return self.lse_ge_max_holds and self.gap_bound_holdscertifiedproperty
certified(self) -> boolWhether a rigorous closed-form gap was produced *and* the sandwich holds.
Returns: bool
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qMethod implementation
def certified(self) -> bool:
"""Whether a rigorous closed-form gap was produced *and* the sandwich holds."""
return "logsumexp_gap" in self.method and self.is_soundRead the implementation
class DPGapCertificate:
r"""A closed-form sandwich certificate for a soft-DP value against the hard optimum.
Attributes
----------
hard_value:
The hard DP optimum ``V*`` (max score, or min cost when ``sense == "min"``).
soft_value:
The soft ``lse_beta`` value ``V_beta`` from the differentiable backend.
gap_bound:
The rigorous closed-form gap ``log(num_paths) / beta``.
beta:
The inverse temperature used for the relaxation.
num_paths:
The exact number ``N`` of complete paths / alignments.
sense:
``"max"`` (Viterbi / longest / CTC) or ``"min"`` (shortest path).
method:
Always ``"logsumexp_gap"`` -- the closed-form bound (no optimization).
agrees_with_bruteforce:
``True`` / ``False`` if a brute-force optimum was supplied and matched (the
exact-DP self-check), else ``None``.
tol:
Numerical tolerance for the sandwich checks.
"""
hard_value: float
soft_value: float
gap_bound: float
beta: float
num_paths: int
sense: str = "max"
method: str = "logsumexp_gap"
agrees_with_bruteforce: bool | None = None
tol: float = 1e-9
@property
def lse_ge_max_holds(self) -> bool:
"""Whether the ``lse_beta >= max`` side holds (``<=`` for the ``min`` sense)."""
if self.sense == "min":
return self.soft_value <= self.hard_value + self.tol
return self.soft_value >= self.hard_value - self.tol
@property
def gap_bound_holds(self) -> bool:
"""Whether the soft value stays within ``gap_bound`` of the hard optimum."""
if self.sense == "min":
return self.soft_value >= self.hard_value - self.gap_bound - self.tol
return self.soft_value <= self.hard_value + self.gap_bound + self.tol
@property
def absolute_gap(self) -> float:
"""The realized ``|V_beta - V*|`` (``<= gap_bound`` when sound)."""
return abs(self.soft_value - self.hard_value)
@property
def is_sound(self) -> bool:
"""Whether the full closed-form sandwich holds for the measured values."""
return self.lse_ge_max_holds and self.gap_bound_holds
@property
def certified(self) -> bool:
"""Whether a rigorous closed-form gap was produced *and* the sandwich holds."""
return "logsumexp_gap" in self.method and self.is_soundcertify_soft_dp
omnibias.struct.certify_soft_dpSource ↗certify_soft_dp(hard_value: float, soft_value: float, num_paths: int, beta: float, *, sense: str='max', stepwise_bound: float | None=None, brute_force_value: float | None=None, tol: float=1e-09) -> DPGapCertificateBuild a DPGapCertificate sandwiching soft_value and hard_value.
Parameters
hard_value: The hard DP optimum V* (from omnibias.struct.viterbi etc.).
soft_value: The soft lse_beta value V_beta (from a backend soft_*).
num_paths: The exact path count N (omnibias.struct.count_paths); must be >= 1 (a problem with no complete paths is infeasible and cannot be certified).
beta: The inverse temperature beta > 0.
sense: "max" (default) or "min".
stepwise_bound: Optional tighter per-step bound (omnibias.struct.stepwise_gap_bound); when given, the certified gap_bound is the (still-sound) minimum of it and the global log(N) / beta, and method records the tightening.
brute_force_value: Optional exact-DP oracle value; when given, agrees_with_bruteforce records whether hard_value matched it within tol.
tol: Numerical tolerance for the sandwich / agreement checks.
Parameters
| Name | Type & default | Contract |
|---|---|---|
hard_valuepositional-or-keyword | floatRequired | The hard DP optimum V* (from omnibias.struct.viterbi etc.). |
soft_valuepositional-or-keyword | floatRequired | The soft lse_beta value V_beta (from a backend soft_*). |
num_pathspositional-or-keyword | intRequired | The exact path count N (omnibias.struct.count_paths); must be >= 1 (a problem with no complete paths is infeasible and cannot be certified). |
betapositional-or-keyword | floatRequired | The inverse temperature beta > 0. |
sensekeyword-only | strDefault: 'max' | "max" (default) or "min". |
stepwise_boundkeyword-only | float | NoneDefault: None | Optional tighter per-step bound (omnibias.struct.stepwise_gap_bound); when given, the certified gap_bound is the (still-sound) minimum of it and the global log(N) / beta, and method records the tightening. |
brute_force_valuekeyword-only | float | NoneDefault: None | Optional exact-DP oracle value; when given, agrees_with_bruteforce records whether hard_value matched it within tol. |
tolkeyword-only | floatDefault: 1e-09 | Numerical tolerance for the sandwich / agreement checks. |
DPGapCertificateExplicit validation & failure cases
- When
sense not in ('max', 'min'), raisesValueError(f"sense must be 'max' or 'min', got {sense!r}"). - When
num_paths < 1, raisesValueError(f'no complete paths (num_paths={num_paths}); the problem is infeasible and cannot be certified').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · certificate rejects bad sense
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_rejects_bad_sense() -> None:
with pytest.raises(ValueError, match="sense"):
certify_soft_dp(0.0, 0.0, 1, 1.0, sense="argmax")python -m pytest "packages/omnibias-struct/tests/test_certificate.py::test_certificate_rejects_bad_sense" -qRegression example · certify rejects infeasible zero path problem
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certify_rejects_infeasible_zero_path_problem() -> None:
with pytest.raises(ValueError, match="infeasible"):
certify_soft_dp(0.0, 0.0, 0, 4.0)python -m pytest packages/omnibias-struct/tests/test_core_harden.py -k test_certify_rejects_infeasible_zero_path_problem -qRead the implementation
def certify_soft_dp(
hard_value: float,
soft_value: float,
num_paths: int,
beta: float,
*,
sense: str = "max",
stepwise_bound: float | None = None,
brute_force_value: float | None = None,
tol: float = 1e-9,
) -> DPGapCertificate:
r"""Build a :class:`DPGapCertificate` sandwiching ``soft_value`` and ``hard_value``.
Parameters
----------
hard_value:
The hard DP optimum ``V*`` (from :func:`omnibias.struct.viterbi` etc.).
soft_value:
The soft ``lse_beta`` value ``V_beta`` (from a backend ``soft_*``).
num_paths:
The exact path count ``N`` (:func:`omnibias.struct.count_paths`); must be ``>= 1``
(a problem with no complete paths is infeasible and cannot be certified).
beta:
The inverse temperature ``beta > 0``.
sense:
``"max"`` (default) or ``"min"``.
stepwise_bound:
Optional tighter per-step bound (:func:`omnibias.struct.stepwise_gap_bound`); when
given, the certified ``gap_bound`` is the (still-sound) minimum of it and the
global ``log(N) / beta``, and ``method`` records the tightening.
brute_force_value:
Optional exact-DP oracle value; when given, ``agrees_with_bruteforce`` records
whether ``hard_value`` matched it within ``tol``.
tol:
Numerical tolerance for the sandwich / agreement checks.
"""
if sense not in ("max", "min"):
raise ValueError(f"sense must be 'max' or 'min', got {sense!r}")
if num_paths < 1:
raise ValueError(
f"no complete paths (num_paths={num_paths}); the problem is infeasible and "
"cannot be certified"
)
global_bound = logsumexp_gap_bound(num_paths, beta)
if stepwise_bound is None:
gap_bound, method = global_bound, "logsumexp_gap"
else:
gap_bound = min(global_bound, float(stepwise_bound))
method = "min(logsumexp_gap, stepwise)"
agrees = None if brute_force_value is None else abs(hard_value - brute_force_value) <= tol
return DPGapCertificate(
hard_value=float(hard_value),
soft_value=float(soft_value),
gap_bound=float(gap_bound),
beta=float(beta),
num_paths=int(num_paths),
sense=sense,
method=method,
agrees_with_bruteforce=agrees,
tol=float(tol),
)DTWLattice
omnibias.struct.DTWLatticeSource ↗class DTWLatticeDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
The (n_rows, n_cols) monotonic warping grid (steps: down, right, diagonal).
Pure structure -- the differentiable soft DTW consumes a backend cost tensor alongside
the lattice shape, exactly as ~omnibias.struct.ChainTrellis pairs with backend
emissions. Intended for tiny grids (the brute-force oracle is exponential).
Parameters
| Name | Type & default | Contract |
|---|---|---|
n_rowsdataclass field | intRequired | See the operation contract and implementation below. |
n_colsdataclass field | intRequired | See the operation contract and implementation below. |
Executed regression · hard dtw matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_dtw_matches_brute_force() -> None:
rng = np.random.default_rng(0)
for n, m in ((3, 3), (4, 2), (2, 5), (4, 4)):
cost = _cost(rng, n, m)
assert abs(hard_dtw(cost) - brute_force_dtw(cost)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_dtw.py::test_hard_dtw_matches_brute_force" -qRegression example · soft dtw sandwiches hard dtw with log n gap
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_dtw_sandwiches_hard_dtw_with_log_n_gap() -> None:
rng = np.random.default_rng(2)
cost = _cost(rng, 4, 4)
ct = torch.tensor(cost)
hard = hard_dtw(cost)
num_paths = DTWLattice(4, 4).count_paths()
prev_gap = np.inf
for beta in (1.0, 2.0, 4.0, 8.0, 16.0):
soft = float(tdtw.soft_dtw(ct, beta))
cert = certify_soft_dp(hard, soft, num_paths, beta, sense="min", brute_force_value=brute_force_dtw(cost))
assert cert.is_sound # V* - log(N)/beta <= V_beta <= V*
assert cert.agrees_with_bruteforce
assert soft <= hard + 1e-9 # softmin never exceeds the hard min
assert cert.absolute_gap <= prev_gap + 1e-12 # gap shrinks with beta
prev_gap = cert.absolute_gappython -m pytest packages/omnibias-struct/tests/test_dtw.py -k test_soft_dtw_sandwiches_hard_dtw_with_log_n_gap -qFields & methods
n_rowsfield
n_rows: intDeclared int field on DTWLattice. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗n_colsfield
n_cols: intDeclared int field on DTWLattice. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
self.n_rows < 1 or self.n_cols < 1, raisesValueError(f'lattice must be at least 1x1, got {self.n_rows}x{self.n_cols}').
Executed regression · hard dtw matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_dtw_matches_brute_force() -> None:
rng = np.random.default_rng(0)
for n, m in ((3, 3), (4, 2), (2, 5), (4, 4)):
cost = _cost(rng, n, m)
assert abs(hard_dtw(cost) - brute_force_dtw(cost)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_dtw.py::test_hard_dtw_matches_brute_force" -qMethod implementation
def __post_init__(self) -> None:
if self.n_rows < 1 or self.n_cols < 1:
raise ValueError(f"lattice must be at least 1x1, got {self.n_rows}x{self.n_cols}")enumerate_pathsmethod
enumerate_paths(self) -> Iterator[tuple[tuple[int, int], ...]]Yield every monotonic (0,0) -> (n-1,m-1) path as a tuple of (i, j) cells.
Returns: Iterator[tuple[tuple[int, int], ...]]
Executed regression · hard dtw matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_dtw_matches_brute_force() -> None:
rng = np.random.default_rng(0)
for n, m in ((3, 3), (4, 2), (2, 5), (4, 4)):
cost = _cost(rng, n, m)
assert abs(hard_dtw(cost) - brute_force_dtw(cost)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_dtw.py::test_hard_dtw_matches_brute_force" -qMethod implementation
def enumerate_paths(self) -> Iterator[tuple[tuple[int, int], ...]]:
"""Yield every monotonic ``(0,0) -> (n-1,m-1)`` path as a tuple of ``(i, j)`` cells."""
target = (self.n_rows - 1, self.n_cols - 1)
def dfs(cell: tuple[int, int], acc: tuple[tuple[int, int], ...]) -> Iterator[tuple[tuple[int, int], ...]]:
if cell == target:
yield acc
return
i, j = cell
for ni, nj in ((i + 1, j), (i, j + 1), (i + 1, j + 1)):
if ni < self.n_rows and nj < self.n_cols:
yield from dfs((ni, nj), (*acc, (ni, nj)))
yield from dfs((0, 0), ((0, 0),))path_costmethod
path_cost(self, path: Sequence[tuple[int, int]], cost: FloatArray) -> floatSum of local costs D over the cells a path visits.
Parameters
| Name | Type & default | Contract |
|---|---|---|
pathpositional-or-keyword | Sequence[tuple[int, int]]Required | See the operation contract and implementation below. |
costpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
Returns: float
Executed regression · hard dtw matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_dtw_matches_brute_force() -> None:
rng = np.random.default_rng(0)
for n, m in ((3, 3), (4, 2), (2, 5), (4, 4)):
cost = _cost(rng, n, m)
assert abs(hard_dtw(cost) - brute_force_dtw(cost)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_dtw.py::test_hard_dtw_matches_brute_force" -qMethod implementation
def path_cost(self, path: Sequence[tuple[int, int]], cost: FloatArray) -> float:
"""Sum of local costs ``D`` over the cells a path visits."""
return float(sum(float(cost[int(i), int(j)]) for i, j in path))count_pathsmethod
count_paths(self) -> intExact number of monotonic paths -- the Delannoy number D(n-1, m-1).
Returns: int
Executed regression · soft dtw sandwiches hard dtw with log n gap
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_dtw_sandwiches_hard_dtw_with_log_n_gap() -> None:
rng = np.random.default_rng(2)
cost = _cost(rng, 4, 4)
ct = torch.tensor(cost)
hard = hard_dtw(cost)
num_paths = DTWLattice(4, 4).count_paths()
prev_gap = np.inf
for beta in (1.0, 2.0, 4.0, 8.0, 16.0):
soft = float(tdtw.soft_dtw(ct, beta))
cert = certify_soft_dp(hard, soft, num_paths, beta, sense="min", brute_force_value=brute_force_dtw(cost))
assert cert.is_sound # V* - log(N)/beta <= V_beta <= V*
assert cert.agrees_with_bruteforce
assert soft <= hard + 1e-9 # softmin never exceeds the hard min
assert cert.absolute_gap <= prev_gap + 1e-12 # gap shrinks with beta
prev_gap = cert.absolute_gappython -m pytest "packages/omnibias-struct/tests/test_dtw.py::test_soft_dtw_sandwiches_hard_dtw_with_log_n_gap" -qMethod implementation
def count_paths(self) -> int:
"""Exact number of monotonic paths -- the Delannoy number ``D(n-1, m-1)``."""
counts = np.zeros((self.n_rows, self.n_cols), dtype=object)
counts[0, 0] = 1
for i in range(self.n_rows):
for j in range(self.n_cols):
if i == 0 and j == 0:
continue
total = 0
if i > 0:
total += counts[i - 1, j]
if j > 0:
total += counts[i, j - 1]
if i > 0 and j > 0:
total += counts[i - 1, j - 1]
counts[i, j] = total
return int(counts[self.n_rows - 1, self.n_cols - 1])Read the implementation
class DTWLattice:
r"""The ``(n_rows, n_cols)`` monotonic warping grid (steps: down, right, diagonal).
Pure structure -- the differentiable soft DTW consumes a backend cost tensor alongside
the lattice shape, exactly as :class:`~omnibias.struct.ChainTrellis` pairs with backend
emissions. Intended for tiny grids (the brute-force oracle is exponential).
"""
n_rows: int
n_cols: int
def __post_init__(self) -> None:
if self.n_rows < 1 or self.n_cols < 1:
raise ValueError(f"lattice must be at least 1x1, got {self.n_rows}x{self.n_cols}")
def enumerate_paths(self) -> Iterator[tuple[tuple[int, int], ...]]:
"""Yield every monotonic ``(0,0) -> (n-1,m-1)`` path as a tuple of ``(i, j)`` cells."""
target = (self.n_rows - 1, self.n_cols - 1)
def dfs(cell: tuple[int, int], acc: tuple[tuple[int, int], ...]) -> Iterator[tuple[tuple[int, int], ...]]:
if cell == target:
yield acc
return
i, j = cell
for ni, nj in ((i + 1, j), (i, j + 1), (i + 1, j + 1)):
if ni < self.n_rows and nj < self.n_cols:
yield from dfs((ni, nj), (*acc, (ni, nj)))
yield from dfs((0, 0), ((0, 0),))
def path_cost(self, path: Sequence[tuple[int, int]], cost: FloatArray) -> float:
"""Sum of local costs ``D`` over the cells a path visits."""
return float(sum(float(cost[int(i), int(j)]) for i, j in path))
def count_paths(self) -> int:
"""Exact number of monotonic paths -- the Delannoy number ``D(n-1, m-1)``."""
counts = np.zeros((self.n_rows, self.n_cols), dtype=object)
counts[0, 0] = 1
for i in range(self.n_rows):
for j in range(self.n_cols):
if i == 0 and j == 0:
continue
total = 0
if i > 0:
total += counts[i - 1, j]
if j > 0:
total += counts[i, j - 1]
if i > 0 and j > 0:
total += counts[i - 1, j - 1]
counts[i, j] = total
return int(counts[self.n_rows - 1, self.n_cols - 1])brute_force_dtw
omnibias.struct.brute_force_dtwSource ↗brute_force_dtw(cost: FloatArray) -> floatExact hard DTW by enumerating every monotonic path (oracle for tiny grids).
Parameters
| Name | Type & default | Contract |
|---|---|---|
costpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
floatExecuted regression · hard dtw matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_dtw_matches_brute_force() -> None:
rng = np.random.default_rng(0)
for n, m in ((3, 3), (4, 2), (2, 5), (4, 4)):
cost = _cost(rng, n, m)
assert abs(hard_dtw(cost) - brute_force_dtw(cost)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_dtw.py::test_hard_dtw_matches_brute_force" -qRegression example · soft dtw sandwiches hard dtw with log n gap
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_dtw_sandwiches_hard_dtw_with_log_n_gap() -> None:
rng = np.random.default_rng(2)
cost = _cost(rng, 4, 4)
ct = torch.tensor(cost)
hard = hard_dtw(cost)
num_paths = DTWLattice(4, 4).count_paths()
prev_gap = np.inf
for beta in (1.0, 2.0, 4.0, 8.0, 16.0):
soft = float(tdtw.soft_dtw(ct, beta))
cert = certify_soft_dp(hard, soft, num_paths, beta, sense="min", brute_force_value=brute_force_dtw(cost))
assert cert.is_sound # V* - log(N)/beta <= V_beta <= V*
assert cert.agrees_with_bruteforce
assert soft <= hard + 1e-9 # softmin never exceeds the hard min
assert cert.absolute_gap <= prev_gap + 1e-12 # gap shrinks with beta
prev_gap = cert.absolute_gappython -m pytest packages/omnibias-struct/tests/test_dtw.py -k test_soft_dtw_sandwiches_hard_dtw_with_log_n_gap -qRead the implementation
def brute_force_dtw(cost: FloatArray) -> float:
r"""Exact hard DTW by enumerating every monotonic path (oracle for tiny grids)."""
d = np.asarray(cost, dtype=float)
lattice = DTWLattice(*d.shape)
return min(lattice.path_cost(p, d) for p in lattice.enumerate_paths())brute_force_soft_dtw
omnibias.struct.brute_force_soft_dtwSource ↗brute_force_soft_dtw(cost: FloatArray, beta: float) -> floatExact soft DTW -beta^-1 log sum_paths exp(-beta cost(path)) (global softmin).
The ground truth for the recursive soft-DTW: because lse_beta distributes over the
additive path costs, the recursion equals this flat softmin over all monotonic paths.
Parameters
| Name | Type & default | Contract |
|---|---|---|
costpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · recursive soft dtw equals flat softmin over paths
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_recursive_soft_dtw_equals_flat_softmin_over_paths() -> None:
rng = np.random.default_rng(1)
cost = _cost(rng, 4, 3)
ct = torch.tensor(cost)
for beta in (0.5, 1.0, 4.0, 16.0):
recursive = float(tdtw.soft_dtw(ct, beta))
brute = brute_force_soft_dtw(cost, beta)
assert abs(recursive - brute) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_dtw.py::test_recursive_soft_dtw_equals_flat_softmin_over_paths" -qRegression example · dtw value iv encloses brute force over box
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_dtw_value_iv_encloses_brute_force_over_box() -> None:
rng = np.random.default_rng(10)
center = rng.standard_normal((3, 3))
radius, beta = 0.3, 2.0
iv = dtw_value_iv(box(center, radius), beta)
samples = _corners(center, radius) + [
center + rng.uniform(-radius, radius, center.shape) for _ in range(80)
]
for cost in samples:
assert iv.lo - TOL <= brute_force_soft_dtw(cost, beta) <= iv.hi + TOLpython -m pytest packages/omnibias-struct/tests/test_verified.py -k test_dtw_value_iv_encloses_brute_force_over_box -qRead the implementation
def brute_force_soft_dtw(cost: FloatArray, beta: float) -> float:
r"""Exact soft DTW ``-beta^-1 log sum_paths exp(-beta cost(path))`` (global softmin).
The ground truth for the recursive soft-DTW: because ``lse_beta`` distributes over the
additive path costs, the recursion equals this flat softmin over all monotonic paths.
"""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
d = np.asarray(cost, dtype=float)
lattice = DTWLattice(*d.shape)
neg_costs = np.array([-lattice.path_cost(p, d) for p in lattice.enumerate_paths()])
mx = float(np.max(neg_costs))
lse = mx + math.log(float(np.sum(np.exp(beta * (neg_costs - mx))))) / beta
return -lsehard_dtw
omnibias.struct.hard_dtwSource ↗hard_dtw(cost: FloatArray) -> floatMinimum-cost monotonic warping (classic DTW) of an (n, m) local-cost matrix.
Parameters
| Name | Type & default | Contract |
|---|---|---|
costpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
floatExecuted regression · hard dtw matches brute force
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_dtw_matches_brute_force() -> None:
rng = np.random.default_rng(0)
for n, m in ((3, 3), (4, 2), (2, 5), (4, 4)):
cost = _cost(rng, n, m)
assert abs(hard_dtw(cost) - brute_force_dtw(cost)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_dtw.py::test_hard_dtw_matches_brute_force" -qRegression example · soft dtw sandwiches hard dtw with log n gap
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_dtw_sandwiches_hard_dtw_with_log_n_gap() -> None:
rng = np.random.default_rng(2)
cost = _cost(rng, 4, 4)
ct = torch.tensor(cost)
hard = hard_dtw(cost)
num_paths = DTWLattice(4, 4).count_paths()
prev_gap = np.inf
for beta in (1.0, 2.0, 4.0, 8.0, 16.0):
soft = float(tdtw.soft_dtw(ct, beta))
cert = certify_soft_dp(hard, soft, num_paths, beta, sense="min", brute_force_value=brute_force_dtw(cost))
assert cert.is_sound # V* - log(N)/beta <= V_beta <= V*
assert cert.agrees_with_bruteforce
assert soft <= hard + 1e-9 # softmin never exceeds the hard min
assert cert.absolute_gap <= prev_gap + 1e-12 # gap shrinks with beta
prev_gap = cert.absolute_gappython -m pytest packages/omnibias-struct/tests/test_dtw.py -k test_soft_dtw_sandwiches_hard_dtw_with_log_n_gap -qRead the implementation
def hard_dtw(cost: FloatArray) -> float:
r"""Minimum-cost monotonic warping (classic DTW) of an ``(n, m)`` local-cost matrix."""
d = np.asarray(cost, dtype=float)
n, m = d.shape
r = np.full((n, m), np.inf)
r[0, 0] = d[0, 0]
for i in range(n):
for j in range(m):
if i == 0 and j == 0:
continue
best = np.inf
if i > 0:
best = min(best, r[i - 1, j])
if j > 0:
best = min(best, r[i, j - 1])
if i > 0 and j > 0:
best = min(best, r[i - 1, j - 1])
r[i, j] = d[i, j] + best
return float(r[n - 1, m - 1])best_projective_tree
omnibias.struct.best_projective_treeSource ↗best_projective_tree(arc: FloatArray) -> tuple[float, dict[int, int]]Classic Eisner Viterbi parse: the best score and the head map {modifier: head}.
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
tuple[float, dict[int, int]]Executed regression · best projective tree is valid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_best_projective_tree_is_valid(seed: int) -> None:
arc = _arc(seed, 5)
score, heads = best_projective_tree(arc)
assert abs(score - hard_eisner(arc)) < TOL
assert set(heads) == set(range(1, 6)) # every word takes a head
assert heads in list(iter_projective_trees(5)) # the head map is a valid projective treepython -m pytest "packages/omnibias-struct/tests/test_eisner.py::test_best_projective_tree_is_valid[0]" -qRead the implementation
def best_projective_tree(arc: FloatArray) -> tuple[float, dict[int, int]]:
r"""Classic Eisner Viterbi parse: the best score and the head map ``{modifier: head}``."""
a = np.asarray(arc, dtype=float)
positions = a.shape[0]
n = positions - 1
neg = -math.inf
cr = np.full((positions, positions), neg)
cl = np.full((positions, positions), neg)
ir = np.full((positions, positions), neg)
il = np.full((positions, positions), neg)
bcr: dict[tuple[int, int], int] = {}
bcl: dict[tuple[int, int], int] = {}
bir: dict[tuple[int, int], int] = {}
bil: dict[tuple[int, int], int] = {}
for s in range(positions):
cr[s, s] = 0.0
cl[s, s] = 0.0
for w in range(1, positions):
for s in range(0, positions - w):
t = s + w
best, arg = neg, s
for r in range(s, t):
v = cr[s, r] + cl[r + 1, t]
if v > best:
best, arg = v, r
ir[s, t], bir[(s, t)] = best + a[s, t], arg
if s >= 1:
il[s, t], bil[(s, t)] = best + a[t, s], arg
best, arg = neg, s + 1
for r in range(s + 1, t + 1):
v = ir[s, r] + cr[r, t]
if v > best:
best, arg = v, r
cr[s, t], bcr[(s, t)] = best, arg
best, arg = neg, s
for r in range(s, t):
if r >= 1:
v = cl[s, r] + il[r, t]
if v > best:
best, arg = v, r
cl[s, t], bcl[(s, t)] = best, arg
heads: dict[int, int] = {}
def rec(kind: str, s: int, t: int) -> None:
if s == t:
return
if kind == "IR":
heads[t] = s
r = bir[(s, t)]
rec("CR", s, r)
rec("CL", r + 1, t)
elif kind == "IL":
heads[s] = t
r = bil[(s, t)]
rec("CR", s, r)
rec("CL", r + 1, t)
elif kind == "CR":
r = bcr[(s, t)]
rec("IR", s, r)
rec("CR", r, t)
else: # CL
r = bcl[(s, t)]
rec("CL", s, r)
rec("IL", r, t)
rec("CR", 0, n)
return float(cr[0, n]), headsbrute_force_eisner
omnibias.struct.brute_force_eisnerSource ↗brute_force_eisner(arc: FloatArray, beta: float | None=None) -> floatFlat oracle via the driver's derivation enumeration over the Eisner hypergraph.
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | float | NoneDefault: None | See the operation contract and implementation below. |
floatRead the implementation
def brute_force_eisner(arc: FloatArray, beta: float | None = None) -> float:
r"""Flat oracle via the driver's derivation enumeration over the Eisner hypergraph."""
spec = eisner_hypergraph(int(np.asarray(arc).shape[0]) - 1)
return brute_force_value(spec.graph, eisner_edge_weights(spec, arc), beta)brute_force_projective
omnibias.struct.brute_force_projectiveSource ↗brute_force_projective(arc: FloatArray, beta: float | None=None) -> floatFlat oracle over *enumerated* projective trees: max (beta is None) or lse_beta.
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | float | NoneDefault: None | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
scores.size == 0, raisesValueError('no projective trees (n must be >= 1)'). - When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · eisner hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_eisner_hard_equals_brute_and_count(seed: int) -> None:
assert probe_eisner_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_eisner_hard_equals_brute_and_count[0]" -qRegression example · hard eisner matches driver and bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_eisner_matches_driver_and_bruteforce(seed: int) -> None:
arc = _arc(seed, 4)
spec = eisner_hypergraph(4)
w = eisner_edge_weights(spec, arc)
he = hard_eisner(arc)
assert abs(he - hard_value(spec.graph, w)) < TOL
assert abs(he - brute_force_projective(arc, None)) < 1e-11python -m pytest packages/omnibias-struct/tests/test_eisner.py -k test_hard_eisner_matches_driver_and_bruteforce -qRead the implementation
def brute_force_projective(arc: FloatArray, beta: float | None = None) -> float:
r"""Flat oracle over *enumerated* projective trees: ``max`` (``beta is None``) or ``lse_beta``."""
a = np.asarray(arc, dtype=float)
n = a.shape[0] - 1
scores = np.array(
[float(sum(a[heads[m], m] for m in range(1, n + 1))) for heads in iter_projective_trees(n)]
)
if scores.size == 0:
raise ValueError("no projective trees (n must be >= 1)")
if beta is None:
return float(np.max(scores))
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
m = float(np.max(scores))
return m + math.log(float(np.sum(np.exp(beta * (scores - m))))) / betacount_projective_trees
omnibias.struct.count_projective_treesSource ↗count_projective_trees(n_words: int) -> intExact number of projective dependency trees of n_words -- the N in the gap.
Parameters
| Name | Type & default | Contract |
|---|---|---|
n_wordspositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExecuted regression · eisner hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_eisner_hard_equals_brute_and_count(seed: int) -> None:
assert probe_eisner_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_eisner_hard_equals_brute_and_count[0]" -qRegression example · count projective trees matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_count_projective_trees_matches_bruteforce(n_words: int) -> None:
assert count_projective_trees(n_words) == sum(1 for _ in iter_projective_trees(n_words))python -m pytest packages/omnibias-struct/tests/test_eisner.py -k test_count_projective_trees_matches_bruteforce -qRead the implementation
def count_projective_trees(n_words: int) -> int:
r"""Exact number of projective dependency trees of ``n_words`` -- the ``N`` in the gap."""
return count_derivations(eisner_hypergraph(n_words).graph)eisner_hypergraph
omnibias.struct.eisner_hypergraphSource ↗eisner_hypergraph(n_words: int) -> EisnerSpecLift Eisner's projective-parse DP for n_words onto a chart Hypergraph.
Items are ordered by span width (and incomplete before complete within a width) so tails
always precede heads. CR/CL are complete right/left spans, IR/IL incomplete.
Parameters
| Name | Type & default | Contract |
|---|---|---|
n_wordspositional-or-keyword | intRequired | See the operation contract and implementation below. |
EisnerSpecExplicit validation & failure cases
- When
n_words < 1, raisesValueError(f'n_words must be >= 1, got {n_words}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · eisner hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_eisner_hard_equals_brute_and_count(seed: int) -> None:
assert probe_eisner_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_eisner_hard_equals_brute_and_count[0]" -qRegression example · hard eisner matches driver and bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_eisner_matches_driver_and_bruteforce(seed: int) -> None:
arc = _arc(seed, 4)
spec = eisner_hypergraph(4)
w = eisner_edge_weights(spec, arc)
he = hard_eisner(arc)
assert abs(he - hard_value(spec.graph, w)) < TOL
assert abs(he - brute_force_projective(arc, None)) < 1e-11python -m pytest packages/omnibias-struct/tests/test_eisner.py -k test_hard_eisner_matches_driver_and_bruteforce -qRead the implementation
def eisner_hypergraph(n_words: int) -> EisnerSpec:
r"""Lift Eisner's projective-parse DP for ``n_words`` onto a chart :class:`Hypergraph`.
Items are ordered by span width (and incomplete before complete within a width) so tails
always precede heads. ``CR/CL`` are complete right/left spans, ``IR/IL`` incomplete.
"""
if n_words < 1:
raise ValueError(f"n_words must be >= 1, got {n_words}")
positions = n_words + 1
node_of: dict[tuple[str, int, int], int] = {}
nid = 0
for w in range(0, positions):
if w >= 1:
for s in range(0, positions - w):
t = s + w
node_of[("IR", s, t)] = nid
nid += 1
if s >= 1:
node_of[("IL", s, t)] = nid
nid += 1
for s in range(0, positions - w):
t = s + w
node_of[("CR", s, t)] = nid
nid += 1
node_of[("CL", s, t)] = nid
nid += 1
edges: list[HyperEdge] = []
specs: list[tuple[str, int, int]] = []
for s in range(positions):
edges.append(HyperEdge(head=node_of[("CR", s, s)], tails=()))
specs.append(("base", -1, -1))
edges.append(HyperEdge(head=node_of[("CL", s, s)], tails=()))
specs.append(("base", -1, -1))
for w in range(1, positions):
for s in range(0, positions - w):
t = s + w
for r in range(s, t):
edges.append(
HyperEdge(head=node_of[("IR", s, t)], tails=(node_of[("CR", s, r)], node_of[("CL", r + 1, t)]))
)
specs.append(("arc", s, t))
if s >= 1:
for r in range(s, t):
edges.append(
HyperEdge(head=node_of[("IL", s, t)], tails=(node_of[("CR", s, r)], node_of[("CL", r + 1, t)]))
)
specs.append(("arc", t, s))
for r in range(s + 1, t + 1):
edges.append(
HyperEdge(head=node_of[("CR", s, t)], tails=(node_of[("IR", s, r)], node_of[("CR", r, t)]))
)
specs.append(("base", -1, -1))
for r in range(s, t):
if r >= 1:
edges.append(
HyperEdge(head=node_of[("CL", s, t)], tails=(node_of[("CL", s, r)], node_of[("IL", r, t)]))
)
specs.append(("base", -1, -1))
root = node_of[("CR", 0, n_words)]
graph = Hypergraph(num_nodes=nid, edges=tuple(edges), root=root)
return EisnerSpec(graph=graph, edge_specs=tuple(specs), n_words=n_words, node_of=node_of, root=root)hard_eisner
omnibias.struct.hard_eisnerSource ↗hard_eisner(arc: FloatArray) -> floatClassic Eisner best projective-parse score (max-plus), independent of the driver.
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
floatExecuted regression · eisner hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_eisner_hard_equals_brute_and_count(seed: int) -> None:
assert probe_eisner_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_eisner_hard_equals_brute_and_count[0]" -qRegression example · hard eisner matches driver and bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_eisner_matches_driver_and_bruteforce(seed: int) -> None:
arc = _arc(seed, 4)
spec = eisner_hypergraph(4)
w = eisner_edge_weights(spec, arc)
he = hard_eisner(arc)
assert abs(he - hard_value(spec.graph, w)) < TOL
assert abs(he - brute_force_projective(arc, None)) < 1e-11python -m pytest packages/omnibias-struct/tests/test_eisner.py -k test_hard_eisner_matches_driver_and_bruteforce -qRead the implementation
def hard_eisner(arc: FloatArray) -> float:
r"""Classic Eisner best projective-parse score (max-plus), independent of the driver."""
a = np.asarray(arc, dtype=float)
positions = a.shape[0]
n = positions - 1
neg = -math.inf
cr = np.full((positions, positions), neg)
cl = np.full((positions, positions), neg)
ir = np.full((positions, positions), neg)
il = np.full((positions, positions), neg)
for s in range(positions):
cr[s, s] = 0.0
cl[s, s] = 0.0
for w in range(1, positions):
for s in range(0, positions - w):
t = s + w
glue = max(cr[s, r] + cl[r + 1, t] for r in range(s, t))
ir[s, t] = glue + a[s, t]
if s >= 1:
il[s, t] = glue + a[t, s]
cr[s, t] = max(ir[s, r] + cr[r, t] for r in range(s + 1, t + 1))
cl_best = neg
for r in range(s, t):
if r >= 1:
cl_best = max(cl_best, cl[s, r] + il[r, t])
cl[s, t] = cl_best
return float(cr[0, n])iter_projective_trees
omnibias.struct.iter_projective_treesSource ↗iter_projective_trees(n: int) -> Iterator[dict[int, int]]Yield every valid projective head map {modifier: head} of n words (brute force).
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intRequired | See the operation contract and implementation below. |
Iterator[dict[int, int]]Executed regression · eisner hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_eisner_hard_equals_brute_and_count(seed: int) -> None:
assert probe_eisner_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_eisner_hard_equals_brute_and_count[0]" -qRegression example · count projective trees matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_count_projective_trees_matches_bruteforce(n_words: int) -> None:
assert count_projective_trees(n_words) == sum(1 for _ in iter_projective_trees(n_words))python -m pytest packages/omnibias-struct/tests/test_eisner.py -k test_count_projective_trees_matches_bruteforce -qRead the implementation
def iter_projective_trees(n: int) -> Iterator[dict[int, int]]:
r"""Yield every valid projective head map ``{modifier: head}`` of ``n`` words (brute force)."""
for assignment in itertools.product(range(n + 1), repeat=n):
heads = {m: assignment[m - 1] for m in range(1, n + 1)}
if any(heads[m] == m for m in range(1, n + 1)):
continue
if _is_tree(heads, n) and _is_projective(heads, n):
yield headssoft_eisner
omnibias.struct.soft_eisnerSource ↗soft_eisner(arc: FloatArray, beta: float) -> floatSoft lse_beta projective-parse partition (numpy oracle for the backend layer).
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatRead the implementation
def soft_eisner(arc: FloatArray, beta: float) -> float:
r"""Soft ``lse_beta`` projective-parse partition (numpy oracle for the backend layer)."""
spec = eisner_hypergraph(int(np.asarray(arc).shape[0]) - 1)
return soft_value(spec.graph, eisner_edge_weights(spec, arc), beta)logsumexp_gap_bound
omnibias.struct.logsumexp_gap_boundSource ↗logsumexp_gap_bound(num_paths: int, beta: float) -> floatClosed-form upper bound on lse_beta - max: log(num_paths) / beta.
Parameters
num_paths: The exact number N >= 1 of complete paths (e.g. from omnibias.struct.count_paths).
beta: The inverse temperature beta > 0.
Returns
float log(num_paths) / beta (0 when num_paths == 1: a single path has no gap). A larger num_paths or smaller beta only *widens* the certified gap -- the bound is never optimistic.
Parameters
| Name | Type & default | Contract |
|---|---|---|
num_pathspositional-or-keyword | intRequired | The exact number N >= 1 of complete paths (e.g. from omnibias.struct.count_paths). |
betapositional-or-keyword | floatRequired | The inverse temperature beta > 0. |
floatExplicit validation & failure cases
- When
num_paths < 1, raisesValueError(f'num_paths must be >= 1, got {num_paths}'). - When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · stepwise bound equals global for a chain
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_stepwise_bound_equals_global_for_a_chain() -> None:
trellis = random_chain(0)
beta = 4.0
assert abs(stepwise_gap_bound(trellis, beta) - logsumexp_gap_bound(count_paths(trellis), beta)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_core_harden.py::test_stepwise_bound_equals_global_for_a_chain" -qRegression example · logsumexp gap bound math
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_logsumexp_gap_bound_math() -> None:
assert logsumexp_gap_bound(1, 2.0) == 0.0 # a single path has no gap
assert math.isclose(logsumexp_gap_bound(8, 2.0), math.log(8) / 2.0)
with pytest.raises(ValueError):
logsumexp_gap_bound(0, 1.0)
with pytest.raises(ValueError):
logsumexp_gap_bound(4, 0.0)python -m pytest packages/omnibias-struct/tests/test_certificate.py -k test_logsumexp_gap_bound_math -qRead the implementation
def logsumexp_gap_bound(num_paths: int, beta: float) -> float:
r"""Closed-form upper bound on ``lse_beta - max``: ``log(num_paths) / beta``.
Parameters
----------
num_paths:
The exact number ``N >= 1`` of complete paths (e.g. from
:func:`omnibias.struct.count_paths`).
beta:
The inverse temperature ``beta > 0``.
Returns
-------
float
``log(num_paths) / beta`` (``0`` when ``num_paths == 1``: a single path has no
gap). A larger ``num_paths`` or smaller ``beta`` only *widens* the certified
gap -- the bound is never optimistic.
"""
if num_paths < 1:
raise ValueError(f"num_paths must be >= 1, got {num_paths}")
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
return math.log(num_paths) / betastepwise_gap_bound
omnibias.struct.stepwise_gap_boundSource ↗stepwise_gap_bound(problem: ChainTrellis | DAG | CTCLattice, beta: float, *, n_steps: int | None=None) -> floatN-free sound gap bound: the critical-path sum of log(fan-in) / beta.
Each lse_beta reduction over k terms contributes at most log(k) / beta of
slack, and the slacks compose additively along the *deepest* chain of reductions in
the DP (leaves are exact). Hence
V_\beta - V^* \;\le\; \max_{\text{paths}}\ \sum_{\text{reductions } r}
\frac{\log(\mathrm{fanin}_r)}{\beta}.**Honesty note (a data-driven finding).** This is *not* tighter than the global
log(N) / beta. Because the forward path count obeys
log(paths->v) <= log(indeg(v)) + max_{u -> v} log(paths->u), the critical-path sum
provably dominates log N; the two coincide only for series-parallel structure
(e.g. a dense ChainTrellis) and it is strictly *looser* for reconvergent
DAGs / CTC lattices. Its real use is as an **N-free** certificate computed from fan-in
alone when the path count is unavailable. certify_soft_dp takes
min(global, stepwise), so a sealed bound is never worse than log(N) / beta.
Sound for both the max (Viterbi / CTC) and min (shortest-path softmin) senses.
Parameters
| Name | Type & default | Contract |
|---|---|---|
problempositional-or-keyword | ChainTrellis | DAG | CTCLatticeRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
n_stepskeyword-only | int | NoneDefault: None | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}'). - When
n_steps is None, raisesValueError('stepwise_gap_bound on a CTCLattice requires n_steps (= T)'). - When
n_steps < problem.n_labels, raisesValueError('infeasible CTC instance: n_steps shorter than the label sequence').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · stepwise bound equals global for a chain
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_stepwise_bound_equals_global_for_a_chain() -> None:
trellis = random_chain(0)
beta = 4.0
assert abs(stepwise_gap_bound(trellis, beta) - logsumexp_gap_bound(count_paths(trellis), beta)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_core_harden.py::test_stepwise_bound_equals_global_for_a_chain" -qRegression example · stepwise bound dominates global and stays sound
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_stepwise_bound_dominates_global_and_stays_sound(seed: int) -> None:
torch = pytest.importorskip("torch")
from omnibias.struct.torch import soft_shortest_path
dag = random_dag(seed, n=6)
beta = 4.0
hard, _ = shortest_path(dag)
soft = float(soft_shortest_path(torch.tensor(dag_weight_matrix(dag)), dag, beta))
realized = hard - soft # min-sense gap >= 0
global_bound = logsumexp_gap_bound(count_paths(dag), beta)
stepwise = stepwise_gap_bound(dag, beta)
assert realized <= stepwise + 1e-9 # sound
assert global_bound <= stepwise + 1e-12 # provably dominated (never tighter)python -m pytest packages/omnibias-struct/tests/test_core_harden.py -k test_stepwise_bound_dominates_global_and_stays_sound -qRead the implementation
def stepwise_gap_bound(
problem: ChainTrellis | DAG | CTCLattice,
beta: float,
*,
n_steps: int | None = None,
) -> float:
r"""N-free sound gap bound: the critical-path sum of ``log(fan-in) / beta``.
Each ``lse_beta`` reduction over ``k`` terms contributes at most ``log(k) / beta`` of
slack, and the slacks compose additively along the *deepest* chain of reductions in
the DP (leaves are exact). Hence
.. math::
V_\beta - V^* \;\le\; \max_{\text{paths}}\ \sum_{\text{reductions } r}
\frac{\log(\mathrm{fanin}_r)}{\beta}.
**Honesty note (a data-driven finding).** This is *not* tighter than the global
``log(N) / beta``. Because the forward path count obeys
``log(paths->v) <= log(indeg(v)) + max_{u -> v} log(paths->u)``, the critical-path sum
provably dominates ``log N``; the two coincide only for series-parallel structure
(e.g. a dense :class:`ChainTrellis`) and it is strictly *looser* for reconvergent
DAGs / CTC lattices. Its real use is as an **N-free** certificate computed from fan-in
alone when the path count is unavailable. :func:`certify_soft_dp` takes
``min(global, stepwise)``, so a sealed bound is never worse than ``log(N) / beta``.
Sound for both the ``max`` (Viterbi / CTC) and ``min`` (shortest-path softmin) senses.
"""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
if isinstance(problem, ChainTrellis):
# T reductions of width S along every path (forward T-1 + final).
return problem.n_steps * math.log(problem.n_states) / beta
if isinstance(problem, DAG):
preds: dict[int, list[int]] = {v: problem.incoming(v) for v in range(problem.num_nodes)}
slack = [-math.inf] * problem.num_nodes
slack[problem.source] = 0.0
for v in range(problem.num_nodes):
if v == problem.source or not preds[v]:
continue
best_child = max(slack[u] for u in preds[v])
if best_child == -math.inf:
continue
slack[v] = math.log(len(preds[v])) / beta + best_child
return max(slack[problem.sink], 0.0)
if n_steps is None:
raise ValueError("stepwise_gap_bound on a CTCLattice requires n_steps (= T)")
m = 2 * problem.n_labels + 1
if n_steps < problem.n_labels:
raise ValueError("infeasible CTC instance: n_steps shorter than the label sequence")
slack_t = [-math.inf] * m
slack_t[0] = 0.0
if m > 1:
slack_t[1] = 0.0
for _ in range(1, n_steps):
nxt = [-math.inf] * m
for s in range(m):
preds_s = problem.incoming(s)
best_child = max((slack_t[p] for p in preds_s), default=-math.inf)
if best_child == -math.inf:
continue
nxt[s] = math.log(len(preds_s)) / beta + best_child
slack_t = nxt
ends = [slack_t[m - 1]] + ([slack_t[m - 2]] if m >= 2 else [])
n_ends = sum(1 for e in ends if e != -math.inf)
best_end = max(ends)
return best_end + (math.log(n_ends) / beta if n_ends > 1 else 0.0)brute_force_ctc
omnibias.struct.brute_force_ctcSource ↗brute_force_ctc(lattice: CTCLattice, log_probs: object) -> floatExact best CTC alignment score by enumerating all C ** T label sequences.
Parameters
| Name | Type & default | Contract |
|---|---|---|
latticepositional-or-keyword | CTCLatticeRequired | See the operation contract and implementation below. |
log_probspositional-or-keyword | objectRequired | See the operation contract and implementation below. |
floatExecuted regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-ctc]" -qRegression example · ctc best matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_ctc_best_matches_bruteforce(seed: int) -> None:
lattice, log_probs = sample_ctc(seed)
assert abs(ctc_best(lattice, log_probs) - brute_force_ctc(lattice, log_probs)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_hard_dp.py -k test_ctc_best_matches_bruteforce -qRead the implementation
def brute_force_ctc(lattice: CTCLattice, log_probs: object) -> float:
r"""Exact best CTC alignment score by enumerating all ``C ** T`` label sequences."""
lp = np.asarray(log_probs, dtype=float)
n_steps, num_classes = lp.shape
target = tuple(int(y) for y in lattice.targets)
best = -math.inf
for idx in range(num_classes**n_steps):
seq, rem = [], idx
for _ in range(n_steps):
seq.append(rem % num_classes)
rem //= num_classes
if lattice.collapse(seq) == target:
score = float(sum(lp[t, seq[t]] for t in range(n_steps)))
best = max(best, score)
return bestbrute_force_partition
omnibias.struct.brute_force_partitionSource ↗brute_force_partition(problem: ChainTrellis | DAG | CTCLattice, beta: float, log_probs: object | None=None) -> floatExact soft value beta^-1 log sum_paths exp(beta score) over every path.
The ground truth for the soft-DP recursion. For a DAG the "score" is the
negated cost (max convention), so the soft *cost* returned by
omnibias.struct.torch.soft_shortest_path is its negation. For a
CTCLattice pass log_probs (T, C).
Parameters
| Name | Type & default | Contract |
|---|---|---|
problempositional-or-keyword | ChainTrellis | DAG | CTCLatticeRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
log_probspositional-or-keyword | object | NoneDefault: None | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · gap shrinks with beta
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_gap_shrinks_with_beta() -> None:
trellis = random_chain(3)
hard, _ = viterbi(trellis)
num_paths = count_paths(trellis)
gaps = [
certify_soft_dp(hard, brute_force_partition(trellis, b), num_paths, b).absolute_gap
for b in (1.0, 4.0, 16.0, 64.0)
]
assert all(gaps[i + 1] < gaps[i] for i in range(len(gaps) - 1))
assert gaps[-1] < 1e-2python -m pytest "packages/omnibias-struct/tests/test_certificate.py::test_gap_shrinks_with_beta" -qRegression example · pairwise lse iv encloses and matches vector form
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_pairwise_lse_iv_encloses_and_matches_vector_form() -> None:
rng = np.random.default_rng(1)
for _ in range(50):
a, b = rng.standard_normal(2)
beta = 3.0
iv = pairwise_lse_iv(a, b, beta)
true = (np.logaddexp(beta * a, beta * b)) / beta
assert iv.lo - TOL <= true <= iv.hi + TOLpython -m pytest packages/omnibias-struct/tests/test_verified.py -k test_pairwise_lse_iv_encloses_and_matches_vector_form -qRead the implementation
def brute_force_partition(
problem: ChainTrellis | DAG | CTCLattice,
beta: float,
log_probs: object | None = None,
) -> float:
r"""Exact soft value ``beta^-1 log sum_paths exp(beta score)`` over every path.
The ground truth for the soft-DP recursion. For a :class:`DAG` the "score" is the
negated cost (max convention), so the soft *cost* returned by
:func:`omnibias.struct.torch.soft_shortest_path` is its negation. For a
:class:`CTCLattice` pass ``log_probs`` ``(T, C)``.
"""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
if isinstance(problem, ChainTrellis):
scores = np.array([problem.path_score(p) for p in problem.enumerate_paths()])
return _logsumexp(scores, beta)
if isinstance(problem, DAG):
scores = np.array([-problem.path_cost(p) for p in problem.enumerate_paths()])
return _logsumexp(scores, beta)
lp = np.asarray(log_probs, dtype=float)
n_steps, num_classes = lp.shape
target = tuple(int(y) for y in problem.targets)
scores_list: list[float] = []
for idx in range(num_classes**n_steps):
seq, rem = [], idx
for _ in range(n_steps):
seq.append(rem % num_classes)
rem //= num_classes
if problem.collapse(seq) == target:
scores_list.append(float(sum(lp[t, seq[t]] for t in range(n_steps))))
return _logsumexp(np.array(scores_list), beta)brute_force_shortest_path
omnibias.struct.brute_force_shortest_pathSource ↗brute_force_shortest_path(dag: DAG) -> tuple[float, tuple[int, ...]]Exact minimum-cost path by enumerating all source -> sink paths (oracle).
Parameters
| Name | Type & default | Contract |
|---|---|---|
dagpositional-or-keyword | DAGRequired | See the operation contract and implementation below. |
tuple[float, tuple[int, ...]]Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-shortest_path]" -qRegression example · shortest path matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_shortest_path_matches_bruteforce(seed: int) -> None:
dag = random_dag(seed)
cost, path = shortest_path(dag)
brute_cost, _ = brute_force_shortest_path(dag)
assert abs(cost - brute_cost) < 1e-9
assert path[0] == dag.source and path[-1] == dag.sink
assert abs(dag.path_cost(path) - cost) < 1e-9python -m pytest packages/omnibias-struct/tests/test_hard_dp.py -k test_shortest_path_matches_bruteforce -qRead the implementation
def brute_force_shortest_path(dag: DAG) -> tuple[float, tuple[int, ...]]:
r"""Exact minimum-cost path by enumerating all ``source -> sink`` paths (oracle)."""
best_cost: float = math.inf
best_path: tuple[int, ...] = ()
for path in dag.enumerate_paths():
cost = dag.path_cost(path)
if cost < best_cost:
best_cost, best_path = cost, path
return best_cost, best_pathbrute_force_viterbi
omnibias.struct.brute_force_viterbiSource ↗brute_force_viterbi(trellis: ChainTrellis) -> tuple[float, tuple[int, ...]]Exact best path by enumerating all S ** T state sequences (oracle).
Parameters
| Name | Type & default | Contract |
|---|---|---|
trellispositional-or-keyword | ChainTrellisRequired | See the operation contract and implementation below. |
tuple[float, tuple[int, ...]]Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-viterbi]" -qRegression example · viterbi matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_viterbi_matches_bruteforce(seed: int) -> None:
trellis = random_chain(seed)
value, path = viterbi(trellis)
brute_value, brute_path = brute_force_viterbi(trellis)
assert abs(value - brute_value) < 1e-9
# the returned path is a genuine argmax path (its own score equals the optimum)
assert abs(trellis.path_score(path) - value) < 1e-9
assert abs(trellis.path_score(brute_path) - brute_value) < 1e-9python -m pytest packages/omnibias-struct/tests/test_hard_dp.py -k test_viterbi_matches_bruteforce -qRead the implementation
def brute_force_viterbi(trellis: ChainTrellis) -> tuple[float, tuple[int, ...]]:
r"""Exact best path by enumerating all ``S ** T`` state sequences (oracle)."""
best_value: float = -math.inf
best_path: tuple[int, ...] = ()
for path in trellis.enumerate_paths():
value = trellis.path_score(path)
if value > best_value:
best_value, best_path = value, path
return best_value, best_pathctc_best
omnibias.struct.ctc_bestSource ↗ctc_best(lattice: CTCLattice, log_probs: object) -> floatBest single-alignment score (max over CTC alignments) for log_probs (T, C).
Parameters
| Name | Type & default | Contract |
|---|---|---|
latticepositional-or-keyword | CTCLatticeRequired | See the operation contract and implementation below. |
log_probspositional-or-keyword | objectRequired | See the operation contract and implementation below. |
floatExecuted regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-ctc]" -qRegression example · ctc best matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_ctc_best_matches_bruteforce(seed: int) -> None:
lattice, log_probs = sample_ctc(seed)
assert abs(ctc_best(lattice, log_probs) - brute_force_ctc(lattice, log_probs)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_hard_dp.py -k test_ctc_best_matches_bruteforce -qRead the implementation
def ctc_best(lattice: CTCLattice, log_probs: object) -> float:
r"""Best single-alignment score (max over CTC alignments) for ``log_probs`` ``(T, C)``."""
return ctc_best_alignment(lattice, log_probs)[0]ctc_best_alignment
omnibias.struct.ctc_best_alignmentSource ↗ctc_best_alignment(lattice: CTCLattice, log_probs: object) -> tuple[float, tuple[int, ...]]Best CTC alignment (max-score traceback) and its score for log_probs (T, C).
Returns (value, alignment) where alignment is the length-T class-id
sequence that attains the best score; lattice.collapse(alignment) equals
lattice.targets. The Viterbi analogue of ctc_best, exposing the traceback
(which ctc_best discards) for parity with viterbi / shortest_path.
Parameters
| Name | Type & default | Contract |
|---|---|---|
latticepositional-or-keyword | CTCLatticeRequired | See the operation contract and implementation below. |
log_probspositional-or-keyword | objectRequired | See the operation contract and implementation below. |
tuple[float, tuple[int, ...]]Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-ctc]" -qRegression example · ctc best alignment value and collapse
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_ctc_best_alignment_value_and_collapse(seed: int) -> None:
lattice, lp = sample_ctc(seed)
value, alignment = ctc_best_alignment(lattice, lp)
assert abs(value - ctc_best(lattice, lp)) < 1e-12
assert abs(value - brute_force_ctc(lattice, lp)) < 1e-9
assert len(alignment) == lp.shape[0]
assert lattice.collapse(alignment) == tuple(int(y) for y in lattice.targets)
assert abs(sum(lp[t, alignment[t]] for t in range(lp.shape[0])) - value) < 1e-9python -m pytest packages/omnibias-struct/tests/test_core_harden.py -k test_ctc_best_alignment_value_and_collapse -qRead the implementation
def ctc_best_alignment(lattice: CTCLattice, log_probs: object) -> tuple[float, tuple[int, ...]]:
r"""Best CTC alignment (max-score traceback) and its score for ``log_probs`` ``(T, C)``.
Returns ``(value, alignment)`` where ``alignment`` is the length-``T`` class-id
sequence that attains the best score; ``lattice.collapse(alignment)`` equals
``lattice.targets``. The Viterbi analogue of :func:`ctc_best`, exposing the traceback
(which :func:`ctc_best` discards) for parity with :func:`viterbi` / :func:`shortest_path`.
"""
lp = np.asarray(log_probs, dtype=float)
n_steps = lp.shape[0]
ext = lattice.extended_labels()
m = int(ext.shape[0])
f = np.full((n_steps, m), -math.inf)
back = np.full((n_steps, m), -1, dtype=int)
f[0, 0] = lp[0, ext[0]]
if m > 1:
f[0, 1] = lp[0, ext[1]]
for t in range(1, n_steps):
for s in range(m):
preds = lattice.incoming(s)
j = max(preds, key=lambda p: f[t - 1, p])
if f[t - 1, j] == -math.inf:
continue
f[t, s] = lp[t, ext[s]] + f[t - 1, j]
back[t, s] = j
ends = [m - 1] + ([m - 2] if m >= 2 else [])
best_end = max(ends, key=lambda s: f[n_steps - 1, s])
value = float(f[n_steps - 1, best_end])
positions = [best_end]
for t in range(n_steps - 1, 0, -1):
positions.append(int(back[t, positions[-1]]))
positions.reverse()
alignment = tuple(int(ext[s]) for s in positions)
return value, alignmentshortest_path
omnibias.struct.shortest_pathSource ↗shortest_path(dag: DAG) -> tuple[float, tuple[int, ...]]Minimum-cost source -> sink path of a DAG and its cost.
Parameters
| Name | Type & default | Contract |
|---|---|---|
dagpositional-or-keyword | DAGRequired | See the operation contract and implementation below. |
tuple[float, tuple[int, ...]]Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-shortest_path]" -qRegression example · shortest path matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_shortest_path_matches_bruteforce(seed: int) -> None:
dag = random_dag(seed)
cost, path = shortest_path(dag)
brute_cost, _ = brute_force_shortest_path(dag)
assert abs(cost - brute_cost) < 1e-9
assert path[0] == dag.source and path[-1] == dag.sink
assert abs(dag.path_cost(path) - cost) < 1e-9python -m pytest packages/omnibias-struct/tests/test_hard_dp.py -k test_shortest_path_matches_bruteforce -qRead the implementation
def shortest_path(dag: DAG) -> tuple[float, tuple[int, ...]]:
r"""Minimum-cost ``source -> sink`` path of a :class:`DAG` and its cost."""
weights = dag.weight_matrix()
dist = np.full(dag.num_nodes, np.inf)
dist[dag.source] = 0.0
back = [-1] * dag.num_nodes
for v in range(dag.num_nodes):
if v == dag.source:
dist[v] = 0.0
continue
preds = dag.incoming(v)
if not preds:
continue
vals = [dist[u] + weights[u, v] for u in preds]
j = int(np.argmin(vals))
dist[v], back[v] = vals[j], preds[j]
cost = float(dist[dag.sink])
path = [dag.sink]
node = dag.sink
while node != dag.source and back[node] != -1:
node = back[node]
path.append(node)
path.reverse()
return cost, tuple(path)viterbi
omnibias.struct.viterbiSource ↗viterbi(trellis: ChainTrellis) -> tuple[float, tuple[int, ...]]Best (max-score) state path of a ChainTrellis and its score.
Parameters
| Name | Type & default | Contract |
|---|---|---|
trellispositional-or-keyword | ChainTrellisRequired | See the operation contract and implementation below. |
tuple[float, tuple[int, ...]]Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-viterbi]" -qRegression example · certifies well separated winner and matches viterbi
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certifies_well_separated_winner_and_matches_viterbi() -> None:
emis = np.array([[3.0, 0.0], [0.0, 3.0], [3.0, 0.0]])
trans = np.array([[1.0, 0.0], [0.0, 1.0]])
cert = certify_decoding(emis, trans, eps=0.25)
_, winner = viterbi(ChainTrellis(emis, trans, np.zeros(2)))
assert cert.winner == winner
assert cert.certified
assert cert.min_margin > 0.0python -m pytest packages/omnibias-struct/tests/test_decode.py -k test_certifies_well_separated_winner_and_matches_viterbi -qRead the implementation
def viterbi(trellis: ChainTrellis) -> tuple[float, tuple[int, ...]]:
r"""Best (max-score) state path of a :class:`ChainTrellis` and its score."""
emissions, transitions, start = trellis.emissions, trellis.transitions, trellis.start
n_steps, n_states = trellis.n_steps, trellis.n_states
v = start + emissions[0]
back = np.zeros((n_steps, n_states), dtype=int)
for t in range(1, n_steps):
scores = v[:, None] + transitions # (S_prev, S)
best_prev = np.argmax(scores, axis=0)
back[t] = best_prev
v = emissions[t] + scores[best_prev, np.arange(n_states)]
last = int(np.argmax(v))
value = float(v[last])
path = [last]
for t in range(n_steps - 1, 0, -1):
last = int(back[t, last])
path.append(last)
path.reverse()
return value, tuple(path)brute_force_mas
omnibias.struct.brute_force_masSource ↗brute_force_mas(score: FloatArray) -> floatBest alignment score by enumerating every valid alignment (oracle).
Parameters
| Name | Type & default | Contract |
|---|---|---|
scorepositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
floatExecuted regression · soft mas matches oracle and marginals equal autograd
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_mas_matches_oracle_and_marginals_equal_autograd() -> None:
rng = np.random.default_rng(2)
score = rng.standard_normal((3, 5))
st = torch.tensor(score)
hard = hard_mas(score)
assert abs(hard - brute_force_mas(score)) < 1e-9
for beta in (0.5, 2.0, 8.0):
assert abs(float(tmono.soft_mas(st, beta)) - brute_force_soft_mas(score, beta)) < 1e-9
stg = torch.tensor(score, requires_grad=True)
tmono.soft_mas(stg, 3.0).backward()
marg = tmono.soft_mas_marginals(torch.tensor(score), 3.0)
assert torch.max(torch.abs(stg.grad - marg)).item() < 1e-9
assert torch.allclose(marg.sum(dim=0), torch.ones(5), atol=1e-9) # each frame assigned oncepython -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_mas_matches_oracle_and_marginals_equal_autograd" -qRegression example · soft mas certified gap and parity
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_mas_certified_gap_and_parity() -> None:
from omnibias.struct import count_alignments # noqa: PLC0415
rng = np.random.default_rng(3)
score = rng.standard_normal((3, 5))
st, sj = torch.tensor(score), jnp.asarray(score)
hard = hard_mas(score)
n = count_alignments(3, 5)
for beta in (1.0, 4.0, 16.0):
soft = float(tmono.soft_mas(st, beta))
cert = certify_soft_dp(hard, soft, n, beta, brute_force_value=brute_force_mas(score))
assert cert.is_sound
assert abs(soft - float(jmono.soft_mas(sj, beta))) < 1e-9
m_t = tmono.soft_mas_marginals(st, 4.0).numpy()
m_j = np.asarray(jmono.soft_mas_marginals(sj, 4.0))
assert np.max(np.abs(m_t - m_j)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_plan_attn.py -k test_soft_mas_certified_gap_and_parity -qRead the implementation
def brute_force_mas(score: FloatArray) -> float:
r"""Best alignment score by enumerating every valid alignment (oracle)."""
s = np.asarray(score, dtype=float)
n_tokens, n_frames = _validate(s)
return max(
float(sum(s[i, j] for j, i in enumerate(a)))
for a in enumerate_alignments(n_tokens, n_frames)
)brute_force_soft_mas
omnibias.struct.brute_force_soft_masSource ↗brute_force_soft_mas(score: FloatArray, beta: float) -> floatExact soft-MAS beta^-1 log sum_alignments exp(beta score) (global softmax).
Parameters
| Name | Type & default | Contract |
|---|---|---|
scorepositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · soft mas matches oracle and marginals equal autograd
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_mas_matches_oracle_and_marginals_equal_autograd() -> None:
rng = np.random.default_rng(2)
score = rng.standard_normal((3, 5))
st = torch.tensor(score)
hard = hard_mas(score)
assert abs(hard - brute_force_mas(score)) < 1e-9
for beta in (0.5, 2.0, 8.0):
assert abs(float(tmono.soft_mas(st, beta)) - brute_force_soft_mas(score, beta)) < 1e-9
stg = torch.tensor(score, requires_grad=True)
tmono.soft_mas(stg, 3.0).backward()
marg = tmono.soft_mas_marginals(torch.tensor(score), 3.0)
assert torch.max(torch.abs(stg.grad - marg)).item() < 1e-9
assert torch.allclose(marg.sum(dim=0), torch.ones(5), atol=1e-9) # each frame assigned oncepython -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_mas_matches_oracle_and_marginals_equal_autograd" -qRead the implementation
def brute_force_soft_mas(score: FloatArray, beta: float) -> float:
r"""Exact soft-MAS ``beta^-1 log sum_alignments exp(beta score)`` (global softmax)."""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
s = np.asarray(score, dtype=float)
n_tokens, n_frames = _validate(s)
scores = np.array(
[float(sum(s[i, j] for j, i in enumerate(a))) for a in enumerate_alignments(n_tokens, n_frames)]
)
mx = float(np.max(scores))
return mx + math.log(float(np.sum(np.exp(beta * (scores - mx))))) / betacount_alignments
omnibias.struct.count_alignmentsSource ↗count_alignments(n_tokens: int, n_frames: int) -> intNumber of monotonic-surjective alignments C(T-1, L-1).
Parameters
| Name | Type & default | Contract |
|---|---|---|
n_tokenspositional-or-keyword | intRequired | See the operation contract and implementation below. |
n_framespositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExecuted regression · soft mas certified gap and parity
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_mas_certified_gap_and_parity() -> None:
from omnibias.struct import count_alignments # noqa: PLC0415
rng = np.random.default_rng(3)
score = rng.standard_normal((3, 5))
st, sj = torch.tensor(score), jnp.asarray(score)
hard = hard_mas(score)
n = count_alignments(3, 5)
for beta in (1.0, 4.0, 16.0):
soft = float(tmono.soft_mas(st, beta))
cert = certify_soft_dp(hard, soft, n, beta, brute_force_value=brute_force_mas(score))
assert cert.is_sound
assert abs(soft - float(jmono.soft_mas(sj, beta))) < 1e-9
m_t = tmono.soft_mas_marginals(st, 4.0).numpy()
m_j = np.asarray(jmono.soft_mas_marginals(sj, 4.0))
assert np.max(np.abs(m_t - m_j)) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_mas_certified_gap_and_parity" -qRead the implementation
def count_alignments(n_tokens: int, n_frames: int) -> int:
r"""Number of monotonic-surjective alignments ``C(T-1, L-1)``."""
if n_frames < n_tokens:
return 0
return int(math.comb(n_frames - 1, n_tokens - 1))hard_mas
omnibias.struct.hard_masSource ↗hard_mas(score: FloatArray) -> floatBest monotonic-surjective alignment score of an (L, T) score matrix.
Parameters
| Name | Type & default | Contract |
|---|---|---|
scorepositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
floatExecuted regression · soft mas matches oracle and marginals equal autograd
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_mas_matches_oracle_and_marginals_equal_autograd() -> None:
rng = np.random.default_rng(2)
score = rng.standard_normal((3, 5))
st = torch.tensor(score)
hard = hard_mas(score)
assert abs(hard - brute_force_mas(score)) < 1e-9
for beta in (0.5, 2.0, 8.0):
assert abs(float(tmono.soft_mas(st, beta)) - brute_force_soft_mas(score, beta)) < 1e-9
stg = torch.tensor(score, requires_grad=True)
tmono.soft_mas(stg, 3.0).backward()
marg = tmono.soft_mas_marginals(torch.tensor(score), 3.0)
assert torch.max(torch.abs(stg.grad - marg)).item() < 1e-9
assert torch.allclose(marg.sum(dim=0), torch.ones(5), atol=1e-9) # each frame assigned oncepython -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_mas_matches_oracle_and_marginals_equal_autograd" -qRegression example · soft mas certified gap and parity
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_mas_certified_gap_and_parity() -> None:
from omnibias.struct import count_alignments # noqa: PLC0415
rng = np.random.default_rng(3)
score = rng.standard_normal((3, 5))
st, sj = torch.tensor(score), jnp.asarray(score)
hard = hard_mas(score)
n = count_alignments(3, 5)
for beta in (1.0, 4.0, 16.0):
soft = float(tmono.soft_mas(st, beta))
cert = certify_soft_dp(hard, soft, n, beta, brute_force_value=brute_force_mas(score))
assert cert.is_sound
assert abs(soft - float(jmono.soft_mas(sj, beta))) < 1e-9
m_t = tmono.soft_mas_marginals(st, 4.0).numpy()
m_j = np.asarray(jmono.soft_mas_marginals(sj, 4.0))
assert np.max(np.abs(m_t - m_j)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_plan_attn.py -k test_soft_mas_certified_gap_and_parity -qRead the implementation
def hard_mas(score: FloatArray) -> float:
r"""Best monotonic-surjective alignment score of an ``(L, T)`` score matrix."""
s = np.asarray(score, dtype=float)
n_tokens, n_frames = _validate(s)
q = np.full((n_tokens, n_frames), -np.inf)
q[0, 0] = s[0, 0]
for j in range(1, n_frames):
for i in range(min(j, n_tokens - 1) + 1):
stay = q[i, j - 1]
advance = q[i - 1, j - 1] if i > 0 else -np.inf
q[i, j] = s[i, j] + max(stay, advance)
return float(q[n_tokens - 1, n_frames - 1])brute_force_arborescence
omnibias.struct.brute_force_arborescenceSource ↗brute_force_arborescence(arc: FloatArray, beta: float | None=None) -> floatFlat oracle over *enumerated* arborescences: max (beta is None) or lse_beta.
With beta set this equals matrix_tree_partition to machine precision (the
determinant is the exact same sum); with beta is None it equals
hard_matrix_tree.
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | float | NoneDefault: None | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
scores.size == 0, raisesValueError('no arborescences (n must be >= 1)'). - When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · mtt edmonds equals hard and brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_mtt_edmonds_equals_hard_and_brute(seed: int) -> None:
assert probe_mtt_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_mtt_edmonds_equals_hard_and_brute[0]" -qRegression example · hard matrix tree matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_matrix_tree_matches_bruteforce(seed: int) -> None:
arc = _arc(seed, 4)
assert abs(hard_matrix_tree(arc) - brute_force_arborescence(arc, None)) < 1e-11python -m pytest packages/omnibias-struct/tests/test_mtt.py -k test_hard_matrix_tree_matches_bruteforce -qRead the implementation
def brute_force_arborescence(arc: FloatArray, beta: float | None = None) -> float:
r"""Flat oracle over *enumerated* arborescences: ``max`` (``beta is None``) or ``lse_beta``.
With ``beta`` set this equals :func:`matrix_tree_partition` to machine precision (the
determinant is the exact same sum); with ``beta is None`` it equals
:func:`hard_matrix_tree`.
"""
a = np.asarray(arc, dtype=float)
n = a.shape[0] - 1
scores = np.array(
[float(sum(a[heads[m], m] for m in range(1, n + 1))) for heads in iter_arborescences(n)]
)
if scores.size == 0:
raise ValueError("no arborescences (n must be >= 1)")
if beta is None:
return float(np.max(scores))
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
hi = float(np.max(scores))
return hi + math.log(float(np.sum(np.exp(beta * (scores - hi))))) / betacount_arborescences
omnibias.struct.count_arborescencesSource ↗count_arborescences(n_words: int) -> intNumber of spanning arborescences rooted at 0 over n_words -- (n + 1)^(n - 1).
Cayley's formula (spanning trees of the complete graph K_{n+1}, each oriented away
from the fixed root 0); this is the N in the log(N) / beta gap bound.
Parameters
| Name | Type & default | Contract |
|---|---|---|
n_wordspositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
n_words < 1, raisesValueError(f'n_words must be >= 1, got {n_words}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · family gap sandwich is sound
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_family_gap_sandwich_is_sound(probe) -> None: # noqa: ANN001
pytest.importorskip("torch")
rec = probe(0, BETA, "torch")
assert rec.ok
assert rec.metrics["realized_gap"] <= rec.metrics["bound"] + 1e-9python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_family_gap_sandwich_is_sound[probe_mtt_gap]" -qRegression example · count arborescences matches bruteforce and cayley
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_count_arborescences_matches_bruteforce_and_cayley(n_words: int) -> None:
n = count_arborescences(n_words)
assert n == sum(1 for _ in iter_arborescences(n_words))
assert n == (n_words + 1) ** (n_words - 1)python -m pytest packages/omnibias-struct/tests/test_mtt.py -k test_count_arborescences_matches_bruteforce_and_cayley -qRead the implementation
def count_arborescences(n_words: int) -> int:
r"""Number of spanning arborescences rooted at ``0`` over ``n_words`` -- ``(n + 1)^(n - 1)``.
Cayley's formula (spanning trees of the complete graph ``K_{n+1}``, each oriented away
from the fixed root ``0``); this is the ``N`` in the ``log(N) / beta`` gap bound.
"""
if n_words < 1:
raise ValueError(f"n_words must be >= 1, got {n_words}")
return int((n_words + 1) ** (n_words - 1))hard_matrix_tree
omnibias.struct.hard_matrix_treeSource ↗hard_matrix_tree(arc: FloatArray) -> floatScore of the maximum spanning arborescence (Chu-Liu/Edmonds), independent of the det.
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
floatExecuted regression · mtt edmonds equals hard and brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_mtt_edmonds_equals_hard_and_brute(seed: int) -> None:
assert probe_mtt_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_mtt_edmonds_equals_hard_and_brute[0]" -qRegression example · hard matrix tree matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_matrix_tree_matches_bruteforce(seed: int) -> None:
arc = _arc(seed, 4)
assert abs(hard_matrix_tree(arc) - brute_force_arborescence(arc, None)) < 1e-11python -m pytest packages/omnibias-struct/tests/test_mtt.py -k test_hard_matrix_tree_matches_bruteforce -qRead the implementation
def hard_matrix_tree(arc: FloatArray) -> float:
r"""Score of the maximum spanning arborescence (Chu-Liu/Edmonds), independent of the det."""
return max_arborescence(arc)[0]iter_arborescences
omnibias.struct.iter_arborescencesSource ↗iter_arborescences(n_words: int) -> Iterator[dict[int, int]]Yield every valid spanning arborescence head map {modifier: head} (brute force).
Parameters
| Name | Type & default | Contract |
|---|---|---|
n_wordspositional-or-keyword | intRequired | See the operation contract and implementation below. |
Iterator[dict[int, int]]Explicit validation & failure cases
- When
n_words < 1, raisesValueError(f'n_words must be >= 1, got {n_words}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · mtt edmonds equals hard and brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_mtt_edmonds_equals_hard_and_brute(seed: int) -> None:
assert probe_mtt_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_mtt_edmonds_equals_hard_and_brute[0]" -qRegression example · count arborescences matches bruteforce and cayley
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_count_arborescences_matches_bruteforce_and_cayley(n_words: int) -> None:
n = count_arborescences(n_words)
assert n == sum(1 for _ in iter_arborescences(n_words))
assert n == (n_words + 1) ** (n_words - 1)python -m pytest packages/omnibias-struct/tests/test_mtt.py -k test_count_arborescences_matches_bruteforce_and_cayley -qRead the implementation
def iter_arborescences(n_words: int) -> Iterator[dict[int, int]]:
r"""Yield every valid spanning arborescence head map ``{modifier: head}`` (brute force)."""
if n_words < 1:
raise ValueError(f"n_words must be >= 1, got {n_words}")
for assignment in itertools.product(range(n_words + 1), repeat=n_words):
heads = {m: assignment[m - 1] for m in range(1, n_words + 1)}
if any(heads[m] == m for m in range(1, n_words + 1)):
continue
if _reaches_root(heads, n_words):
yield headsmatrix_tree_marginals
omnibias.struct.matrix_tree_marginalsSource ↗matrix_tree_marginals(arc: FloatArray, beta: float) -> FloatArrayClosed-form arc marginals P_beta(h -> m) via L^{-1} (Koo et al. 2007).
Returns an (n + 1, n + 1) matrix; [h, m] is the probability that arc h -> m is
in a sampled arborescence. Equals d matrix_tree_partition / d arc exactly, and every
modifier column m >= 1 sums to 1 (each word takes exactly one head). Column-max
stabilised so it matches the differentiable backends at any beta.
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
FloatArrayExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Read the implementation
def matrix_tree_marginals(arc: FloatArray, beta: float) -> FloatArray:
r"""Closed-form arc marginals ``P_beta(h -> m)`` via ``L^{-1}`` (Koo et al. 2007).
Returns an ``(n + 1, n + 1)`` matrix; ``[h, m]`` is the probability that arc ``h -> m`` is
in a sampled arborescence. Equals ``d matrix_tree_partition / d arc`` exactly, and every
modifier column ``m >= 1`` sums to ``1`` (each word takes exactly one head). Column-max
stabilised so it matches the differentiable backends at any ``beta``.
"""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
a = np.asarray(arc, dtype=float)
n = a.shape[0] - 1
ltilde, c = _stabilised_laplacian(a, beta)
binv = np.linalg.inv(ltilde)
diag_b = np.diag(binv)
out = np.zeros((n + 1, n + 1))
for m in range(1, n + 1):
root_tilde = math.exp(beta * a[0, m] - c[m - 1])
out[0, m] = root_tilde * diag_b[m - 1]
for h in range(1, n + 1):
if h == m:
continue
a_tilde = math.exp(beta * a[h, m] - c[m - 1])
out[h, m] = a_tilde * (diag_b[m - 1] - binv[m - 1, h - 1])
return outmatrix_tree_partition
omnibias.struct.matrix_tree_partitionSource ↗matrix_tree_partition(arc: FloatArray, beta: float) -> floatExact non-projective soft value log det L(beta) / beta (numpy oracle).
The determinant sums exp(beta * score) over *all* spanning arborescences exactly, so
this is not an lse_beta relaxation -- it equals the flat
brute_force_arborescence partition to machine precision. As beta -> inf it
decreases to the maximum-arborescence score (hard_matrix_tree).
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}'). - When
sign <= 0.0, raisesValueError('Laplacian determinant is non-positive; arc weights are degenerate').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · soft matrix tree is exact
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_matrix_tree_is_exact(seed: int) -> None:
# The determinant partition is the *exact* sum over arborescences, not an lse bound.
arc = _arc(seed, 4)
at, aj = torch.tensor(arc), jnp.asarray(arc)
for beta in (1.0, 4.0, 16.0):
ref = brute_force_arborescence(arc, beta)
assert abs(matrix_tree_partition(arc, beta) - ref) < 1e-9
assert abs(float(st.soft_matrix_tree(at, beta)) - ref) < 1e-9
assert abs(float(sj.soft_matrix_tree(aj, beta)) - ref) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_mtt.py::test_soft_matrix_tree_is_exact[0]" -qRegression example · matrix tree partition iv encloses exact partition over box
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_matrix_tree_partition_iv_encloses_exact_partition_over_box() -> None:
rng = np.random.default_rng(14)
n = 3
# A modestly-scaled (well-conditioned) arc box: the interval determinant certifies det > 0.
arc0 = 0.3 * rng.standard_normal((n + 1, n + 1))
arc0[:, 0] = 0.0 # ROOT is never a modifier
radius, beta = 0.05, 1.5
iv = matrix_tree_partition_iv(box(arc0, radius), beta)
for _ in range(150):
arcp = arc0 + rng.uniform(-radius, radius, arc0.shape)
arcp[:, 0] = 0.0
assert iv.lo - TOL <= brute_force_arborescence(arcp, beta) <= iv.hi + TOL
# at radius 0 the interval determinant pins the exact log-det partition
point = matrix_tree_partition_iv(
[[Interval.point(float(arc0[i, j])) for j in range(n + 1)] for i in range(n + 1)], beta
)
exact = matrix_tree_partition(arc0, beta)
assert point.lo - TOL <= exact <= point.hi + TOLpython -m pytest packages/omnibias-struct/tests/test_verified.py -k test_matrix_tree_partition_iv_encloses_exact_partition_over_box -qRead the implementation
def matrix_tree_partition(arc: FloatArray, beta: float) -> float:
r"""Exact non-projective soft value ``log det L(beta) / beta`` (numpy oracle).
The determinant sums ``exp(beta * score)`` over *all* spanning arborescences exactly, so
this is not an ``lse_beta`` relaxation -- it equals the flat
:func:`brute_force_arborescence` partition to machine precision. As ``beta -> inf`` it
decreases to the maximum-arborescence score (:func:`hard_matrix_tree`).
"""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
ltilde, c = _stabilised_laplacian(arc, beta)
sign, logabsdet = np.linalg.slogdet(ltilde)
if sign <= 0.0:
raise ValueError("Laplacian determinant is non-positive; arc weights are degenerate")
return float((logabsdet + float(np.sum(c))) / beta)max_arborescence
omnibias.struct.max_arborescenceSource ↗max_arborescence(arc: FloatArray) -> tuple[float, dict[int, int]]Chu-Liu/Edmonds maximum spanning arborescence rooted at 0 (multi-root).
Returns (score, heads) with heads[m] the chosen head of word m and score
the summed arc scores -- the beta -> inf limit of matrix_tree_partition.
Parameters
| Name | Type & default | Contract |
|---|---|---|
arcpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
tuple[float, dict[int, int]]Explicit validation & failure cases
- When
n < 1, raisesValueError(f'need at least one word (arc >= 2x2), got n={n}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · mtt edmonds equals hard and brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_mtt_edmonds_equals_hard_and_brute(seed: int) -> None:
assert probe_mtt_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_mtt_edmonds_equals_hard_and_brute[0]" -qRegression example · max arborescence is valid
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_max_arborescence_is_valid(seed: int) -> None:
arc = _arc(seed, 5)
score, heads = max_arborescence(arc)
assert abs(score - hard_matrix_tree(arc)) < 1e-12
assert set(heads) == set(range(1, 6)) # every word takes a head
# following heads from any word reaches the ROOT (0) without a cycle
for m in range(1, 6):
seen: set[int] = set()
cur = m
while cur != 0:
assert cur not in seen
seen.add(cur)
cur = heads[cur]python -m pytest packages/omnibias-struct/tests/test_mtt.py -k test_max_arborescence_is_valid -qRead the implementation
def max_arborescence(arc: FloatArray) -> tuple[float, dict[int, int]]:
r"""Chu-Liu/Edmonds maximum spanning arborescence rooted at ``0`` (multi-root).
Returns ``(score, heads)`` with ``heads[m]`` the chosen head of word ``m`` and ``score``
the summed arc scores -- the ``beta -> inf`` limit of :func:`matrix_tree_partition`.
"""
a = np.asarray(arc, dtype=float)
n = a.shape[0] - 1
if n < 1:
raise ValueError(f"need at least one word (arc >= 2x2), got n={n}")
nodes = set(range(n + 1))
weight = {(h, m): float(a[h, m]) for m in range(1, n + 1) for h in range(n + 1) if h != m}
heads = _edmonds(nodes, 0, weight)
score = float(sum(a[heads[m], m] for m in range(1, n + 1)))
return score, {m: heads[m] for m in range(1, n + 1)}brute_force_entropy
omnibias.struct.brute_force_entropySource ↗brute_force_entropy(graph: Hypergraph, weights: Sequence[float], beta: float) -> floatShannon entropy (nats) of p_beta by flat enumeration -- the oracle for the identity.
H = -sum_D p_beta(D) log p_beta(D); equals the closed-form beta (V_beta - E[score]).
Ranges from log(#derivations) as beta -> 0 to log(#argmax) as beta -> inf.
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
weightspositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}'). - When
scores.size == 0, raisesValueError('graph has no complete derivations (root unreachable)').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · entropy identity and mc
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_entropy_identity_and_mc(backend: str) -> None:
pytest.importorskip(backend)
rec = probe_entropy(0, BETA, backend)
assert rec.ok, rec
assert rec.metrics["identity_err"] < 1e-8python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_entropy_identity_and_mc[jax]" -qRegression example · path entropy matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_path_entropy_matches_bruteforce(seed: int) -> None:
w = _weights(seed)
wt, wj = torch.tensor(w), jnp.asarray(w)
for beta in (0.5, 2.0, 8.0):
ref = brute_force_entropy(GRAPH, w, beta)
assert abs(float(st.path_entropy(GRAPH, wt, beta)) - ref) < 1e-9
assert abs(float(sj.path_entropy(GRAPH, wj, beta)) - ref) < 1e-9python -m pytest packages/omnibias-struct/tests/test_operators.py -k test_path_entropy_matches_bruteforce -qRead the implementation
def brute_force_entropy(graph: Hypergraph, weights: Sequence[float], beta: float) -> float:
r"""Shannon entropy (nats) of ``p_beta`` by flat enumeration -- the oracle for the identity.
``H = -sum_D p_beta(D) log p_beta(D)``; equals the closed-form ``beta (V_beta - E[score])``.
Ranges from ``log(#derivations)`` as ``beta -> 0`` to ``log(#argmax)`` as ``beta -> inf``.
"""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
scores = np.array(
[derivation_weight(weights, d) for d in enumerate_derivations(graph)], dtype=float
)
if scores.size == 0:
raise ValueError("graph has no complete derivations (root unreachable)")
m = float(np.max(scores))
probs = np.exp(beta * (scores - m))
probs /= float(np.sum(probs))
nz = probs > 0.0
return float(-np.sum(probs[nz] * np.log(probs[nz])))brute_force_kbest
omnibias.struct.brute_force_kbestSource ↗brute_force_kbest(graph: Hypergraph, weights: Sequence[float], k: int) -> list[tuple[float, tuple[int, ...]]]Enumerate-and-sort oracle for kbest_derivations (exponential; tiny graphs).
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
weightspositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
list[tuple[float, tuple[int, ...]]]Explicit validation & failure cases
- When
k < 1, raisesValueError(f'k must be >= 1, got {k}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qRegression example · topk paths matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_topk_paths_matches_bruteforce(seed: int) -> None:
w = _weights(seed)
kb = st.topk_paths(GRAPH, torch.tensor(w), 6)
bk = brute_force_kbest(GRAPH, w, 6)
assert [round(s, 10) for s, _ in kb] == [round(s, 10) for s, _ in bk]python -m pytest packages/omnibias-struct/tests/test_operators.py -k test_topk_paths_matches_bruteforce -qRead the implementation
def brute_force_kbest(
graph: Hypergraph, weights: Sequence[float], k: int
) -> list[tuple[float, tuple[int, ...]]]:
r"""Enumerate-and-sort oracle for :func:`kbest_derivations` (exponential; tiny graphs)."""
if k < 1:
raise ValueError(f"k must be >= 1, got {k}")
scored = [(derivation_weight(weights, d), d) for d in enumerate_derivations(graph)]
scored.sort(key=lambda x: -x[0])
return scored[:k]kbest_derivations
omnibias.struct.kbest_derivationsSource ↗kbest_derivations(graph: Hypergraph, weights: Sequence[float], k: int) -> list[tuple[float, tuple[int, ...]]]Exact k-best derivations by score (descending) -- the topological k-best DP.
Huang & Chiang (2005): the head's k-best are generated from the k-best of the tails, so a
single topological sweep keeping the top k per node is exact. Returns (score,
edge-tuple) pairs, at most k (fewer if the graph has fewer derivations).
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
weightspositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
list[tuple[float, tuple[int, ...]]]Explicit validation & failure cases
- When
k < 1, raisesValueError(f'k must be >= 1, got {k}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qRead the implementation
def kbest_derivations(
graph: Hypergraph, weights: Sequence[float], k: int
) -> list[tuple[float, tuple[int, ...]]]:
r"""Exact ``k``-best derivations by score (descending) -- the topological k-best DP.
Huang & Chiang (2005): the head's k-best are generated from the k-best of the tails, so a
single topological sweep keeping the top ``k`` per node is exact. Returns ``(score,
edge-tuple)`` pairs, at most ``k`` (fewer if the graph has fewer derivations).
"""
if k < 1:
raise ValueError(f"k must be >= 1, got {k}")
w = np.asarray(weights, dtype=float)
kbest: list[list[tuple[float, tuple[int, ...]]]] = [[] for _ in range(graph.num_nodes)]
for v in range(graph.num_nodes):
inc = graph.incoming(v)
if not inc:
continue
cands: list[tuple[float, tuple[int, ...]]] = []
for ei in inc:
e = graph.edges[ei]
tail_lists = [kbest[t] for t in e.tails]
if any(len(tl) == 0 for tl in tail_lists):
continue # a tail has no sub-derivation yet (unreachable)
for combo in _combine(tail_lists, k):
score = float(w[ei]) + float(sum(c[0] for c in combo))
deriv = (ei, *[x for c in combo for x in c[1]])
cands.append((score, deriv))
cands.sort(key=lambda x: -x[0])
kbest[v] = cands[:k]
return kbest[graph.root]sample_derivations
omnibias.struct.sample_derivationsSource ↗sample_derivations(graph: Hypergraph, weights: Sequence[float], beta: float, num_samples: int, seed: int | None=None) -> tuple[FloatArray, list[tuple[int, ...]]]Exact forward-filtering backward-sampling of num_samples derivations from p_beta.
Returns (counts, samples): counts is (num_samples, num_edges) per-edge usage
counts and samples the chosen edge-index tuples. Each derivation is drawn *exactly*
from p_beta (top-down, choosing each node's incoming edge with the tower softmax of
edge_weight + inside(tails)), so counts.mean(0) -> the closed-form marginals.
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
weightspositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
num_samplespositional-or-keyword | intRequired | See the operation contract and implementation below. |
seedpositional-or-keyword | int | NoneDefault: None | See the operation contract and implementation below. |
tuple[FloatArray, list[tuple[int, ...]]]Explicit validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}'). - When
num_samples < 1, raisesValueError(f'num_samples must be >= 1, got {num_samples}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · sampler empirical marginals converge
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_sampler_empirical_marginals_converge(backend: str) -> None:
pytest.importorskip(backend)
assert probe_sampling(0, BETA, backend).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_sampler_empirical_marginals_converge[jax]" -qRead the implementation
def sample_derivations(
graph: Hypergraph,
weights: Sequence[float],
beta: float,
num_samples: int,
seed: int | None = None,
) -> tuple[FloatArray, list[tuple[int, ...]]]:
r"""Exact forward-filtering backward-sampling of ``num_samples`` derivations from ``p_beta``.
Returns ``(counts, samples)``: ``counts`` is ``(num_samples, num_edges)`` per-edge usage
counts and ``samples`` the chosen edge-index tuples. Each derivation is drawn *exactly*
from ``p_beta`` (top-down, choosing each node's incoming edge with the tower softmax of
``edge_weight + inside(tails)``), so ``counts.mean(0) -> `` the closed-form marginals.
"""
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
if num_samples < 1:
raise ValueError(f"num_samples must be >= 1, got {num_samples}")
w = np.asarray(weights, dtype=float)
inside = _inside(graph, w, beta)
rng = np.random.default_rng(seed)
counts = np.zeros((num_samples, graph.num_edges))
samples: list[tuple[int, ...]] = []
for s in range(num_samples):
chosen: list[int] = []
stack = [graph.root]
while stack:
v = stack.pop()
inc = graph.incoming(v)
if not inc:
continue
rows = np.array(
[w[ei] + sum(inside[t] for t in graph.edges[ei].tails) for ei in inc]
)
m = float(np.max(rows))
probs = np.exp(beta * (rows - m))
probs /= float(np.sum(probs))
ei = int(inc[int(rng.choice(len(inc), p=probs))])
chosen.append(ei)
counts[s, ei] += 1.0
stack.extend(graph.edges[ei].tails)
samples.append(tuple(chosen))
return counts, samplesBinaryGrammar
omnibias.struct.BinaryGrammarSource ↗class BinaryGrammarDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
A Chomsky-normal-form grammar: num_nonterminals symbols and binary A -> B C rules.
rules is a tuple of (A, B, C) triples (head, left child, right child); start
is the goal nonterminal spanning the whole sentence. Every nonterminal may also be
lexical (emit a token) -- the emission scores are supplied per parse, not fixed here.
Parameters
| Name | Type & default | Contract |
|---|---|---|
num_nonterminalsdataclass field | intRequired | See the operation contract and implementation below. |
rulesdataclass field | tuple[tuple[int, int, int], ...]Required | See the operation contract and implementation below. |
startdataclass field | intDefault: 0 | See the operation contract and implementation below. |
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qRegression example · span marginals root is one
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_span_marginals_root_is_one() -> None:
emit, rule = _scores(0, 5)
sp = st.span_marginals(GRAMMAR, torch.tensor(emit), torch.tensor(rule), 4.0)
assert abs(float(sp[GRAMMAR.start, 0, 5]) - 1.0) < 1e-9python -m pytest packages/omnibias-struct/tests/test_parse.py -k test_span_marginals_root_is_one -qFields & methods
num_nonterminalsfield
num_nonterminals: intDeclared int field on BinaryGrammar. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗rulesfield
rules: tuple[tuple[int, int, int], ...]Declared tuple[tuple[int, int, int], ...] field on BinaryGrammar. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗startfield
start: int = 0Declared int field on BinaryGrammar. Default expression: 0.
Regression example · span marginals root is one
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_span_marginals_root_is_one() -> None:
emit, rule = _scores(0, 5)
sp = st.span_marginals(GRAMMAR, torch.tensor(emit), torch.tensor(rule), 4.0)
assert abs(float(sp[GRAMMAR.start, 0, 5]) - 1.0) < 1e-9python -m pytest packages/omnibias-struct/tests/test_parse.py -k test_span_marginals_root_is_one -q__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
self.num_nonterminals < 1, raisesValueError(f'num_nonterminals must be >= 1, got {self.num_nonterminals}'). - When
not 0 <= self.start < self.num_nonterminals, raisesValueError(f'start {self.start} out of range [0, {self.num_nonterminals})'). - When
not 0 <= x < self.num_nonterminals, raisesValueError(f'rule ({a},{b},{c}) has a symbol out of range').
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qMethod implementation
def __post_init__(self) -> None:
if self.num_nonterminals < 1:
raise ValueError(f"num_nonterminals must be >= 1, got {self.num_nonterminals}")
if not 0 <= self.start < self.num_nonterminals:
raise ValueError(f"start {self.start} out of range [0, {self.num_nonterminals})")
for a, b, c in self.rules:
for x in (a, b, c):
if not 0 <= x < self.num_nonterminals:
raise ValueError(f"rule ({a},{b},{c}) has a symbol out of range")num_rulesproperty
num_rules(self) -> intNumber of binary rules.
Returns: int
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qMethod implementation
def num_rules(self) -> int:
"""Number of binary rules."""
return len(self.rules)Read the implementation
class BinaryGrammar:
r"""A Chomsky-normal-form grammar: ``num_nonterminals`` symbols and binary ``A -> B C`` rules.
``rules`` is a tuple of ``(A, B, C)`` triples (head, left child, right child); ``start``
is the goal nonterminal spanning the whole sentence. Every nonterminal may also be
lexical (emit a token) -- the emission scores are supplied per parse, not fixed here.
"""
num_nonterminals: int
rules: tuple[tuple[int, int, int], ...]
start: int = 0
def __post_init__(self) -> None:
if self.num_nonterminals < 1:
raise ValueError(f"num_nonterminals must be >= 1, got {self.num_nonterminals}")
if not 0 <= self.start < self.num_nonterminals:
raise ValueError(f"start {self.start} out of range [0, {self.num_nonterminals})")
for a, b, c in self.rules:
for x in (a, b, c):
if not 0 <= x < self.num_nonterminals:
raise ValueError(f"rule ({a},{b},{c}) has a symbol out of range")
@property
def num_rules(self) -> int:
"""Number of binary rules."""
return len(self.rules)best_parse_tree
omnibias.struct.best_parse_treeSource ↗best_parse_tree(grammar: BinaryGrammar, emit: FloatArray, rule: FloatArray) -> tuple[float, Tree]Classic CKY Viterbi parse: the best score and its parse tree (nested tuples).
Parameters
| Name | Type & default | Contract |
|---|---|---|
grammarpositional-or-keyword | BinaryGrammarRequired | See the operation contract and implementation below. |
emitpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
rulepositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
tuple[float, Tree]Executed regression · best parse tree score and coverage
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_best_parse_tree_score_and_coverage(seed: int) -> None:
emit, rule = _scores(seed, 5)
score, tree = best_parse_tree(GRAMMAR, emit, rule)
assert abs(score - hard_cky(GRAMMAR, emit, rule)) < TOL
leaves: list[int] = []
def walk(node: tuple) -> None:
if len(node) == 2:
leaves.append(node[1])
else:
walk(node[3])
walk(node[4])
walk(tree)
assert leaves == list(range(5)) # the tree covers every token exactly once, in orderpython -m pytest "packages/omnibias-struct/tests/test_parse.py::test_best_parse_tree_score_and_coverage[0]" -qRead the implementation
def best_parse_tree(grammar: BinaryGrammar, emit: FloatArray, rule: FloatArray) -> tuple[float, Tree]:
r"""Classic CKY Viterbi parse: the best score and its parse tree (nested tuples)."""
e = np.asarray(emit, dtype=float)
r = np.asarray(rule, dtype=float)
length_l, r_nt = e.shape[0], grammar.num_nonterminals
neg = -math.inf
chart = np.full((r_nt, length_l + 1, length_l + 1), neg)
back: dict[tuple[int, int, int], tuple[int, int, int, int]] = {}
for i in range(length_l):
for a in range(r_nt):
chart[a, i, i + 1] = e[i, a]
for w in range(2, length_l + 1):
for i in range(0, length_l - w + 1):
j = i + w
for ridx, (a, b, c) in enumerate(grammar.rules):
for k in range(i + 1, j):
val = r[ridx] + chart[b, i, k] + chart[c, k, j]
if val > chart[a, i, j]:
chart[a, i, j] = val
back[(a, i, j)] = (ridx, b, c, k)
def build(a: int, i: int, j: int) -> Tree:
if j - i == 1:
return (a, i)
ridx, b, c, k = back[(a, i, j)]
return (a, i, j, build(b, i, k), build(c, k, j))
return float(chart[grammar.start, 0, length_l]), build(grammar.start, 0, length_l)brute_force_cky
omnibias.struct.brute_force_ckySource ↗brute_force_cky(grammar: BinaryGrammar, emit: FloatArray, rule: FloatArray, beta: float | None=None) -> floatFlat oracle over *enumerated* parse trees: max (beta is None) or lse_beta.
Parameters
| Name | Type & default | Contract |
|---|---|---|
grammarpositional-or-keyword | BinaryGrammarRequired | See the operation contract and implementation below. |
emitpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
rulepositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | float | NoneDefault: None | See the operation contract and implementation below. |
floatExecuted regression · parse hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_parse_hard_equals_brute_and_count(seed: int) -> None:
assert probe_parse_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_parse_hard_equals_brute_and_count[0]" -qRegression example · hard cky matches driver and bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_cky_matches_driver_and_bruteforce(seed: int) -> None:
emit, rule = _scores(seed, 4)
spec = build_chart(GRAMMAR, 4)
w = chart_edge_weights(spec, emit, rule)
hc = hard_cky(GRAMMAR, emit, rule)
assert abs(hc - hard_value(spec.graph, w)) < TOL
assert abs(hc - brute_force_cky(GRAMMAR, emit, rule, None)) < 1e-11python -m pytest packages/omnibias-struct/tests/test_parse.py -k test_hard_cky_matches_driver_and_bruteforce -qRead the implementation
def brute_force_cky(
grammar: BinaryGrammar, emit: FloatArray, rule: FloatArray, beta: float | None = None
) -> float:
r"""Flat oracle over *enumerated* parse trees: ``max`` (``beta is None``) or ``lse_beta``."""
spec = build_chart(grammar, int(np.asarray(emit).shape[0]))
return brute_force_value(spec.graph, chart_edge_weights(spec, emit, rule), beta)build_chart
omnibias.struct.build_chartSource ↗build_chart(grammar: BinaryGrammar, length: int) -> ChartSpecLift grammar parsing a length-length sentence into a chart Hypergraph.
Items are ordered by span width so tails always precede heads (topological); lexical
axioms carry ("emit", i, A) and binary edges ("rule", r).
Parameters
| Name | Type & default | Contract |
|---|---|---|
grammarpositional-or-keyword | BinaryGrammarRequired | See the operation contract and implementation below. |
lengthpositional-or-keyword | intRequired | See the operation contract and implementation below. |
ChartSpecExplicit validation & failure cases
- When
length < 1, raisesValueError(f'length must be >= 1, got {length}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qRegression example · hard cky matches driver and bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_cky_matches_driver_and_bruteforce(seed: int) -> None:
emit, rule = _scores(seed, 4)
spec = build_chart(GRAMMAR, 4)
w = chart_edge_weights(spec, emit, rule)
hc = hard_cky(GRAMMAR, emit, rule)
assert abs(hc - hard_value(spec.graph, w)) < TOL
assert abs(hc - brute_force_cky(GRAMMAR, emit, rule, None)) < 1e-11python -m pytest packages/omnibias-struct/tests/test_parse.py -k test_hard_cky_matches_driver_and_bruteforce -qRead the implementation
def build_chart(grammar: BinaryGrammar, length: int) -> ChartSpec:
r"""Lift ``grammar`` parsing a length-``length`` sentence into a chart :class:`Hypergraph`.
Items are ordered by span width so tails always precede heads (topological); lexical
axioms carry ``("emit", i, A)`` and binary edges ``("rule", r)``.
"""
if length < 1:
raise ValueError(f"length must be >= 1, got {length}")
r_nt, length_l = grammar.num_nonterminals, length
node_of: dict[tuple[int, int, int], int] = {}
nid = 0
for w in range(1, length_l + 1):
for i in range(0, length_l - w + 1):
j = i + w
for a in range(r_nt):
node_of[(a, i, j)] = nid
nid += 1
edges: list[HyperEdge] = []
specs: list[tuple[str, int, int]] = []
for i in range(length_l):
for a in range(r_nt):
edges.append(HyperEdge(head=node_of[(a, i, i + 1)], tails=()))
specs.append(("emit", i, a))
for w in range(2, length_l + 1):
for i in range(0, length_l - w + 1):
j = i + w
for r, (a, b, c) in enumerate(grammar.rules):
for k in range(i + 1, j):
edges.append(
HyperEdge(head=node_of[(a, i, j)], tails=(node_of[(b, i, k)], node_of[(c, k, j)]))
)
specs.append(("rule", r, 0))
root = node_of[(grammar.start, 0, length_l)]
graph = Hypergraph(num_nodes=nid, edges=tuple(edges), root=root)
return ChartSpec(
graph=graph,
edge_specs=tuple(specs),
length=length_l,
num_nonterminals=r_nt,
num_rules=grammar.num_rules,
node_of=node_of,
root=root,
)count_parse_trees
omnibias.struct.count_parse_treesSource ↗count_parse_trees(grammar: BinaryGrammar, length: int) -> intExact number of parse trees of a length-length sentence -- the N in the gap.
Parameters
| Name | Type & default | Contract |
|---|---|---|
grammarpositional-or-keyword | BinaryGrammarRequired | See the operation contract and implementation below. |
lengthpositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExecuted regression · parse hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_parse_hard_equals_brute_and_count(seed: int) -> None:
assert probe_parse_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_parse_hard_equals_brute_and_count[0]" -qRegression example · derivation count is catalan
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_derivation_count_is_catalan(length: int) -> None:
# S -> S S with a single nonterminal: #trees of length L is the Catalan number C_{L-1}.
grammar = BinaryGrammar(1, ((0, 0, 0),), start=0)
catalan = comb(2 * (length - 1), length - 1) // length
assert count_parse_trees(grammar, length) == catalanpython -m pytest packages/omnibias-struct/tests/test_parse.py -k test_derivation_count_is_catalan -qRead the implementation
def count_parse_trees(grammar: BinaryGrammar, length: int) -> int:
r"""Exact number of parse trees of a length-``length`` sentence -- the ``N`` in the gap."""
return count_derivations(build_chart(grammar, length).graph)hard_cky
omnibias.struct.hard_ckySource ↗hard_cky(grammar: BinaryGrammar, emit: FloatArray, rule: FloatArray) -> floatClassic CKY best-parse score (max-plus), independent of the hypergraph driver.
Parameters
| Name | Type & default | Contract |
|---|---|---|
grammarpositional-or-keyword | BinaryGrammarRequired | See the operation contract and implementation below. |
emitpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
rulepositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
floatExecuted regression · parse hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_parse_hard_equals_brute_and_count(seed: int) -> None:
assert probe_parse_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_parse_hard_equals_brute_and_count[0]" -qRegression example · hard cky matches driver and bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_hard_cky_matches_driver_and_bruteforce(seed: int) -> None:
emit, rule = _scores(seed, 4)
spec = build_chart(GRAMMAR, 4)
w = chart_edge_weights(spec, emit, rule)
hc = hard_cky(GRAMMAR, emit, rule)
assert abs(hc - hard_value(spec.graph, w)) < TOL
assert abs(hc - brute_force_cky(GRAMMAR, emit, rule, None)) < 1e-11python -m pytest packages/omnibias-struct/tests/test_parse.py -k test_hard_cky_matches_driver_and_bruteforce -qRead the implementation
def hard_cky(grammar: BinaryGrammar, emit: FloatArray, rule: FloatArray) -> float:
r"""Classic CKY best-parse score (max-plus), independent of the hypergraph driver."""
e = np.asarray(emit, dtype=float)
r = np.asarray(rule, dtype=float)
length_l, r_nt = e.shape[0], grammar.num_nonterminals
neg = -math.inf
chart = np.full((r_nt, length_l + 1, length_l + 1), neg)
for i in range(length_l):
for a in range(r_nt):
chart[a, i, i + 1] = e[i, a]
for w in range(2, length_l + 1):
for i in range(0, length_l - w + 1):
j = i + w
for ridx, (a, b, c) in enumerate(grammar.rules):
for k in range(i + 1, j):
val = r[ridx] + chart[b, i, k] + chart[c, k, j]
if val > chart[a, i, j]:
chart[a, i, j] = val
return float(chart[grammar.start, 0, length_l])soft_cky
omnibias.struct.soft_ckySource ↗soft_cky(grammar: BinaryGrammar, emit: FloatArray, rule: FloatArray, beta: float) -> floatSoft lse_beta inside partition (numpy oracle for the backend soft_inside).
Parameters
| Name | Type & default | Contract |
|---|---|---|
grammarpositional-or-keyword | BinaryGrammarRequired | See the operation contract and implementation below. |
emitpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
rulepositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatRead the implementation
def soft_cky(grammar: BinaryGrammar, emit: FloatArray, rule: FloatArray, beta: float) -> float:
r"""Soft ``lse_beta`` inside partition (numpy oracle for the backend ``soft_inside``)."""
spec = build_chart(grammar, int(np.asarray(emit).shape[0]))
return soft_value(spec.graph, chart_edge_weights(spec, emit, rule), beta)log_num_paths
omnibias.struct.log_num_pathsSource ↗log_num_paths(problem: ChainTrellis | DAG | CTCLattice, n_steps: int | None=None) -> floatlog of the exact number of complete paths / alignments, via a log-space DP.
Finite for arbitrarily large path counts (never overflows to inf and never
materialises the integer count). Returns -inf for an infeasible problem (no
complete paths -- e.g. a CTCLattice whose n_steps is shorter than its
label sequence). For a CTCLattice the alignment length n_steps (= T)
is required, matching omnibias.struct.count_paths.
Parameters
| Name | Type & default | Contract |
|---|---|---|
problempositional-or-keyword | ChainTrellis | DAG | CTCLatticeRequired | See the operation contract and implementation below. |
n_stepspositional-or-keyword | int | NoneDefault: None | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
n_steps is None, raisesValueError('log_num_paths on a CTCLattice requires n_steps (= T)').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · log num paths infeasible ctc is neg inf
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_log_num_paths_infeasible_ctc_is_neg_inf() -> None:
lattice = CTCLattice(np.array([1, 2, 1]), num_classes=3) # L = 3 labels
assert log_num_paths(lattice, 2) == -math.inf # T = 2 < L: cannot emit every labelpython -m pytest "packages/omnibias-struct/tests/test_core_harden.py::test_log_num_paths_infeasible_ctc_is_neg_inf" -qRegression example · log num paths is overflow free
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_log_num_paths_is_overflow_free() -> None:
# 10 ** 500 paths: exact integer count is a 501-digit bignum; log stays a finite float.
big = ChainTrellis(np.zeros((500, 10)), np.zeros((10, 10)))
log_n = log_num_paths(big)
assert math.isfinite(log_n)
assert abs(log_n - 500 * math.log(10)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_core_harden.py -k test_log_num_paths_is_overflow_free -qRead the implementation
def log_num_paths(problem: ChainTrellis | DAG | CTCLattice, n_steps: int | None = None) -> float:
r"""``log`` of the exact number of complete paths / alignments, via a log-space DP.
Finite for arbitrarily large path counts (never overflows to ``inf`` and never
materialises the integer count). Returns ``-inf`` for an infeasible problem (no
complete paths -- e.g. a :class:`CTCLattice` whose ``n_steps`` is shorter than its
label sequence). For a :class:`CTCLattice` the alignment length ``n_steps`` (``= T``)
is required, matching :func:`omnibias.struct.count_paths`.
"""
if isinstance(problem, ChainTrellis):
return problem.n_steps * math.log(problem.n_states)
if isinstance(problem, DAG):
succ: dict[int, list[int]] = {}
for u, v in problem.edges:
succ.setdefault(u, []).append(v)
log_counts = [-math.inf] * problem.num_nodes
log_counts[problem.sink] = 0.0
for node in range(problem.num_nodes - 1, -1, -1):
if node == problem.sink:
continue
log_counts[node] = _logaddexp([log_counts[v] for v in succ.get(node, [])])
return log_counts[problem.source]
if n_steps is None:
raise ValueError("log_num_paths on a CTCLattice requires n_steps (= T)")
m = 2 * problem.n_labels + 1
if n_steps < problem.n_labels: # too short to emit every label -> infeasible
return -math.inf
log_counts = [-math.inf] * m
log_counts[0] = 0.0
if m > 1:
log_counts[1] = 0.0
for _ in range(1, n_steps):
nxt = [-math.inf] * m
for s in range(m):
nxt[s] = _logaddexp([log_counts[p] for p in problem.incoming(s)])
log_counts = nxt
ends = [log_counts[m - 1]] + ([log_counts[m - 2]] if m >= 2 else [])
return _logaddexp(ends)AcyclicMDP
omnibias.struct.AcyclicMDPSource ↗class AcyclicMDPDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
A deterministic acyclic MDP: actions[i] = (state, next_state) with state < next.
Action i earns reward rewards[i] (supplied separately, so it can be a learnable
backend tensor). A state with no outgoing action is terminal; trajectories run from
start to any terminal.
Parameters
| Name | Type & default | Contract |
|---|---|---|
num_statesdataclass field | intRequired | See the operation contract and implementation below. |
actionsdataclass field | tuple[tuple[int, int], ...]Required | See the operation contract and implementation below. |
startdataclass field | intDefault: 0 | See the operation contract and implementation below. |
Executed regression · soft value iteration parity
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_value_iteration_parity() -> None:
mdp = _diamond_mdp()
rng = np.random.default_rng(1)
rewards = rng.standard_normal(len(mdp.actions))
for beta in (1.0, 8.0):
v_t = float(tplan.soft_value_iteration(torch.tensor(rewards), mdp, beta))
v_j = float(jplan.soft_value_iteration(jnp.asarray(rewards), mdp, beta))
assert abs(v_t - v_j) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_value_iteration_parity" -qFields & methods
num_statesfield
num_states: intDeclared int field on AcyclicMDP. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗actionsfield
actions: tuple[tuple[int, int], ...]Declared tuple[tuple[int, int], ...] field on AcyclicMDP. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
self.num_states < 1, raisesValueError(f'num_states must be >= 1, got {self.num_states}'). - When
not 0 <= u < self.num_states or not 0 <= v < self.num_states, raisesValueError(f'action {idx} ({u}->{v}) out of range'). - When
u >= v, raisesValueError(f'action {idx} ({u}->{v}) violates topological order (u < v)').
Executed regression · soft value iteration parity
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_value_iteration_parity() -> None:
mdp = _diamond_mdp()
rng = np.random.default_rng(1)
rewards = rng.standard_normal(len(mdp.actions))
for beta in (1.0, 8.0):
v_t = float(tplan.soft_value_iteration(torch.tensor(rewards), mdp, beta))
v_j = float(jplan.soft_value_iteration(jnp.asarray(rewards), mdp, beta))
assert abs(v_t - v_j) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_value_iteration_parity" -qMethod implementation
def __post_init__(self) -> None:
if self.num_states < 1:
raise ValueError(f"num_states must be >= 1, got {self.num_states}")
by_state: dict[int, list[int]] = {}
for idx, (u, v) in enumerate(self.actions):
if not 0 <= u < self.num_states or not 0 <= v < self.num_states:
raise ValueError(f"action {idx} ({u}->{v}) out of range")
if u >= v:
raise ValueError(f"action {idx} ({u}->{v}) violates topological order (u < v)")
by_state.setdefault(u, []).append(idx)
object.__setattr__(self, "_by_state", by_state)actions_ofmethod
actions_of(self, state: int) -> list[int]Action ids available in state (empty iff terminal).
Parameters
| Name | Type & default | Contract |
|---|---|---|
statepositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: list[int]
Executed regression · soft value iteration parity
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_value_iteration_parity() -> None:
mdp = _diamond_mdp()
rng = np.random.default_rng(1)
rewards = rng.standard_normal(len(mdp.actions))
for beta in (1.0, 8.0):
v_t = float(tplan.soft_value_iteration(torch.tensor(rewards), mdp, beta))
v_j = float(jplan.soft_value_iteration(jnp.asarray(rewards), mdp, beta))
assert abs(v_t - v_j) < 1e-9python -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_value_iteration_parity" -qMethod implementation
def actions_of(self, state: int) -> list[int]:
"""Action ids available in ``state`` (empty iff terminal)."""
return self._by_state.get(state, [])is_terminalmethod
is_terminal(self, state: int) -> boolWhether state has no outgoing action.
Parameters
| Name | Type & default | Contract |
|---|---|---|
statepositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: bool
Method implementation
def is_terminal(self, state: int) -> bool:
"""Whether ``state`` has no outgoing action."""
return not self._by_state.get(state)enumerate_trajectoriesmethod
enumerate_trajectories(self) -> Iterator[tuple[int, ...]]Yield every start -> terminal trajectory as a tuple of action ids.
Returns: Iterator[tuple[int, ...]]
Executed regression · soft value iteration anneals to hard with certified gap
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_value_iteration_anneals_to_hard_with_certified_gap() -> None:
mdp = _diamond_mdp()
rng = np.random.default_rng(0)
rewards = rng.standard_normal(len(mdp.actions))
rt = torch.tensor(rewards)
hard = hard_value_iteration(mdp, rewards)
assert abs(hard - brute_force_optimal_return(mdp, rewards)) < 1e-9
num_traj = mdp.count_trajectories()
prev = np.inf
for beta in (1.0, 2.0, 4.0, 8.0, 16.0):
soft = float(tplan.soft_value_iteration(rt, mdp, beta))
cert = certify_soft_dp(hard, soft, num_traj, beta, brute_force_value=brute_force_optimal_return(mdp, rewards))
assert cert.is_sound and cert.agrees_with_bruteforce # V* <= V_beta <= V* + log(N)/beta
assert cert.absolute_gap <= prev + 1e-12
prev = cert.absolute_gappython -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_value_iteration_anneals_to_hard_with_certified_gap" -qMethod implementation
def enumerate_trajectories(self) -> Iterator[tuple[int, ...]]:
"""Yield every ``start -> terminal`` trajectory as a tuple of action ids."""
def dfs(state: int, acc: tuple[int, ...]) -> Iterator[tuple[int, ...]]:
acts = self.actions_of(state)
if not acts:
yield acc
return
for i in acts:
yield from dfs(self.actions[i][1], (*acc, i))
yield from dfs(self.start, ())trajectory_returnmethod
trajectory_return(self, action_ids: object, rewards: FloatArray) -> floatTotal reward of a trajectory (sequence of action ids).
Parameters
| Name | Type & default | Contract |
|---|---|---|
action_idspositional-or-keyword | objectRequired | See the operation contract and implementation below. |
rewardspositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
Returns: float
Executed regression · soft value iteration anneals to hard with certified gap
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_value_iteration_anneals_to_hard_with_certified_gap() -> None:
mdp = _diamond_mdp()
rng = np.random.default_rng(0)
rewards = rng.standard_normal(len(mdp.actions))
rt = torch.tensor(rewards)
hard = hard_value_iteration(mdp, rewards)
assert abs(hard - brute_force_optimal_return(mdp, rewards)) < 1e-9
num_traj = mdp.count_trajectories()
prev = np.inf
for beta in (1.0, 2.0, 4.0, 8.0, 16.0):
soft = float(tplan.soft_value_iteration(rt, mdp, beta))
cert = certify_soft_dp(hard, soft, num_traj, beta, brute_force_value=brute_force_optimal_return(mdp, rewards))
assert cert.is_sound and cert.agrees_with_bruteforce # V* <= V_beta <= V* + log(N)/beta
assert cert.absolute_gap <= prev + 1e-12
prev = cert.absolute_gappython -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_value_iteration_anneals_to_hard_with_certified_gap" -qMethod implementation
def trajectory_return(self, action_ids: object, rewards: FloatArray) -> float:
"""Total reward of a trajectory (sequence of action ids)."""
r = np.asarray(rewards, dtype=float)
return float(sum(float(r[int(i)]) for i in np.asarray(action_ids, dtype=int).reshape(-1)))count_trajectoriesmethod
count_trajectories(self) -> intNumber of start -> terminal trajectories (topological-order DP).
Returns: int
Executed regression · soft value iteration anneals to hard with certified gap
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_value_iteration_anneals_to_hard_with_certified_gap() -> None:
mdp = _diamond_mdp()
rng = np.random.default_rng(0)
rewards = rng.standard_normal(len(mdp.actions))
rt = torch.tensor(rewards)
hard = hard_value_iteration(mdp, rewards)
assert abs(hard - brute_force_optimal_return(mdp, rewards)) < 1e-9
num_traj = mdp.count_trajectories()
prev = np.inf
for beta in (1.0, 2.0, 4.0, 8.0, 16.0):
soft = float(tplan.soft_value_iteration(rt, mdp, beta))
cert = certify_soft_dp(hard, soft, num_traj, beta, brute_force_value=brute_force_optimal_return(mdp, rewards))
assert cert.is_sound and cert.agrees_with_bruteforce # V* <= V_beta <= V* + log(N)/beta
assert cert.absolute_gap <= prev + 1e-12
prev = cert.absolute_gappython -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_value_iteration_anneals_to_hard_with_certified_gap" -qMethod implementation
def count_trajectories(self) -> int:
"""Number of ``start -> terminal`` trajectories (topological-order DP)."""
cnt = [0] * self.num_states
for s in range(self.num_states - 1, -1, -1):
acts = self.actions_of(s)
cnt[s] = 1 if not acts else sum(cnt[self.actions[i][1]] for i in acts)
return int(cnt[self.start])Read the implementation
class AcyclicMDP:
r"""A deterministic acyclic MDP: ``actions[i] = (state, next_state)`` with ``state < next``.
Action ``i`` earns reward ``rewards[i]`` (supplied separately, so it can be a learnable
backend tensor). A state with no outgoing action is terminal; trajectories run from
:attr:`start` to any terminal.
"""
num_states: int
actions: tuple[tuple[int, int], ...]
start: int = 0
_by_state: dict[int, list[int]] = field(default_factory=dict, compare=False, repr=False)
def __post_init__(self) -> None:
if self.num_states < 1:
raise ValueError(f"num_states must be >= 1, got {self.num_states}")
by_state: dict[int, list[int]] = {}
for idx, (u, v) in enumerate(self.actions):
if not 0 <= u < self.num_states or not 0 <= v < self.num_states:
raise ValueError(f"action {idx} ({u}->{v}) out of range")
if u >= v:
raise ValueError(f"action {idx} ({u}->{v}) violates topological order (u < v)")
by_state.setdefault(u, []).append(idx)
object.__setattr__(self, "_by_state", by_state)
def actions_of(self, state: int) -> list[int]:
"""Action ids available in ``state`` (empty iff terminal)."""
return self._by_state.get(state, [])
def is_terminal(self, state: int) -> bool:
"""Whether ``state`` has no outgoing action."""
return not self._by_state.get(state)
def enumerate_trajectories(self) -> Iterator[tuple[int, ...]]:
"""Yield every ``start -> terminal`` trajectory as a tuple of action ids."""
def dfs(state: int, acc: tuple[int, ...]) -> Iterator[tuple[int, ...]]:
acts = self.actions_of(state)
if not acts:
yield acc
return
for i in acts:
yield from dfs(self.actions[i][1], (*acc, i))
yield from dfs(self.start, ())
def trajectory_return(self, action_ids: object, rewards: FloatArray) -> float:
"""Total reward of a trajectory (sequence of action ids)."""
r = np.asarray(rewards, dtype=float)
return float(sum(float(r[int(i)]) for i in np.asarray(action_ids, dtype=int).reshape(-1)))
def count_trajectories(self) -> int:
"""Number of ``start -> terminal`` trajectories (topological-order DP)."""
cnt = [0] * self.num_states
for s in range(self.num_states - 1, -1, -1):
acts = self.actions_of(s)
cnt[s] = 1 if not acts else sum(cnt[self.actions[i][1]] for i in acts)
return int(cnt[self.start])brute_force_optimal_return
omnibias.struct.brute_force_optimal_returnSource ↗brute_force_optimal_return(mdp: AcyclicMDP, rewards: FloatArray) -> floatOptimal return by enumerating every trajectory (oracle for tiny MDPs).
Parameters
| Name | Type & default | Contract |
|---|---|---|
mdppositional-or-keyword | AcyclicMDPRequired | See the operation contract and implementation below. |
rewardspositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
floatExecuted regression · soft value iteration anneals to hard with certified gap
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_value_iteration_anneals_to_hard_with_certified_gap() -> None:
mdp = _diamond_mdp()
rng = np.random.default_rng(0)
rewards = rng.standard_normal(len(mdp.actions))
rt = torch.tensor(rewards)
hard = hard_value_iteration(mdp, rewards)
assert abs(hard - brute_force_optimal_return(mdp, rewards)) < 1e-9
num_traj = mdp.count_trajectories()
prev = np.inf
for beta in (1.0, 2.0, 4.0, 8.0, 16.0):
soft = float(tplan.soft_value_iteration(rt, mdp, beta))
cert = certify_soft_dp(hard, soft, num_traj, beta, brute_force_value=brute_force_optimal_return(mdp, rewards))
assert cert.is_sound and cert.agrees_with_bruteforce # V* <= V_beta <= V* + log(N)/beta
assert cert.absolute_gap <= prev + 1e-12
prev = cert.absolute_gappython -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_value_iteration_anneals_to_hard_with_certified_gap" -qRead the implementation
def brute_force_optimal_return(mdp: AcyclicMDP, rewards: FloatArray) -> float:
r"""Optimal return by enumerating every trajectory (oracle for tiny MDPs)."""
return max(mdp.trajectory_return(t, rewards) for t in mdp.enumerate_trajectories())hard_value_iteration
omnibias.struct.hard_value_iterationSource ↗hard_value_iteration(mdp: AcyclicMDP, rewards: FloatArray) -> floatOptimal expected return from mdp.start (deterministic hard value iteration).
Parameters
| Name | Type & default | Contract |
|---|---|---|
mdppositional-or-keyword | AcyclicMDPRequired | See the operation contract and implementation below. |
rewardspositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
floatExecuted regression · soft value iteration anneals to hard with certified gap
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_soft_value_iteration_anneals_to_hard_with_certified_gap() -> None:
mdp = _diamond_mdp()
rng = np.random.default_rng(0)
rewards = rng.standard_normal(len(mdp.actions))
rt = torch.tensor(rewards)
hard = hard_value_iteration(mdp, rewards)
assert abs(hard - brute_force_optimal_return(mdp, rewards)) < 1e-9
num_traj = mdp.count_trajectories()
prev = np.inf
for beta in (1.0, 2.0, 4.0, 8.0, 16.0):
soft = float(tplan.soft_value_iteration(rt, mdp, beta))
cert = certify_soft_dp(hard, soft, num_traj, beta, brute_force_value=brute_force_optimal_return(mdp, rewards))
assert cert.is_sound and cert.agrees_with_bruteforce # V* <= V_beta <= V* + log(N)/beta
assert cert.absolute_gap <= prev + 1e-12
prev = cert.absolute_gappython -m pytest "packages/omnibias-struct/tests/test_plan_attn.py::test_soft_value_iteration_anneals_to_hard_with_certified_gap" -qRead the implementation
def hard_value_iteration(mdp: AcyclicMDP, rewards: FloatArray) -> float:
r"""Optimal expected return from ``mdp.start`` (deterministic hard value iteration)."""
r = np.asarray(rewards, dtype=float)
value = np.zeros(mdp.num_states)
for s in range(mdp.num_states - 1, -1, -1):
acts = mdp.actions_of(s)
if acts:
value[s] = max(r[i] + value[mdp.actions[i][1]] for i in acts)
return float(value[mdp.start])SelectionCertificate
omnibias.struct.SelectionCertificateSource ↗class SelectionCertificateDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
A closed-form certificate of the beta -> inf Gibbs-to-Dirac (mode) collapse.
Composes the value-gap sandwich (DPGapCertificate, num_paths = N) with the
mass-concentration lower bound and an optional L^inf argmax-stability radius. Honest by
construction: it states only bounds that hold, never lse_beta == max or p_max == 1.
Attributes
value_gap: The max(s) <= lse_beta(s) <= max(s) + log(N)/beta sandwich (sense == "max").
argmax: The decoded mode index argmax(s).
margin: The top-two logit margin m = s_(1) - s_(2) (+inf for N == 1).
p_max: The exact Gibbs mass at the mode, softmax(beta s)_argmax.
p_max_lower: The closed-form lower bound 1 / (1 + (N-1) e^{-beta m}) on p_max.
eps: The queried L^inf perturbation radius (None if stability was not queried).
tol: Numerical tolerance for the soundness self-checks.
Parameters
| Name | Type & default | Contract |
|---|---|---|
value_gapdataclass field | DPGapCertificateRequired | The max(s) <= lse_beta(s) <= max(s) + log(N)/beta sandwich (sense == "max"). |
argmaxdataclass field | intRequired | The decoded mode index argmax(s). |
margindataclass field | floatRequired | The top-two logit margin m = s_(1) - s_(2) (+inf for N == 1). |
p_maxdataclass field | floatRequired | The exact Gibbs mass at the mode, softmax(beta s)_argmax. |
p_max_lowerdataclass field | floatRequired | The closed-form lower bound 1 / (1 + (N-1) e^{-beta m}) on p_max. |
epsdataclass field | float | NoneDefault: None | The queried L^inf perturbation radius (None if stability was not queried). |
toldataclass field | floatDefault: 1e-09 | Numerical tolerance for the soundness self-checks. |
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qFields & methods
value_gapfield
value_gap: DPGapCertificateThe max(s) <= lse_beta(s) <= max(s) + log(N)/beta sandwich (sense == "max").
p_max_lowerfield
p_max_lower: floatThe closed-form lower bound 1 / (1 + (N-1) e^{-beta m}) on p_max.
epsfield
eps: float | None = NoneThe queried L^inf perturbation radius (None if stability was not queried).
betaproperty
beta(self) -> floatThe inverse temperature beta of the relaxation.
Returns: float
Executed regression · seal verify roundtrip and tamper
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_seal_verify_roundtrip_and_tamper() -> None:
cert = certify_argmax([3.0, 1.0, 0.5], beta=6.0, eps=0.2)
sealed = seal_selection_certificate(cert, meta={"note": "unit-test"})
# Import here: seal() warms omnibias.core.verified, breaking the core proof/verified cycle.
from omnibias.core.proof.certificate import verify_certificate_digest
assert verify_certificate_digest(sealed)
assert sealed["claim"].startswith("softmax(")
assert sealed["payload"]["type"] == "certified_argmax"
assert sealed["payload"]["argmax"] == cert.argmax
assert sealed["payload"]["argmax_stable"] is True
assert sealed["honesty"]["unproven_claim"] is False
assert sealed["meta"]["note"] == "unit-test"
# Tampering with any bound invalidates the digest.
tampered = {**sealed, "payload": {**sealed["payload"], "p_max_lower": 0.0}}
assert not verify_certificate_digest(tampered)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_seal_verify_roundtrip_and_tamper" -qMethod implementation
def beta(self) -> float:
"""The inverse temperature ``beta`` of the relaxation."""
return self.value_gap.betanum_choicesproperty
num_choices(self) -> intThe number N of choices (logits).
Returns: int
Executed regression · singleton is trivially certified
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_singleton_is_trivially_certified() -> None:
cert = certify_argmax([2.0], beta=3.0)
assert cert.num_choices == 1
assert cert.gap_bound == 0.0
assert cert.p_max == 1.0
assert cert.p_max_lower == 1.0
assert math.isinf(cert.margin)
assert cert.is_sound and cert.certifiedpython -m pytest "packages/omnibias-struct/tests/test_select.py::test_singleton_is_trivially_certified" -qMethod implementation
def num_choices(self) -> int:
"""The number ``N`` of choices (logits)."""
return self.value_gap.num_pathsgap_boundproperty
gap_bound(self) -> floatThe closed-form value gap log(N)/beta.
Returns: float
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qMethod implementation
def gap_bound(self) -> float:
"""The closed-form value gap ``log(N)/beta``."""
return self.value_gap.gap_boundhard_valueproperty
hard_value(self) -> floatThe hard optimum max(s).
Returns: float
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qMethod implementation
def hard_value(self) -> float:
"""The hard optimum ``max(s)``."""
return self.value_gap.hard_valuesoft_valueproperty
soft_value(self) -> floatThe soft value lse_beta(s).
Returns: float
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qMethod implementation
def soft_value(self) -> float:
"""The soft value ``lse_beta(s)``."""
return self.value_gap.soft_valuemass_concentration_holdsproperty
mass_concentration_holds(self) -> boolWhether the measured p_max respects its closed-form lower bound.
Returns: bool
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qMethod implementation
def mass_concentration_holds(self) -> bool:
"""Whether the measured ``p_max`` respects its closed-form lower bound."""
return self.p_max >= self.p_max_lower - self.tolargmax_stableproperty
argmax_stable(self) -> bool | NoneWhether the decode is the unique argmax over the eps-ball (None if no eps).
Returns: bool | None
Executed regression · argmax stability threshold
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_argmax_stability_threshold() -> None:
logits = np.array([2.0, 1.0, 0.5, 0.0]) # margin = 1.0
m = argmax_stability_margin(logits)
assert m == pytest.approx(1.0)
stable = certify_argmax(logits, 5.0, eps=0.4 * m) # 2*eps = 0.8 m < m -> stable
unstable = certify_argmax(logits, 5.0, eps=0.6 * m) # 2*eps = 1.2 m > m -> not stable
assert stable.argmax_stable is True
assert stable.robust_radius == pytest.approx(0.5) # m / 2
assert unstable.argmax_stable is False
# eps not queried -> None (no claim made), still sound.
assert certify_argmax(logits, 5.0).argmax_stable is Nonepython -m pytest "packages/omnibias-struct/tests/test_select.py::test_argmax_stability_threshold" -qMethod implementation
def argmax_stable(self) -> bool | None:
"""Whether the decode is the unique argmax over the ``eps``-ball (``None`` if no ``eps``)."""
if self.eps is None:
return None
return self.margin > 2.0 * self.eps + self.tolrobust_radiusproperty
robust_radius(self) -> floatThe certified L^inf radius m / 2 within which the argmax is unique.
Returns: float
Executed regression · argmax stability threshold
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_argmax_stability_threshold() -> None:
logits = np.array([2.0, 1.0, 0.5, 0.0]) # margin = 1.0
m = argmax_stability_margin(logits)
assert m == pytest.approx(1.0)
stable = certify_argmax(logits, 5.0, eps=0.4 * m) # 2*eps = 0.8 m < m -> stable
unstable = certify_argmax(logits, 5.0, eps=0.6 * m) # 2*eps = 1.2 m > m -> not stable
assert stable.argmax_stable is True
assert stable.robust_radius == pytest.approx(0.5) # m / 2
assert unstable.argmax_stable is False
# eps not queried -> None (no claim made), still sound.
assert certify_argmax(logits, 5.0).argmax_stable is Nonepython -m pytest "packages/omnibias-struct/tests/test_select.py::test_argmax_stability_threshold" -qMethod implementation
def robust_radius(self) -> float:
"""The certified ``L^inf`` radius ``m / 2`` within which the argmax is unique."""
return self.margin / 2.0is_soundproperty
is_sound(self) -> boolWhether every asserted bound holds for the measured values (the soundness check).
Returns: bool
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qMethod implementation
def is_sound(self) -> bool:
"""Whether every asserted bound holds for the measured values (the soundness check)."""
return self.value_gap.is_sound and self.mass_concentration_holdscertifiedproperty
certified(self) -> boolWhether a rigorous closed-form collapse certificate was produced *and* is sound.
Returns: bool
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qMethod implementation
def certified(self) -> bool:
"""Whether a rigorous closed-form collapse certificate was produced *and* is sound."""
return self.value_gap.certified and self.mass_concentration_holdsRead the implementation
class SelectionCertificate:
r"""A closed-form certificate of the ``beta -> inf`` Gibbs-to-Dirac (mode) collapse.
Composes the value-gap sandwich (:class:`DPGapCertificate`, ``num_paths = N``) with the
mass-concentration lower bound and an optional ``L^inf`` argmax-stability radius. Honest by
construction: it states only bounds that hold, never ``lse_beta == max`` or ``p_max == 1``.
Attributes
----------
value_gap:
The ``max(s) <= lse_beta(s) <= max(s) + log(N)/beta`` sandwich (``sense == "max"``).
argmax:
The decoded mode index ``argmax(s)``.
margin:
The top-two logit margin ``m = s_(1) - s_(2)`` (``+inf`` for ``N == 1``).
p_max:
The exact Gibbs mass at the mode, ``softmax(beta s)_argmax``.
p_max_lower:
The closed-form lower bound ``1 / (1 + (N-1) e^{-beta m})`` on ``p_max``.
eps:
The queried ``L^inf`` perturbation radius (``None`` if stability was not queried).
tol:
Numerical tolerance for the soundness self-checks.
"""
value_gap: DPGapCertificate
argmax: int
margin: float
p_max: float
p_max_lower: float
eps: float | None = None
tol: float = 1e-9
@property
def beta(self) -> float:
"""The inverse temperature ``beta`` of the relaxation."""
return self.value_gap.beta
@property
def num_choices(self) -> int:
"""The number ``N`` of choices (logits)."""
return self.value_gap.num_paths
@property
def gap_bound(self) -> float:
"""The closed-form value gap ``log(N)/beta``."""
return self.value_gap.gap_bound
@property
def hard_value(self) -> float:
"""The hard optimum ``max(s)``."""
return self.value_gap.hard_value
@property
def soft_value(self) -> float:
"""The soft value ``lse_beta(s)``."""
return self.value_gap.soft_value
@property
def mass_concentration_holds(self) -> bool:
"""Whether the measured ``p_max`` respects its closed-form lower bound."""
return self.p_max >= self.p_max_lower - self.tol
@property
def argmax_stable(self) -> bool | None:
"""Whether the decode is the unique argmax over the ``eps``-ball (``None`` if no ``eps``)."""
if self.eps is None:
return None
return self.margin > 2.0 * self.eps + self.tol
@property
def robust_radius(self) -> float:
"""The certified ``L^inf`` radius ``m / 2`` within which the argmax is unique."""
return self.margin / 2.0
@property
def is_sound(self) -> bool:
"""Whether every asserted bound holds for the measured values (the soundness check)."""
return self.value_gap.is_sound and self.mass_concentration_holds
@property
def certified(self) -> bool:
"""Whether a rigorous closed-form collapse certificate was produced *and* is sound."""
return self.value_gap.certified and self.mass_concentration_holdsOther public import paths
omnibias.struct.SelectionCertificateomnibias.struct.decision.SelectionCertificateomnibias.struct.select.SelectionCertificate
argmax_stability_margin
omnibias.struct.argmax_stability_marginSource ↗argmax_stability_margin(logits: NDArray[Any] | list[float]) -> floatThe top-two logit margin m = s_(1) - s_(2) (+inf for a single choice).
The decoded argmax is the unique maximiser over every input perturbation
||delta||_inf <= eps exactly when m > 2 eps; equivalently the certified robustness
radius of the decode is m / 2.
Parameters
| Name | Type & default | Contract |
|---|---|---|
logitspositional-or-keyword | NDArray[Any] | list[float]Required | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
s.size == 0, raisesValueError('logits must be non-empty').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qRegression example · beta for confidence roundtrip
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_beta_for_confidence_roundtrip() -> None:
for n, m, target in [(3, 2.0, 0.99), (10, 0.5, 0.9), (2, 1.0, 0.999)]:
b = beta_for_confidence(m, n, target)
assert mass_concentration_bound(m, n, b) == pytest.approx(target, rel=1e-9, abs=1e-12)
# A hair below the required beta undershoots the target.
assert mass_concentration_bound(m, n, 0.99 * b) < targetpython -m pytest packages/omnibias-struct/tests/test_select.py -k test_beta_for_confidence_roundtrip -qRead the implementation
def argmax_stability_margin(logits: NDArray[Any] | list[float]) -> float:
r"""The top-two logit margin ``m = s_(1) - s_(2)`` (``+inf`` for a single choice).
The decoded ``argmax`` is the unique maximiser over every input perturbation
``||delta||_inf <= eps`` exactly when ``m > 2 eps``; equivalently the certified robustness
radius of the decode is ``m / 2``.
"""
s = np.asarray(logits, dtype=float).reshape(-1)
if s.size == 0:
raise ValueError("logits must be non-empty")
if s.size == 1:
return math.inf
top2 = np.partition(s, -2)[-2:]
return float(top2[1] - top2[0])Other public import paths
omnibias.struct.argmax_stability_marginomnibias.struct.select.argmax_stability_margin
beta_for_confidence
omnibias.struct.beta_for_confidenceSource ↗beta_for_confidence(margin: float, num_choices: int, target_mass: float) -> floatSmallest beta for which mass_concentration_bound certifies p_max >= target.
Inverting the bound: 1/(1+(N-1)e^{-beta m}) >= t iff
beta >= log((N-1) t / (1 - t)) / m. Requires 0 < target_mass < 1 and margin > 0
(with a unique mode, any confidence < 1 is reachable at finite beta).
Parameters
| Name | Type & default | Contract |
|---|---|---|
marginpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
num_choicespositional-or-keyword | intRequired | See the operation contract and implementation below. |
target_masspositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
not 0.0 < target_mass < 1.0, raisesValueError(f'target_mass must be in (0, 1), got {target_mass}'). - When
margin <= 0.0, raisesValueError(f'margin must be > 0 to reach a target confidence, got {margin}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · beta for confidence roundtrip
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_beta_for_confidence_roundtrip() -> None:
for n, m, target in [(3, 2.0, 0.99), (10, 0.5, 0.9), (2, 1.0, 0.999)]:
b = beta_for_confidence(m, n, target)
assert mass_concentration_bound(m, n, b) == pytest.approx(target, rel=1e-9, abs=1e-12)
# A hair below the required beta undershoots the target.
assert mass_concentration_bound(m, n, 0.99 * b) < targetpython -m pytest "packages/omnibias-struct/tests/test_select.py::test_beta_for_confidence_roundtrip" -qRegression example · select torch jax parity
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_select_torch_jax_parity() -> None:
torch = pytest.importorskip("torch")
jax = pytest.importorskip("jax")
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
from omnibias.struct.jax import select as js
from omnibias.struct.torch import select as ts
for seed in range(6):
rng = np.random.default_rng(500 + seed)
# Well-determined instance: a clear margin so the parity tol is not masking a tie.
s = np.sort(rng.standard_normal(7))[::-1] + np.linspace(0.0, 0.3, 7)[::-1]
v = rng.standard_normal(7)
beta = float(rng.uniform(1.0, 12.0))
st, vt = torch.tensor(s, dtype=torch.float64), torch.tensor(v, dtype=torch.float64)
sj, vj = jnp.asarray(s), jnp.asarray(v)
def close(a, b) -> bool: # noqa: ANN001
return bool(np.max(np.abs(np.asarray(a) - np.asarray(b))) < PARITY_TOL)
assert close(ts.soft_max_value(st, beta).numpy(), js.soft_max_value(sj, beta))
assert close(ts.soft_argmax(st, beta).numpy(), js.soft_argmax(sj, beta))
assert close(ts.gibbs_mean(st, beta).numpy(), js.gibbs_mean(sj, beta))
assert close(ts.gibbs_covariance(st, beta).numpy(), js.gibbs_covariance(sj, beta))
kt = ts.gibbs_cumulants_directional(st, vt, beta, order=4).numpy()
kj = np.asarray(js.gibbs_cumulants_directional(sj, vj, beta, order=4))
assert close(kt, kj)
soft_t, cert_t = ts.certified_argmax(st, beta, eps=0.05)
soft_j, cert_j = js.certified_argmax(sj, beta, eps=0.05)
assert close(soft_t.numpy(), soft_j)
assert cert_t.argmax == cert_j.argmax
assert cert_t.p_max_lower == pytest.approx(cert_j.p_max_lower, rel=RTOL, abs=ATOL)python -m pytest packages/omnibias-struct/tests/test_select.py -k test_select_torch_jax_parity -qRead the implementation
def beta_for_confidence(margin: float, num_choices: int, target_mass: float) -> float:
r"""Smallest ``beta`` for which :func:`mass_concentration_bound` certifies ``p_max >= target``.
Inverting the bound: ``1/(1+(N-1)e^{-beta m}) >= t`` iff
``beta >= log((N-1) t / (1 - t)) / m``. Requires ``0 < target_mass < 1`` and ``margin > 0``
(with a unique mode, any confidence ``< 1`` is reachable at finite ``beta``).
"""
if not 0.0 < target_mass < 1.0:
raise ValueError(f"target_mass must be in (0, 1), got {target_mass}")
if margin <= 0.0:
raise ValueError(f"margin must be > 0 to reach a target confidence, got {margin}")
if num_choices <= 1:
return 0.0
ratio = (num_choices - 1) * target_mass / (1.0 - target_mass)
return max(math.log(ratio) / margin, 0.0)Other public import paths
omnibias.struct.beta_for_confidenceomnibias.struct.select.beta_for_confidence
certify_argmax
omnibias.struct.certify_argmaxSource ↗certify_argmax(logits: NDArray[Any] | list[float], beta: float, *, eps: float | None=None, tol: float=1e-09) -> SelectionCertificateCertify the beta -> inf Gibbs-to-Dirac collapse of softmax(beta * logits).
Computes, in closed form (no optimization): the value-gap sandwich via
certify_soft_dp (num_paths = len(logits)), the exact mode mass p_max and its
lower bound mass_concentration_bound, and -- when eps is given -- the
L^inf argmax-stability verdict m > 2 eps. Returns a SelectionCertificate.
Parameters
logits: A 1-D array of N >= 1 real scores s.
beta: The inverse temperature beta > 0.
eps: Optional L^inf perturbation radius for the decode-stability sub-claim.
tol: Numerical tolerance for the soundness self-checks.
Parameters
| Name | Type & default | Contract |
|---|---|---|
logitspositional-or-keyword | NDArray[Any] | list[float]Required | A 1-D array of N >= 1 real scores s. |
betapositional-or-keyword | floatRequired | The inverse temperature beta > 0. |
epskeyword-only | float | NoneDefault: None | Optional L^inf perturbation radius for the decode-stability sub-claim. |
tolkeyword-only | floatDefault: 1e-09 | Numerical tolerance for the soundness self-checks. |
SelectionCertificateExplicit validation & failure cases
- When
n < 1, raisesValueError('logits must be non-empty'). - When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}'). - When
eps is not None and eps < 0.0, raisesValueError(f'eps must be non-negative, got {eps}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qRegression example · certify argmax input validation
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certify_argmax_input_validation() -> None:
with pytest.raises(ValueError):
certify_argmax([], beta=1.0)
with pytest.raises(ValueError):
certify_argmax([1.0, 2.0], beta=0.0)
with pytest.raises(ValueError):
certify_argmax([1.0, 2.0], beta=1.0, eps=-0.1)python -m pytest packages/omnibias-struct/tests/test_select.py -k test_certify_argmax_input_validation -qRead the implementation
def certify_argmax(
logits: NDArray[Any] | list[float],
beta: float,
*,
eps: float | None = None,
tol: float = 1e-9,
) -> SelectionCertificate:
r"""Certify the ``beta -> inf`` Gibbs-to-Dirac collapse of ``softmax(beta * logits)``.
Computes, in closed form (no optimization): the value-gap sandwich via
:func:`certify_soft_dp` (``num_paths = len(logits)``), the exact mode mass ``p_max`` and its
lower bound :func:`mass_concentration_bound`, and -- when ``eps`` is given -- the
``L^inf`` argmax-stability verdict ``m > 2 eps``. Returns a :class:`SelectionCertificate`.
Parameters
----------
logits:
A 1-D array of ``N >= 1`` real scores ``s``.
beta:
The inverse temperature ``beta > 0``.
eps:
Optional ``L^inf`` perturbation radius for the decode-stability sub-claim.
tol:
Numerical tolerance for the soundness self-checks.
"""
s = np.asarray(logits, dtype=float).reshape(-1)
n = int(s.size)
if n < 1:
raise ValueError("logits must be non-empty")
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
if eps is not None and eps < 0.0:
raise ValueError(f"eps must be non-negative, got {eps}")
scaled = beta * s
shift = float(np.max(scaled))
exp_shifted = np.exp(scaled - shift)
soft_value = float(shift + np.log(np.sum(exp_shifted))) / beta
hard_value = float(np.max(s))
p_max = float(np.max(exp_shifted) / np.sum(exp_shifted))
argmax = int(np.argmax(s))
margin = argmax_stability_margin(s)
p_max_lower = mass_concentration_bound(margin, n, beta)
value_gap = certify_soft_dp(
hard_value=hard_value,
soft_value=soft_value,
num_paths=n,
beta=beta,
sense="max",
tol=tol,
)
return SelectionCertificate(
value_gap=value_gap,
argmax=argmax,
margin=margin,
p_max=p_max,
p_max_lower=p_max_lower,
eps=None if eps is None else float(eps),
tol=float(tol),
)Other public import paths
omnibias.struct.certify_argmaxomnibias.struct.select.certify_argmax
mass_concentration_bound
omnibias.struct.mass_concentration_boundSource ↗mass_concentration_bound(margin: float, num_choices: int, beta: float) -> floatClosed-form lower bound on the Gibbs mass at the mode: 1 / (1 + (N-1) e^{-beta m}).
For a Gibbs law p_i ∝ e^{beta s_i} with top-two margin m = s_(1) - s_(2) >= 0, every
non-mode term obeys e^{-beta (s_(1) - s_i)} <= e^{-beta m} (since s_i <= s_(2)), so
p_max = 1 / (1 + sum_{i != mode} e^{-beta (s_(1) - s_i)}) >= 1 / (1 + (N-1) e^{-beta m}).
A larger num_choices or smaller beta / margin only *lowers* the bound -- it is
never optimistic. num_choices == 1 returns 1.0 (a singleton is already a Dirac).
Parameters
| Name | Type & default | Contract |
|---|---|---|
marginpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
num_choicespositional-or-keyword | intRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
num_choices < 1, raisesValueError(f'num_choices must be >= 1, got {num_choices}'). - When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}'). - When
margin < 0.0, raisesValueError(f'margin must be >= 0, got {margin}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · certificate sound on grid
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_certificate_sound_on_grid() -> None:
rng = np.random.default_rng(0)
for n in GRID_N:
for logits in _logit_shapes(n, rng):
for beta in GRID_BETA:
cert = certify_argmax(logits, beta)
_assert_sound(cert, logits, beta)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_certificate_sound_on_grid" -qRegression example · beta for confidence roundtrip
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_beta_for_confidence_roundtrip() -> None:
for n, m, target in [(3, 2.0, 0.99), (10, 0.5, 0.9), (2, 1.0, 0.999)]:
b = beta_for_confidence(m, n, target)
assert mass_concentration_bound(m, n, b) == pytest.approx(target, rel=1e-9, abs=1e-12)
# A hair below the required beta undershoots the target.
assert mass_concentration_bound(m, n, 0.99 * b) < targetpython -m pytest packages/omnibias-struct/tests/test_select.py -k test_beta_for_confidence_roundtrip -qRead the implementation
def mass_concentration_bound(margin: float, num_choices: int, beta: float) -> float:
r"""Closed-form lower bound on the Gibbs mass at the mode: ``1 / (1 + (N-1) e^{-beta m})``.
For a Gibbs law ``p_i ∝ e^{beta s_i}`` with top-two margin ``m = s_(1) - s_(2) >= 0``, every
non-mode term obeys ``e^{-beta (s_(1) - s_i)} <= e^{-beta m}`` (since ``s_i <= s_(2)``), so
``p_max = 1 / (1 + sum_{i != mode} e^{-beta (s_(1) - s_i)}) >= 1 / (1 + (N-1) e^{-beta m})``.
A larger ``num_choices`` or smaller ``beta`` / ``margin`` only *lowers* the bound -- it is
never optimistic. ``num_choices == 1`` returns ``1.0`` (a singleton is already a Dirac).
"""
if num_choices < 1:
raise ValueError(f"num_choices must be >= 1, got {num_choices}")
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
if num_choices == 1:
return 1.0
if margin < 0.0:
raise ValueError(f"margin must be >= 0, got {margin}")
if math.isinf(margin):
return 1.0
return 1.0 / (1.0 + (num_choices - 1) * math.exp(-beta * margin))Other public import paths
omnibias.struct.mass_concentration_boundomnibias.struct.select.mass_concentration_bound
seal_selection_certificate
omnibias.struct.seal_selection_certificateSource ↗seal_selection_certificate(cert: SelectionCertificate, *, meta: dict[str, Any] | None=None) -> CertSeal a SelectionCertificate as a tamper-evident v1 certificate.
The payload records the closed-form collapse claims (value gap, mass concentration, and the
optional L^inf argmax-stability radius). Honesty fixes unproven_claim=False; this is a
textbook analytic inequality, so theorem_prover_verified is not sought (the digest is
the guarantee). Verify with omnibias.core.proof.certificate.verify_certificate_digest.
Parameters
| Name | Type & default | Contract |
|---|---|---|
certpositional-or-keyword | SelectionCertificateRequired | See the operation contract and implementation below. |
metakeyword-only | dict[str, Any] | NoneDefault: None | See the operation contract and implementation below. |
CertExecuted regression · seal verify roundtrip and tamper
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_seal_verify_roundtrip_and_tamper() -> None:
cert = certify_argmax([3.0, 1.0, 0.5], beta=6.0, eps=0.2)
sealed = seal_selection_certificate(cert, meta={"note": "unit-test"})
# Import here: seal() warms omnibias.core.verified, breaking the core proof/verified cycle.
from omnibias.core.proof.certificate import verify_certificate_digest
assert verify_certificate_digest(sealed)
assert sealed["claim"].startswith("softmax(")
assert sealed["payload"]["type"] == "certified_argmax"
assert sealed["payload"]["argmax"] == cert.argmax
assert sealed["payload"]["argmax_stable"] is True
assert sealed["honesty"]["unproven_claim"] is False
assert sealed["meta"]["note"] == "unit-test"
# Tampering with any bound invalidates the digest.
tampered = {**sealed, "payload": {**sealed["payload"], "p_max_lower": 0.0}}
assert not verify_certificate_digest(tampered)python -m pytest "packages/omnibias-struct/tests/test_select.py::test_seal_verify_roundtrip_and_tamper" -qRead the implementation
def seal_selection_certificate(
cert: SelectionCertificate, *, meta: dict[str, Any] | None = None
) -> Cert:
r"""Seal a :class:`SelectionCertificate` as a tamper-evident v1 certificate.
The payload records the closed-form collapse claims (value gap, mass concentration, and the
optional ``L^inf`` argmax-stability radius). Honesty fixes ``unproven_claim=False``; this is a
textbook analytic inequality, so ``theorem_prover_verified`` is not sought (the digest is
the guarantee). Verify with :func:`omnibias.core.proof.certificate.verify_certificate_digest`.
"""
# Imported here (not at module load) so that `import omnibias.struct` stays free of the
# order-sensitive omnibias.core.proof <-> omnibias.core.verified import cycle; warming
# ``verified`` first fully resolves that cycle before ``proof.certificate`` is read.
import omnibias.core.verified # noqa: F401 (side-effect: breaks the core import cycle)
from omnibias.core.proof.certificate import make_certificate
payload: dict[str, Any] = {
"type": "certified_argmax",
"beta": cert.beta,
"num_choices": cert.num_choices,
"argmax": cert.argmax,
"hard_value": cert.hard_value,
"soft_value": cert.soft_value,
"value_gap_bound": cert.gap_bound,
"margin": cert.margin,
"p_max": cert.p_max,
"p_max_lower": cert.p_max_lower,
}
if cert.eps is not None:
payload["eps"] = cert.eps
payload["argmax_stable"] = bool(cert.argmax_stable)
claim = (
f"softmax(beta={cert.beta!r}) over {cert.num_choices} choices collapses onto mode "
f"{cert.argmax}: max <= lse_beta <= max + {cert.gap_bound!r}, and Gibbs mass "
f">= {cert.p_max_lower!r}"
)
payload_meta: dict[str, Any] = {
"scope": "closed_form_inequality",
"label": "closed-form (log(N)/beta value gap + mode-mass concentration bound)",
}
if meta:
payload_meta.update(meta)
return make_certificate(
claim=claim,
payload=payload,
honesty={"unproven_claim": False},
meta=payload_meta,
)Other public import paths
omnibias.struct.seal_selection_certificateomnibias.struct.select.seal_selection_certificate
CountingSemiring
omnibias.struct.CountingSemiringSource ↗class CountingSemiringThe (+, x) counting semiring -- exact number of derivations (weights ignored).
Executed regression · parse hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_parse_hard_equals_brute_and_count(seed: int) -> None:
assert probe_parse_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_parse_hard_equals_brute_and_count[0]" -qFields & methods
edgemethod
edge(self, weight: float, tails: Sequence[int]) -> intSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
weightpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
tailspositional-or-keyword | Sequence[int]Required | See the operation contract and implementation below. |
Returns: int
Executed regression · parse hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_parse_hard_equals_brute_and_count(seed: int) -> None:
assert probe_parse_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_parse_hard_equals_brute_and_count[0]" -qMethod implementation
def edge(self, weight: float, tails: Sequence[int]) -> int:
prod = 1
for t in tails:
prod *= t
return prodreducemethod
reduce(self, values: Sequence[int]) -> intSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuespositional-or-keyword | Sequence[int]Required | See the operation contract and implementation below. |
Returns: int
Executed regression · parse hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_parse_hard_equals_brute_and_count(seed: int) -> None:
assert probe_parse_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_parse_hard_equals_brute_and_count[0]" -qMethod implementation
def reduce(self, values: Sequence[int]) -> int:
return sum(values)Read the implementation
class CountingSemiring:
r"""The ``(+, x)`` counting semiring -- exact number of derivations (weights ignored)."""
zero: int = 0
one: int = 1
def edge(self, weight: float, tails: Sequence[int]) -> int:
prod = 1
for t in tails:
prod *= t
return prod
def reduce(self, values: Sequence[int]) -> int:
return sum(values)HyperEdge
omnibias.struct.HyperEdgeSource ↗class HyperEdgeDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
A weighted hyperedge head <- tails of arity len(tails) in {0, 1, 2}.
tails are node indices, each strictly less than head (topological order); an
arity-0 edge is an **axiom** (a leaf / base case). The edge weight is supplied
separately as weights[edge_index] so it can be an arbitrary differentiable function
of the backend parameters -- the structure here is pure data.
Parameters
| Name | Type & default | Contract |
|---|---|---|
headdataclass field | intRequired | See the operation contract and implementation below. |
tailsdataclass field | tuple[int, ...]Default: () | See the operation contract and implementation below. |
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qRegression example · structural validation
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_structural_validation() -> None:
with pytest.raises(ValueError, match="arity"):
HyperEdge(head=5, tails=(0, 1, 2))
with pytest.raises(ValueError, match="topological"):
HyperEdge(head=1, tails=(2,))
with pytest.raises(ValueError, match="root"):
Hypergraph(num_nodes=2, edges=(HyperEdge(head=0),), root=5)python -m pytest packages/omnibias-struct/tests/test_semiring.py -k test_structural_validation -qFields & methods
headfield
head: intDeclared int field on HyperEdge. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗tailsfield
tails: tuple[int, ...] = ()Declared tuple[int, ...] field on HyperEdge. Default expression: ().
__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
len(self.tails) > 2, raisesValueError(f'hyperedge arity must be <= 2, got {len(self.tails)} tails'). - When
t >= self.head, raisesValueError(f'hyperedge {self.head} <- {self.tails} violates topological order (tail {t} >= head {self.head})').
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qMethod implementation
def __post_init__(self) -> None:
if len(self.tails) > 2:
raise ValueError(f"hyperedge arity must be <= 2, got {len(self.tails)} tails")
for t in self.tails:
if t >= self.head:
raise ValueError(
f"hyperedge {self.head} <- {self.tails} violates topological order "
f"(tail {t} >= head {self.head})"
)Read the implementation
class HyperEdge:
r"""A weighted hyperedge ``head <- tails`` of arity ``len(tails) in {0, 1, 2}``.
``tails`` are node indices, each strictly less than ``head`` (topological order); an
arity-0 edge is an **axiom** (a leaf / base case). The edge weight is supplied
separately as ``weights[edge_index]`` so it can be an arbitrary differentiable function
of the backend parameters -- the structure here is pure data.
"""
head: int
tails: tuple[int, ...] = ()
def __post_init__(self) -> None:
if len(self.tails) > 2:
raise ValueError(f"hyperedge arity must be <= 2, got {len(self.tails)} tails")
for t in self.tails:
if t >= self.head:
raise ValueError(
f"hyperedge {self.head} <- {self.tails} violates topological order "
f"(tail {t} >= head {self.head})"
)Hypergraph
omnibias.struct.HypergraphSource ↗class HypergraphDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
A topologically-ordered weighted hypergraph with a distinguished root goal node.
Nodes are 0 .. num_nodes - 1; every HyperEdge's tails are < head so a
single forward sweep computes every node value. incoming lists the edges into a
node; num_edges is the length of the parallel weights vector consumed by the
reductions and the backend driver.
Parameters
| Name | Type & default | Contract |
|---|---|---|
num_nodesdataclass field | intRequired | See the operation contract and implementation below. |
edgesdataclass field | tuple[HyperEdge, ...]Required | See the operation contract and implementation below. |
rootdataclass field | intRequired | See the operation contract and implementation below. |
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qRegression example · structural validation
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_structural_validation() -> None:
with pytest.raises(ValueError, match="arity"):
HyperEdge(head=5, tails=(0, 1, 2))
with pytest.raises(ValueError, match="topological"):
HyperEdge(head=1, tails=(2,))
with pytest.raises(ValueError, match="root"):
Hypergraph(num_nodes=2, edges=(HyperEdge(head=0),), root=5)python -m pytest packages/omnibias-struct/tests/test_semiring.py -k test_structural_validation -qFields & methods
num_nodesfield
num_nodes: intDeclared int field on Hypergraph. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗edgesfield
edges: tuple[HyperEdge, ...]Declared tuple[HyperEdge, ...] field on Hypergraph. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗rootfield
root: intDeclared int field on Hypergraph. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
self.num_nodes < 1, raisesValueError(f'num_nodes must be >= 1, got {self.num_nodes}'). - When
not 0 <= self.root < self.num_nodes, raisesValueError(f'root {self.root} out of range [0, {self.num_nodes})'). - When
not 0 <= e.head < self.num_nodes, raisesValueError(f'edge {ei} head {e.head} out of range [0, {self.num_nodes})'). - When
not 0 <= t < self.num_nodes, raisesValueError(f'edge {ei} tail {t} out of range [0, {self.num_nodes})').
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qMethod implementation
def __post_init__(self) -> None:
if self.num_nodes < 1:
raise ValueError(f"num_nodes must be >= 1, got {self.num_nodes}")
if not 0 <= self.root < self.num_nodes:
raise ValueError(f"root {self.root} out of range [0, {self.num_nodes})")
inc: list[list[int]] = [[] for _ in range(self.num_nodes)]
for ei, e in enumerate(self.edges):
if not 0 <= e.head < self.num_nodes:
raise ValueError(f"edge {ei} head {e.head} out of range [0, {self.num_nodes})")
for t in e.tails:
if not 0 <= t < self.num_nodes:
raise ValueError(f"edge {ei} tail {t} out of range [0, {self.num_nodes})")
inc[e.head].append(ei)
object.__setattr__(self, "_incoming", tuple(tuple(x) for x in inc))num_edgesproperty
num_edges(self) -> intNumber of hyperedges (the length of the weights vector).
Returns: int
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qMethod implementation
def num_edges(self) -> int:
"""Number of hyperedges (the length of the ``weights`` vector)."""
return len(self.edges)incomingmethod
incoming(self, node: int) -> tuple[int, ...]Edge indices whose head is node (the alternatives reduced at node).
Parameters
| Name | Type & default | Contract |
|---|---|---|
nodepositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: tuple[int, ...]
Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qMethod implementation
def incoming(self, node: int) -> tuple[int, ...]:
"""Edge indices whose head is ``node`` (the alternatives reduced at ``node``)."""
return self._incoming[node]Read the implementation
class Hypergraph:
r"""A topologically-ordered weighted hypergraph with a distinguished ``root`` goal node.
Nodes are ``0 .. num_nodes - 1``; every :class:`HyperEdge`'s tails are ``< head`` so a
single forward sweep computes every node value. :meth:`incoming` lists the edges into a
node; :attr:`num_edges` is the length of the parallel ``weights`` vector consumed by the
reductions and the backend driver.
"""
num_nodes: int
edges: tuple[HyperEdge, ...]
root: int
_incoming: tuple[tuple[int, ...], ...] = ()
def __post_init__(self) -> None:
if self.num_nodes < 1:
raise ValueError(f"num_nodes must be >= 1, got {self.num_nodes}")
if not 0 <= self.root < self.num_nodes:
raise ValueError(f"root {self.root} out of range [0, {self.num_nodes})")
inc: list[list[int]] = [[] for _ in range(self.num_nodes)]
for ei, e in enumerate(self.edges):
if not 0 <= e.head < self.num_nodes:
raise ValueError(f"edge {ei} head {e.head} out of range [0, {self.num_nodes})")
for t in e.tails:
if not 0 <= t < self.num_nodes:
raise ValueError(f"edge {ei} tail {t} out of range [0, {self.num_nodes})")
inc[e.head].append(ei)
object.__setattr__(self, "_incoming", tuple(tuple(x) for x in inc))
@property
def num_edges(self) -> int:
"""Number of hyperedges (the length of the ``weights`` vector)."""
return len(self.edges)
def incoming(self, node: int) -> tuple[int, ...]:
"""Edge indices whose head is ``node`` (the alternatives reduced at ``node``)."""
return self._incoming[node]LogSemiring
omnibias.struct.LSEBetaSource ↗class LogSemiringThe soft (lse_beta, +) log semiring -- the differentiable relaxation.
Parameters
| Name | Type & default | Contract |
|---|---|---|
betapositional-or-keyword | floatDefault: 1.0 | See the operation contract and implementation below. |
Executed regression · entropy identity and mc
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_entropy_identity_and_mc(backend: str) -> None:
pytest.importorskip(backend)
rec = probe_entropy(0, BETA, backend)
assert rec.ok, rec
assert rec.metrics["identity_err"] < 1e-8python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_entropy_identity_and_mc[jax]" -qFields & methods
__init__method
__init__(self, beta: float=1.0) -> NoneSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
betapositional-or-keyword | floatDefault: 1.0 | See the operation contract and implementation below. |
Returns: None
Validation & failure cases
- When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
Executed regression · entropy identity and mc
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_entropy_identity_and_mc(backend: str) -> None:
pytest.importorskip(backend)
rec = probe_entropy(0, BETA, backend)
assert rec.ok, rec
assert rec.metrics["identity_err"] < 1e-8python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_entropy_identity_and_mc[jax]" -qMethod implementation
def __init__(self, beta: float = 1.0) -> None:
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
self.beta = float(beta)zeroproperty
zero(self) -> floatSee the class contract above and the exact method implementation below.
Returns: float
Executed regression · entropy identity and mc
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_entropy_identity_and_mc(backend: str) -> None:
pytest.importorskip(backend)
rec = probe_entropy(0, BETA, backend)
assert rec.ok, rec
assert rec.metrics["identity_err"] < 1e-8python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_entropy_identity_and_mc[jax]" -qMethod implementation
def zero(self) -> float:
return -math.infedgemethod
edge(self, weight: float, tails: Sequence[float]) -> floatSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
weightpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
tailspositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
Returns: float
Executed regression · entropy identity and mc
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_entropy_identity_and_mc(backend: str) -> None:
pytest.importorskip(backend)
rec = probe_entropy(0, BETA, backend)
assert rec.ok, rec
assert rec.metrics["identity_err"] < 1e-8python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_entropy_identity_and_mc[jax]" -qMethod implementation
def edge(self, weight: float, tails: Sequence[float]) -> float:
return weight + sum(tails)reducemethod
reduce(self, values: Sequence[float]) -> floatSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuespositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
Returns: float
Executed regression · entropy identity and mc
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_entropy_identity_and_mc(backend: str) -> None:
pytest.importorskip(backend)
rec = probe_entropy(0, BETA, backend)
assert rec.ok, rec
assert rec.metrics["identity_err"] < 1e-8python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_entropy_identity_and_mc[jax]" -qMethod implementation
def reduce(self, values: Sequence[float]) -> float:
return _logsumexp(np.asarray(values, dtype=float), self.beta)betaattribute
beta = float(beta)Public instance attribute assigned by __init__. The source assignment is beta = float(beta); it describes instance state, not a literal constructor default.
Read the implementation
class LogSemiring:
r"""The soft ``(lse_beta, +)`` log semiring -- the differentiable relaxation."""
one: float = 0.0
def __init__(self, beta: float = 1.0) -> None:
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
self.beta = float(beta)
@property
def zero(self) -> float:
return -math.inf
def edge(self, weight: float, tails: Sequence[float]) -> float:
return weight + sum(tails)
def reduce(self, values: Sequence[float]) -> float:
return _logsumexp(np.asarray(values, dtype=float), self.beta)Other public import paths
omnibias.struct.LSEBetaomnibias.struct.LogSemiring
MaxPlusSemiring
omnibias.struct.MaxPlusSemiringSource ↗class MaxPlusSemiringThe hard (max, +) tropical semiring -- the beta -> inf optimum.
Executed regression · oracle matches bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_matches_bruteforce(beta: float) -> None:
g, w = _toy_graph()
assert abs(hard_value(g, w) - brute_force_value(g, w, None)) < TOL
assert abs(soft_value(g, w, beta) - brute_force_value(g, w, beta)) < TOLpython -m pytest "packages/omnibias-struct/tests/test_semiring.py::test_oracle_matches_bruteforce[0.5]" -qFields & methods
zerofield
zero: float = -math.infDeclared float field on MaxPlusSemiring. Default expression: -math.inf.
onefield
one: float = 0.0Declared float field on MaxPlusSemiring. Default expression: 0.0.
edgemethod
edge(self, weight: float, tails: Sequence[float]) -> floatSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
weightpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
tailspositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
Returns: float
Executed regression · oracle matches bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_matches_bruteforce(beta: float) -> None:
g, w = _toy_graph()
assert abs(hard_value(g, w) - brute_force_value(g, w, None)) < TOL
assert abs(soft_value(g, w, beta) - brute_force_value(g, w, beta)) < TOLpython -m pytest "packages/omnibias-struct/tests/test_semiring.py::test_oracle_matches_bruteforce[0.5]" -qMethod implementation
def edge(self, weight: float, tails: Sequence[float]) -> float:
return weight + sum(tails)reducemethod
reduce(self, values: Sequence[float]) -> floatSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuespositional-or-keyword | Sequence[float]Required | See the operation contract and implementation below. |
Returns: float
Executed regression · oracle matches bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_matches_bruteforce(beta: float) -> None:
g, w = _toy_graph()
assert abs(hard_value(g, w) - brute_force_value(g, w, None)) < TOL
assert abs(soft_value(g, w, beta) - brute_force_value(g, w, beta)) < TOLpython -m pytest "packages/omnibias-struct/tests/test_semiring.py::test_oracle_matches_bruteforce[0.5]" -qMethod implementation
def reduce(self, values: Sequence[float]) -> float:
return max(values) if values else self.zeroRead the implementation
class MaxPlusSemiring:
r"""The hard ``(max, +)`` tropical semiring -- the ``beta -> inf`` optimum."""
zero: float = -math.inf
one: float = 0.0
def edge(self, weight: float, tails: Sequence[float]) -> float:
return weight + sum(tails)
def reduce(self, values: Sequence[float]) -> float:
return max(values) if values else self.zeroSemiring
omnibias.struct.SemiringSource ↗class Semiring(Protocol[T])A DP semiring: edge combines a weight with tail values, reduce over edges.
zero is the reduction identity (the value of a node with no incoming edges);
one the combination identity (the empty tail product). edge(weight, tails) is
the value contributed by one hyperedge; reduce(values) folds the alternatives.
Fields & methods
zeroproperty
zero(self) -> TSee the class contract above and the exact method implementation below.
Returns: T
Method implementation
def zero(self) -> T: ...oneproperty
one(self) -> TSee the class contract above and the exact method implementation below.
Returns: T
Method implementation
def one(self) -> T: ...edgemethod
edge(self, weight: float, tails: Sequence[T]) -> TSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
weightpositional-or-keyword | floatRequired | See the operation contract and implementation below. |
tailspositional-or-keyword | Sequence[T]Required | See the operation contract and implementation below. |
Returns: T
Method implementation
def edge(self, weight: float, tails: Sequence[T]) -> T: ...reducemethod
reduce(self, values: Sequence[T]) -> TSee the class contract above and the exact method implementation below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
valuespositional-or-keyword | Sequence[T]Required | See the operation contract and implementation below. |
Returns: T
Method implementation
def reduce(self, values: Sequence[T]) -> T: ...Read the implementation
class Semiring(Protocol[T]):
r"""A DP semiring: ``edge`` combines a weight with tail values, ``reduce`` over edges.
``zero`` is the reduction identity (the value of a node with no incoming edges);
``one`` the combination identity (the empty tail product). ``edge(weight, tails)`` is
the value contributed by one hyperedge; ``reduce(values)`` folds the alternatives.
"""
@property
def zero(self) -> T: ...
@property
def one(self) -> T: ...
def edge(self, weight: float, tails: Sequence[T]) -> T: ...
def reduce(self, values: Sequence[T]) -> T: ...best_derivation
omnibias.struct.best_derivationSource ↗best_derivation(graph: Hypergraph, weights: WeightVector) -> tuple[float, tuple[int, ...]]Max-plus optimal derivation: its score and the tuple of edge indices (pre-order).
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
weightspositional-or-keyword | WeightVectorRequired | See the operation contract and implementation below. |
tuple[float, tuple[int, ...]]Explicit validation & failure cases
- When
len(w) != graph.num_edges, raisesValueError(f'weights must have length num_edges={graph.num_edges}, got {len(w)}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · best derivation agrees with hard value
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_best_derivation_agrees_with_hard_value() -> None:
g, w = _toy_graph()
value, deriv = best_derivation(g, w)
assert abs(value - hard_value(g, w)) < TOL
# the derivation's edge weights sum back to the value
assert abs(sum(w[e] for e in deriv) - value) < TOLpython -m pytest "packages/omnibias-struct/tests/test_semiring.py::test_best_derivation_agrees_with_hard_value" -qRegression example · topk free energy monotone and limits
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_topk_free_energy_monotone_and_limits(seed: int) -> None:
w = _weights(seed)
wt = torch.tensor(w)
n = count_derivations(GRAPH)
beta = 2.0
energies = [float(st.topk_free_energy(GRAPH, wt, k, beta)) for k in range(1, n + 1)]
assert all(energies[i] <= energies[i + 1] + 1e-12 for i in range(len(energies) - 1))
assert abs(energies[-1] - float(st.semiring_value(GRAPH, wt, beta))) < 1e-9 # k = N -> full soft value
best, _ = best_derivation(GRAPH, w)
assert abs(float(st.topk_free_energy(GRAPH, wt, 1, 128.0)) - best) < 1e-6 # k = 1, beta -> infpython -m pytest packages/omnibias-struct/tests/test_operators.py -k test_topk_free_energy_monotone_and_limits -qRead the implementation
def best_derivation(graph: Hypergraph, weights: WeightVector) -> tuple[float, tuple[int, ...]]:
r"""Max-plus optimal derivation: its score and the tuple of edge indices (pre-order)."""
w = [float(x) for x in weights]
if len(w) != graph.num_edges:
raise ValueError(f"weights must have length num_edges={graph.num_edges}, got {len(w)}")
value = [-math.inf] * graph.num_nodes
choice = [-1] * graph.num_nodes
for v in range(graph.num_nodes):
for ei in graph.incoming(v):
e = graph.edges[ei]
score = w[ei] + sum(value[t] for t in e.tails)
if score > value[v]:
value[v], choice[v] = score, ei
def build(node: int) -> tuple[int, ...]:
ei = choice[node]
if ei < 0:
raise ValueError(f"node {node} has no derivation (unreachable)")
out = [ei]
for t in graph.edges[ei].tails:
out.extend(build(t))
return tuple(out)
return value[graph.root], build(graph.root)brute_force_value
omnibias.struct.brute_force_valueSource ↗brute_force_value(graph: Hypergraph, weights: WeightVector, beta: float | None=None) -> floatFlat oracle: max (beta is None) or lse_beta over *enumerated* derivations.
The ground truth for hard_value / soft_value -- enumerates every
derivation (exponential, tiny graphs only) and reduces their scores directly.
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
weightspositional-or-keyword | WeightVectorRequired | See the operation contract and implementation below. |
betapositional-or-keyword | float | NoneDefault: None | See the operation contract and implementation below. |
floatExplicit validation & failure cases
- When
scores.size == 0, raisesValueError('graph has no complete derivations (root unreachable)'). - When
beta <= 0.0, raisesValueError(f'beta must be > 0, got {beta}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · parse hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_parse_hard_equals_brute_and_count(seed: int) -> None:
assert probe_parse_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_parse_hard_equals_brute_and_count[0]" -qRegression example · oracle matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_matches_bruteforce(beta: float) -> None:
g, w = _toy_graph()
assert abs(hard_value(g, w) - brute_force_value(g, w, None)) < TOL
assert abs(soft_value(g, w, beta) - brute_force_value(g, w, beta)) < TOLpython -m pytest packages/omnibias-struct/tests/test_semiring.py -k test_oracle_matches_bruteforce -qRead the implementation
def brute_force_value(
graph: Hypergraph,
weights: WeightVector,
beta: float | None = None,
) -> float:
r"""Flat oracle: ``max`` (``beta is None``) or ``lse_beta`` over *enumerated* derivations.
The ground truth for :func:`hard_value` / :func:`soft_value` -- enumerates every
derivation (exponential, tiny graphs only) and reduces their scores directly.
"""
scores = np.array(
[derivation_weight(weights, d) for d in enumerate_derivations(graph)], dtype=np.float64
)
if scores.size == 0:
raise ValueError("graph has no complete derivations (root unreachable)")
if beta is None:
return float(np.max(scores))
if beta <= 0.0:
raise ValueError(f"beta must be > 0, got {beta}")
return _logsumexp(scores, beta)count_derivations
omnibias.struct.count_derivationsSource ↗count_derivations(graph: Hypergraph) -> intExact number of complete derivations rooted at graph.root -- the N in the gap.
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
intExecuted regression · parse hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_parse_hard_equals_brute_and_count(seed: int) -> None:
assert probe_parse_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_parse_hard_equals_brute_and_count[0]" -qRegression example · counting matches enumeration
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_counting_matches_enumeration() -> None:
g, _ = _toy_graph()
assert count_derivations(g) == len(list(enumerate_derivations(g)))python -m pytest packages/omnibias-struct/tests/test_semiring.py -k test_counting_matches_enumeration -qRead the implementation
def count_derivations(graph: Hypergraph) -> int:
r"""Exact number of complete derivations rooted at ``graph.root`` -- the ``N`` in the gap."""
return semiring_value(graph, None, CountingSemiring())derivation_weight
omnibias.struct.derivation_weightSource ↗derivation_weight(weights: WeightVector, derivation: Sequence[int]) -> floatAdditive score of a derivation: sum(weights[e] for e in derivation).
Parameters
| Name | Type & default | Contract |
|---|---|---|
weightspositional-or-keyword | WeightVectorRequired | See the operation contract and implementation below. |
derivationpositional-or-keyword | Sequence[int]Required | See the operation contract and implementation below. |
floatExecuted regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qRead the implementation
def derivation_weight(weights: WeightVector, derivation: Sequence[int]) -> float:
r"""Additive score of a derivation: ``sum(weights[e] for e in derivation)``."""
return float(sum(float(weights[e]) for e in derivation))enumerate_derivations
omnibias.struct.enumerate_derivationsSource ↗enumerate_derivations(graph: Hypergraph) -> Iterator[tuple[int, ...]]Yield every complete derivation as an edge-index tuple (brute-force; tiny graphs).
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
Iterator[tuple[int, ...]]Executed regression · exact kbest equals bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_exact_kbest_equals_bruteforce() -> None:
assert probe_kbest(0).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_exact_kbest_equals_bruteforce" -qRegression example · counting matches enumeration
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_counting_matches_enumeration() -> None:
g, _ = _toy_graph()
assert count_derivations(g) == len(list(enumerate_derivations(g)))python -m pytest packages/omnibias-struct/tests/test_semiring.py -k test_counting_matches_enumeration -qRead the implementation
def enumerate_derivations(graph: Hypergraph) -> Iterator[tuple[int, ...]]:
r"""Yield every complete derivation as an edge-index tuple (brute-force; tiny graphs)."""
memo: dict[int, list[tuple[int, ...]]] = {}
def at(node: int) -> list[tuple[int, ...]]:
if node in memo:
return memo[node]
out: list[tuple[int, ...]] = []
for ei in graph.incoming(node):
e = graph.edges[ei]
tail_derivs = [at(t) for t in e.tails]
for combo in _product(tail_derivs):
merged = (ei, *[x for sub in combo for x in sub])
out.append(merged)
memo[node] = out
return out
yield from at(graph.root)from_dag
omnibias.struct.from_dagSource ↗from_dag(dag: DAG) -> tuple[Hypergraph, dict[tuple[int, int], int]]Lift a DAG into a Hypergraph (arity-1 edges + a source axiom).
Returns (graph, edge_index) where edge_index[(u, v)] is the hyperedge position
of DAG edge u -> v (so a backend builds weights by scattering the per-edge
*scores* there; the source axiom edge keeps weight 0). graph.root is
dag.sink. The driver value equals the soft path *score* (max convention); softmin
shortest-path cost is its negation, matching
omnibias.struct.torch.soft_shortest_path.
Parameters
| Name | Type & default | Contract |
|---|---|---|
dagpositional-or-keyword | DAGRequired | See the operation contract and implementation below. |
tuple[Hypergraph, dict[tuple[int, int], int]]Executed regression · from dag counts match
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_from_dag_counts_match(seed: int) -> None:
dag = random_dag(seed)
g, _ = from_dag(dag)
assert count_derivations(g) == dag.count_paths()python -m pytest "packages/omnibias-struct/tests/test_semiring.py::test_from_dag_counts_match[0]" -qRegression example · driver torch jax parity
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_driver_torch_jax_parity(seed: int) -> None:
dag = random_dag(seed)
w = dag_weight_matrix(dag)
g, idx = from_dag(dag)
for beta in (1.0, 8.0):
ew_t = _dag_edge_weights(g, idx, -torch.tensor(w), torch)
ew_j = _dag_edge_weights(g, idx, -jnp.asarray(w), jnp)
assert abs(float(st.semiring_value(g, ew_t, beta)) - float(sj.semiring_value(g, ew_j, beta))) < 1e-11
mt = np.asarray(st.semiring_marginals(g, ew_t, beta).detach())
mj = np.asarray(sj.semiring_marginals(g, ew_j, beta))
assert float(np.max(np.abs(mt - mj))) < 1e-11python -m pytest packages/omnibias-struct/tests/test_semiring.py -k test_driver_torch_jax_parity -qRead the implementation
def from_dag(dag: DAG) -> tuple[Hypergraph, dict[tuple[int, int], int]]:
r"""Lift a :class:`DAG` into a :class:`Hypergraph` (arity-1 edges + a source axiom).
Returns ``(graph, edge_index)`` where ``edge_index[(u, v)]`` is the hyperedge position
of DAG edge ``u -> v`` (so a backend builds ``weights`` by scattering the per-edge
*scores* there; the source axiom edge keeps weight ``0``). ``graph.root`` is
``dag.sink``. The driver value equals the soft path *score* (max convention); softmin
shortest-path cost is its negation, matching
:func:`omnibias.struct.torch.soft_shortest_path`.
"""
edges: list[HyperEdge] = [HyperEdge(head=dag.source, tails=())]
edge_index: dict[tuple[int, int], int] = {}
for u, v in sorted(dag.edges):
edge_index[(u, v)] = len(edges)
edges.append(HyperEdge(head=v, tails=(u,)))
graph = Hypergraph(num_nodes=dag.num_nodes, edges=tuple(edges), root=dag.sink)
return graph, edge_indexhard_value
omnibias.struct.hard_valueSource ↗hard_value(graph: Hypergraph, weights: WeightVector) -> floatBest (max-plus) derivation score of graph -- the beta -> inf optimum.
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
weightspositional-or-keyword | WeightVectorRequired | See the operation contract and implementation below. |
floatExecuted regression · oracle matches bruteforce
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_matches_bruteforce(beta: float) -> None:
g, w = _toy_graph()
assert abs(hard_value(g, w) - brute_force_value(g, w, None)) < TOL
assert abs(soft_value(g, w, beta) - brute_force_value(g, w, beta)) < TOLpython -m pytest "packages/omnibias-struct/tests/test_semiring.py::test_oracle_matches_bruteforce[0.5]" -qRegression example · best derivation agrees with hard value
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_best_derivation_agrees_with_hard_value() -> None:
g, w = _toy_graph()
value, deriv = best_derivation(g, w)
assert abs(value - hard_value(g, w)) < TOL
# the derivation's edge weights sum back to the value
assert abs(sum(w[e] for e in deriv) - value) < TOLpython -m pytest packages/omnibias-struct/tests/test_semiring.py -k test_best_derivation_agrees_with_hard_value -qRead the implementation
def hard_value(graph: Hypergraph, weights: WeightVector) -> float:
r"""Best (max-plus) derivation score of ``graph`` -- the ``beta -> inf`` optimum."""
return semiring_value(graph, weights, MaxPlusSemiring())semiring_value
omnibias.struct.semiring_valueSource ↗semiring_value(graph: Hypergraph, weights: WeightVector | None, semiring: Semiring[T]) -> TReduce graph to its root value under semiring (one topological sweep).
weights is a length-graph.num_edges vector of edge weights (None for the
weight-free CountingSemiring). This is the pure-numpy oracle the backend
drivers reproduce; it is exact for any DAG-shaped derivation forest.
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
weightspositional-or-keyword | WeightVector | NoneRequired | See the operation contract and implementation below. |
semiringpositional-or-keyword | Semiring[T]Required | See the operation contract and implementation below. |
TExplicit validation & failure cases
- When
weights is not None and len(weights) != graph.num_edges, raisesValueError(f'weights must have length num_edges={graph.num_edges}, got {len(weights)}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · parse hard equals brute and count
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_parse_hard_equals_brute_and_count(seed: int) -> None:
assert probe_parse_oracle(seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_parse_hard_equals_brute_and_count[0]" -qRead the implementation
def semiring_value(
graph: Hypergraph,
weights: WeightVector | None,
semiring: Semiring[T],
) -> T:
r"""Reduce ``graph`` to its ``root`` value under ``semiring`` (one topological sweep).
``weights`` is a length-``graph.num_edges`` vector of edge weights (``None`` for the
weight-free :class:`CountingSemiring`). This is the pure-numpy oracle the backend
drivers reproduce; it is exact for any DAG-shaped derivation forest.
"""
if weights is not None and len(weights) != graph.num_edges:
raise ValueError(f"weights must have length num_edges={graph.num_edges}, got {len(weights)}")
vals: list[T] = [semiring.zero] * graph.num_nodes
for v in range(graph.num_nodes):
inc = graph.incoming(v)
if not inc:
continue
edge_vals: list[T] = []
for ei in inc:
e = graph.edges[ei]
w = 0.0 if weights is None else float(weights[ei])
edge_vals.append(semiring.edge(w, [vals[t] for t in e.tails]))
vals[v] = semiring.reduce(edge_vals)
return vals[graph.root]soft_value
omnibias.struct.soft_valueSource ↗soft_value(graph: Hypergraph, weights: WeightVector, beta: float) -> floatSoft lse_beta derivation value (numpy oracle for the backend semiring_value).
Parameters
| Name | Type & default | Contract |
|---|---|---|
graphpositional-or-keyword | HypergraphRequired | See the operation contract and implementation below. |
weightspositional-or-keyword | WeightVectorRequired | See the operation contract and implementation below. |
betapositional-or-keyword | floatRequired | See the operation contract and implementation below. |
floatExecuted regression · entropy identity and mc
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_entropy_identity_and_mc(backend: str) -> None:
pytest.importorskip(backend)
rec = probe_entropy(0, BETA, backend)
assert rec.ok, rec
assert rec.metrics["identity_err"] < 1e-8python -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_entropy_identity_and_mc[jax]" -qRegression example · oracle matches bruteforce
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_matches_bruteforce(beta: float) -> None:
g, w = _toy_graph()
assert abs(hard_value(g, w) - brute_force_value(g, w, None)) < TOL
assert abs(soft_value(g, w, beta) - brute_force_value(g, w, beta)) < TOLpython -m pytest packages/omnibias-struct/tests/test_semiring.py -k test_oracle_matches_bruteforce -qRead the implementation
def soft_value(graph: Hypergraph, weights: WeightVector, beta: float) -> float:
r"""Soft ``lse_beta`` derivation value (numpy oracle for the backend ``semiring_value``)."""
return semiring_value(graph, weights, LogSemiring(beta))CTCLattice
omnibias.struct.CTCLatticeSource ↗class CTCLatticeDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
The blank-augmented CTC alignment lattice for a fixed label sequence.
targets are the (non-blank) label ids to emit in order; blank is the blank
symbol id; num_classes is the alphabet size (including blank). A length-T
alignment is a class-id sequence that, after merging equal neighbours and dropping
blanks, equals targets. The extended path visits positions in the sequence
l' = (blank, y_0, blank, y_1, ..., y_{L-1}, blank) of length 2 L + 1.
Parameters
| Name | Type & default | Contract |
|---|---|---|
targetsdataclass field | IntArrayRequired | See the operation contract and implementation below. |
num_classesdataclass field | intRequired | See the operation contract and implementation below. |
blankdataclass field | intDefault: 0 | See the operation contract and implementation below. |
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-ctc]" -qRegression example · log num paths infeasible ctc is neg inf
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_log_num_paths_infeasible_ctc_is_neg_inf() -> None:
lattice = CTCLattice(np.array([1, 2, 1]), num_classes=3) # L = 3 labels
assert log_num_paths(lattice, 2) == -math.inf # T = 2 < L: cannot emit every labelpython -m pytest packages/omnibias-struct/tests/test_core_harden.py -k test_log_num_paths_infeasible_ctc_is_neg_inf -qFields & methods
targetsfield
targets: IntArrayDeclared IntArray field on CTCLattice. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
Regression example · ctc best alignment value and collapse
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_ctc_best_alignment_value_and_collapse(seed: int) -> None:
lattice, lp = sample_ctc(seed)
value, alignment = ctc_best_alignment(lattice, lp)
assert abs(value - ctc_best(lattice, lp)) < 1e-12
assert abs(value - brute_force_ctc(lattice, lp)) < 1e-9
assert len(alignment) == lp.shape[0]
assert lattice.collapse(alignment) == tuple(int(y) for y in lattice.targets)
assert abs(sum(lp[t, alignment[t]] for t in range(lp.shape[0])) - value) < 1e-9python -m pytest packages/omnibias-struct/tests/test_core_harden.py -k test_ctc_best_alignment_value_and_collapse -qnum_classesfield
num_classes: intDeclared int field on CTCLattice. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
self.num_classes < 1, raisesValueError(f'num_classes must be >= 1, got {self.num_classes}'). - When
not 0 <= self.blank < self.num_classes, raisesValueError(f'blank {self.blank} out of range [0, {self.num_classes})'). - When
not 0 <= y < self.num_classes, raisesValueError(f'target label {y} out of range [0, {self.num_classes})'). - When
y == self.blank, raisesValueError('target labels must be non-blank').
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-ctc]" -qMethod implementation
def __post_init__(self) -> None:
targets = np.asarray(self.targets, dtype=int).reshape(-1)
if self.num_classes < 1:
raise ValueError(f"num_classes must be >= 1, got {self.num_classes}")
if not 0 <= self.blank < self.num_classes:
raise ValueError(f"blank {self.blank} out of range [0, {self.num_classes})")
for y in targets:
if not 0 <= y < self.num_classes:
raise ValueError(f"target label {y} out of range [0, {self.num_classes})")
if y == self.blank:
raise ValueError("target labels must be non-blank")
object.__setattr__(self, "targets", targets)n_labelsproperty
n_labels(self) -> intNumber of target labels L.
Returns: int
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-ctc]" -qMethod implementation
def n_labels(self) -> int:
"""Number of target labels ``L``."""
return int(self.targets.shape[0])extended_labelsmethod
extended_labels(self) -> IntArrayThe blank-interleaved sequence l' of length 2 L + 1.
Returns: IntArray
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-ctc]" -qMethod implementation
def extended_labels(self) -> IntArray:
"""The blank-interleaved sequence ``l'`` of length ``2 L + 1``."""
m = 2 * self.n_labels + 1
ext = np.full(m, self.blank, dtype=int)
for i, y in enumerate(self.targets):
ext[2 * i + 1] = int(y)
return extincomingmethod
incoming(self, s: int) -> list[int]Extended-lattice predecessors of position s (self, previous, skip).
Parameters
| Name | Type & default | Contract |
|---|---|---|
spositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: list[int]
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-ctc]" -qMethod implementation
def incoming(self, s: int) -> list[int]:
r"""Extended-lattice predecessors of position ``s`` (self, previous, skip)."""
ext = self.extended_labels()
preds = [s]
if s - 1 >= 0:
preds.append(s - 1)
if s - 2 >= 0 and ext[s] != self.blank and ext[s] != ext[s - 2]:
preds.append(s - 2)
return sorted(preds)collapsemethod
collapse(self, seq: object) -> tuple[int, ...]Merge equal neighbours then drop blanks -- the CTC label of an alignment.
Parameters
| Name | Type & default | Contract |
|---|---|---|
seqpositional-or-keyword | objectRequired | See the operation contract and implementation below. |
Returns: tuple[int, ...]
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-ctc]" -qMethod implementation
def collapse(self, seq: object) -> tuple[int, ...]:
"""Merge equal neighbours then drop blanks -- the CTC label of an alignment."""
out: list[int] = []
prev = None
for c in (int(x) for x in np.asarray(seq, dtype=int).reshape(-1)):
if c != prev:
out.append(c)
prev = c
return tuple(c for c in out if c != self.blank)count_alignmentsmethod
count_alignments(self, n_steps: int) -> intExact number of length-n_steps alignments that collapse to targets.
Parameters
| Name | Type & default | Contract |
|---|---|---|
n_stepspositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: int
Validation & failure cases
- When
n_steps < 1, raisesValueError(f'n_steps must be >= 1, got {n_steps}').
Executed regression · logspace path count matches exact
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_logspace_path_count_matches_exact(problem: str, seed: int) -> None:
rec = probe_path_count(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_logspace_path_count_matches_exact[0-ctc]" -qMethod implementation
def count_alignments(self, n_steps: int) -> int:
"""Exact number of length-``n_steps`` alignments that collapse to ``targets``."""
if n_steps < 1:
raise ValueError(f"n_steps must be >= 1, got {n_steps}")
m = 2 * self.n_labels + 1
if n_steps < self.n_labels: # too short to emit every label
return 0
counts = [0] * m
counts[0] = 1
if m > 1:
counts[1] = 1
for _ in range(1, n_steps):
nxt = [0] * m
for s in range(m):
nxt[s] = sum(counts[p] for p in self.incoming(s))
counts = nxt
total = counts[m - 1]
if m >= 2:
total += counts[m - 2]
return int(total)Read the implementation
class CTCLattice:
r"""The blank-augmented CTC alignment lattice for a fixed label sequence.
``targets`` are the (non-blank) label ids to emit in order; ``blank`` is the blank
symbol id; ``num_classes`` is the alphabet size (including blank). A length-``T``
alignment is a class-id sequence that, after merging equal neighbours and dropping
blanks, equals ``targets``. The extended path visits positions in the sequence
``l' = (blank, y_0, blank, y_1, ..., y_{L-1}, blank)`` of length ``2 L + 1``.
"""
targets: IntArray
num_classes: int
blank: int = 0
def __post_init__(self) -> None:
targets = np.asarray(self.targets, dtype=int).reshape(-1)
if self.num_classes < 1:
raise ValueError(f"num_classes must be >= 1, got {self.num_classes}")
if not 0 <= self.blank < self.num_classes:
raise ValueError(f"blank {self.blank} out of range [0, {self.num_classes})")
for y in targets:
if not 0 <= y < self.num_classes:
raise ValueError(f"target label {y} out of range [0, {self.num_classes})")
if y == self.blank:
raise ValueError("target labels must be non-blank")
object.__setattr__(self, "targets", targets)
@property
def n_labels(self) -> int:
"""Number of target labels ``L``."""
return int(self.targets.shape[0])
def extended_labels(self) -> IntArray:
"""The blank-interleaved sequence ``l'`` of length ``2 L + 1``."""
m = 2 * self.n_labels + 1
ext = np.full(m, self.blank, dtype=int)
for i, y in enumerate(self.targets):
ext[2 * i + 1] = int(y)
return ext
def incoming(self, s: int) -> list[int]:
r"""Extended-lattice predecessors of position ``s`` (self, previous, skip)."""
ext = self.extended_labels()
preds = [s]
if s - 1 >= 0:
preds.append(s - 1)
if s - 2 >= 0 and ext[s] != self.blank and ext[s] != ext[s - 2]:
preds.append(s - 2)
return sorted(preds)
def collapse(self, seq: object) -> tuple[int, ...]:
"""Merge equal neighbours then drop blanks -- the CTC label of an alignment."""
out: list[int] = []
prev = None
for c in (int(x) for x in np.asarray(seq, dtype=int).reshape(-1)):
if c != prev:
out.append(c)
prev = c
return tuple(c for c in out if c != self.blank)
def count_alignments(self, n_steps: int) -> int:
"""Exact number of length-``n_steps`` alignments that collapse to ``targets``."""
if n_steps < 1:
raise ValueError(f"n_steps must be >= 1, got {n_steps}")
m = 2 * self.n_labels + 1
if n_steps < self.n_labels: # too short to emit every label
return 0
counts = [0] * m
counts[0] = 1
if m > 1:
counts[1] = 1
for _ in range(1, n_steps):
nxt = [0] * m
for s in range(m):
nxt[s] = sum(counts[p] for p in self.incoming(s))
counts = nxt
total = counts[m - 1]
if m >= 2:
total += counts[m - 2]
return int(total)ChainTrellis
omnibias.struct.ChainTrellisSource ↗class ChainTrellisDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
A linear-chain trellis: emissions (T, S), transitions (S, S), start (S,).
The score of a state path (s_0, ..., s_{T-1}) is
\mathrm{start}[s_0] + \sum_{t=0}^{T-1} E[t, s_t]
+ \sum_{t=1}^{T-1} A[s_{t-1}, s_t].Every one of the S ** T state sequences is a valid path (the transitions are
finite scores, not a hard adjacency mask).
Parameters
| Name | Type & default | Contract |
|---|---|---|
emissionsdataclass field | FloatArrayRequired | See the operation contract and implementation below. |
transitionsdataclass field | FloatArrayRequired | See the operation contract and implementation below. |
startdataclass field | FloatArrayDefault: field(default=None) | See the operation contract and implementation below. |
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-viterbi]" -qRegression example · log num paths is overflow free
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_log_num_paths_is_overflow_free() -> None:
# 10 ** 500 paths: exact integer count is a 501-digit bignum; log stays a finite float.
big = ChainTrellis(np.zeros((500, 10)), np.zeros((10, 10)))
log_n = log_num_paths(big)
assert math.isfinite(log_n)
assert abs(log_n - 500 * math.log(10)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_core_harden.py -k test_log_num_paths_is_overflow_free -qFields & methods
emissionsfield
emissions: FloatArrayDeclared FloatArray field on ChainTrellis. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗transitionsfield
transitions: FloatArrayDeclared FloatArray field on ChainTrellis. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗startfield
start: FloatArray = field(default=None)Declared FloatArray field on ChainTrellis. Default expression: field(default=None).
__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
emissions.ndim != 2, raisesValueError(f'emissions must be (T, S), got shape {emissions.shape}'). - When
t < 1 or s < 1, raisesValueError(f'emissions must have T >= 1 and S >= 1, got {emissions.shape}'). - When
transitions.shape != (s, s), raisesValueError(f'transitions must be (S, S) = ({s}, {s}), got {transitions.shape}'). - When
start.shape != (s,), raisesValueError(f'start must be (S,) = ({s},), got {start.shape}').
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-viterbi]" -qMethod implementation
def __post_init__(self) -> None:
emissions = np.asarray(self.emissions, dtype=float)
transitions = np.asarray(self.transitions, dtype=float)
if emissions.ndim != 2:
raise ValueError(f"emissions must be (T, S), got shape {emissions.shape}")
t, s = emissions.shape
if t < 1 or s < 1:
raise ValueError(f"emissions must have T >= 1 and S >= 1, got {emissions.shape}")
if transitions.shape != (s, s):
raise ValueError(
f"transitions must be (S, S) = ({s}, {s}), got {transitions.shape}"
)
start = np.zeros(s) if self.start is None else np.asarray(self.start, dtype=float)
if start.shape != (s,):
raise ValueError(f"start must be (S,) = ({s},), got {start.shape}")
object.__setattr__(self, "emissions", emissions)
object.__setattr__(self, "transitions", transitions)
object.__setattr__(self, "start", start)n_stepsproperty
n_steps(self) -> intNumber of time steps T.
Returns: int
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-viterbi]" -qMethod implementation
def n_steps(self) -> int:
"""Number of time steps ``T``."""
return int(self.emissions.shape[0])n_statesproperty
n_states(self) -> intNumber of states S.
Returns: int
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-viterbi]" -qMethod implementation
def n_states(self) -> int:
"""Number of states ``S``."""
return int(self.emissions.shape[1])path_scoremethod
path_score(self, states: object) -> floatAdditive score of the state path states (length T).
Parameters
| Name | Type & default | Contract |
|---|---|---|
statespositional-or-keyword | objectRequired | See the operation contract and implementation below. |
Returns: float
Validation & failure cases
- When
seq.shape[0] != self.n_steps, raisesValueError(f'path must have length T = {self.n_steps}, got {seq.shape[0]}').
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-viterbi]" -qMethod implementation
def path_score(self, states: object) -> float:
"""Additive score of the state path ``states`` (length ``T``)."""
seq = np.asarray(states, dtype=int).reshape(-1)
if seq.shape[0] != self.n_steps:
raise ValueError(f"path must have length T = {self.n_steps}, got {seq.shape[0]}")
score = float(self.start[seq[0]]) + float(self.emissions[0, seq[0]])
for t in range(1, self.n_steps):
score += float(self.transitions[seq[t - 1], seq[t]])
score += float(self.emissions[t, seq[t]])
return scoreenumerate_pathsmethod
enumerate_paths(self) -> Iterator[tuple[int, ...]]Yield every state path (all S ** T of them); brute-force only, tiny T, S.
Returns: Iterator[tuple[int, ...]]
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-viterbi]" -qMethod implementation
def enumerate_paths(self) -> Iterator[tuple[int, ...]]:
"""Yield every state path (all ``S ** T`` of them); brute-force only, tiny ``T, S``."""
s, t = self.n_states, self.n_steps
for idx in range(s**t):
path, rem = [], idx
for _ in range(t):
path.append(rem % s)
rem //= s
yield tuple(path)count_pathsmethod
count_paths(self) -> intExact number of complete paths, S ** T.
Returns: int
Executed regression · logspace path count matches exact
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_logspace_path_count_matches_exact(problem: str, seed: int) -> None:
rec = probe_path_count(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_logspace_path_count_matches_exact[0-viterbi]" -qMethod implementation
def count_paths(self) -> int:
"""Exact number of complete paths, ``S ** T``."""
return int(self.n_states**self.n_steps)Read the implementation
class ChainTrellis:
r"""A linear-chain trellis: emissions ``(T, S)``, transitions ``(S, S)``, start ``(S,)``.
The score of a state path ``(s_0, ..., s_{T-1})`` is
.. math::
\mathrm{start}[s_0] + \sum_{t=0}^{T-1} E[t, s_t]
+ \sum_{t=1}^{T-1} A[s_{t-1}, s_t].
Every one of the ``S ** T`` state sequences is a valid path (the transitions are
finite scores, not a hard adjacency mask).
"""
emissions: FloatArray
transitions: FloatArray
start: FloatArray = field(default=None) # type: ignore[arg-type]
def __post_init__(self) -> None:
emissions = np.asarray(self.emissions, dtype=float)
transitions = np.asarray(self.transitions, dtype=float)
if emissions.ndim != 2:
raise ValueError(f"emissions must be (T, S), got shape {emissions.shape}")
t, s = emissions.shape
if t < 1 or s < 1:
raise ValueError(f"emissions must have T >= 1 and S >= 1, got {emissions.shape}")
if transitions.shape != (s, s):
raise ValueError(
f"transitions must be (S, S) = ({s}, {s}), got {transitions.shape}"
)
start = np.zeros(s) if self.start is None else np.asarray(self.start, dtype=float)
if start.shape != (s,):
raise ValueError(f"start must be (S,) = ({s},), got {start.shape}")
object.__setattr__(self, "emissions", emissions)
object.__setattr__(self, "transitions", transitions)
object.__setattr__(self, "start", start)
@property
def n_steps(self) -> int:
"""Number of time steps ``T``."""
return int(self.emissions.shape[0])
@property
def n_states(self) -> int:
"""Number of states ``S``."""
return int(self.emissions.shape[1])
def path_score(self, states: object) -> float:
"""Additive score of the state path ``states`` (length ``T``)."""
seq = np.asarray(states, dtype=int).reshape(-1)
if seq.shape[0] != self.n_steps:
raise ValueError(f"path must have length T = {self.n_steps}, got {seq.shape[0]}")
score = float(self.start[seq[0]]) + float(self.emissions[0, seq[0]])
for t in range(1, self.n_steps):
score += float(self.transitions[seq[t - 1], seq[t]])
score += float(self.emissions[t, seq[t]])
return score
def enumerate_paths(self) -> Iterator[tuple[int, ...]]:
"""Yield every state path (all ``S ** T`` of them); brute-force only, tiny ``T, S``."""
s, t = self.n_states, self.n_steps
for idx in range(s**t):
path, rem = [], idx
for _ in range(t):
path.append(rem % s)
rem //= s
yield tuple(path)
def count_paths(self) -> int:
"""Exact number of complete paths, ``S ** T``."""
return int(self.n_states**self.n_steps)DAG
omnibias.struct.DAGSource ↗class DAGDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
A weighted DAG for shortest / longest path, nodes in topological order.
edges maps (u, v) -> weight with u < v (topological order). Paths run
from source (default 0) to sink (default num_nodes - 1).
Parameters
| Name | Type & default | Contract |
|---|---|---|
num_nodesdataclass field | intRequired | See the operation contract and implementation below. |
edgesdataclass field | dict[tuple[int, int], float]Required | See the operation contract and implementation below. |
sourcedataclass field | intDefault: 0 | See the operation contract and implementation below. |
sinkdataclass field | intDefault: field(default=None) | See the operation contract and implementation below. |
Executed regression · alignment hard equals brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_alignment_hard_equals_brute(kind: str, seed: int) -> None:
assert probe_align_oracle(kind, seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_alignment_hard_equals_brute[0-affine]" -qRegression example · dag large ball not certified
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_dag_large_ball_not_certified() -> None:
cert = certify_decoding_dag(_DIAMOND_EDGES, _DIAMOND, eps=5.0)
assert not cert.certifiedpython -m pytest packages/omnibias-struct/tests/test_decode.py -k test_dag_large_ball_not_certified -qFields & methods
num_nodesfield
num_nodes: intDeclared int field on DAG. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗edgesfield
edges: dict[tuple[int, int], float]Declared dict[tuple[int, int], float] field on DAG. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗sinkfield
sink: int = field(default=None)Declared int field on DAG. Default expression: field(default=None).
__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
self.num_nodes < 1, raisesValueError(f'num_nodes must be >= 1, got {self.num_nodes}'). - When
not 0 <= u < self.num_nodes or not 0 <= v < self.num_nodes, raisesValueError(f'edge ({u}, {v}) out of range [0, {self.num_nodes})'). - When
u >= v, raisesValueError(f'edge ({u}, {v}) violates topological order (require u < v); relabel nodes so every edge points to a higher index').
Executed regression · alignment hard equals brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_alignment_hard_equals_brute(kind: str, seed: int) -> None:
assert probe_align_oracle(kind, seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_alignment_hard_equals_brute[0-affine]" -qMethod implementation
def __post_init__(self) -> None:
if self.num_nodes < 1:
raise ValueError(f"num_nodes must be >= 1, got {self.num_nodes}")
edges = {(int(u), int(v)): float(w) for (u, v), w in self.edges.items()}
for u, v in edges:
if not 0 <= u < self.num_nodes or not 0 <= v < self.num_nodes:
raise ValueError(f"edge ({u}, {v}) out of range [0, {self.num_nodes})")
if u >= v:
raise ValueError(
f"edge ({u}, {v}) violates topological order (require u < v); "
"relabel nodes so every edge points to a higher index"
)
sink = self.num_nodes - 1 if self.sink is None else int(self.sink)
object.__setattr__(self, "edges", edges)
object.__setattr__(self, "sink", sink)incomingmethod
incoming(self, v: int) -> list[int]Sorted predecessors u with an edge u -> v.
Parameters
| Name | Type & default | Contract |
|---|---|---|
vpositional-or-keyword | intRequired | See the operation contract and implementation below. |
Returns: list[int]
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-shortest_path]" -qMethod implementation
def incoming(self, v: int) -> list[int]:
"""Sorted predecessors ``u`` with an edge ``u -> v``."""
return sorted(u for (u, tgt) in self.edges if tgt == v)weight_matrixmethod
weight_matrix(self) -> FloatArrayDense (num_nodes, num_nodes) weights, +inf where no edge exists.
Returns: FloatArray
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-shortest_path]" -qMethod implementation
def weight_matrix(self) -> FloatArray:
"""Dense ``(num_nodes, num_nodes)`` weights, ``+inf`` where no edge exists."""
w = np.full((self.num_nodes, self.num_nodes), np.inf)
for (u, v), weight in self.edges.items():
w[u, v] = weight
return wenumerate_pathsmethod
enumerate_paths(self) -> Iterator[tuple[int, ...]]Yield every source -> sink path as a tuple of node indices.
Returns: Iterator[tuple[int, ...]]
Executed regression · alignment hard equals brute
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_alignment_hard_equals_brute(kind: str, seed: int) -> None:
assert probe_align_oracle(kind, seed).okpython -m pytest "packages/omnibias-struct/tests/test_refinement_families.py::test_alignment_hard_equals_brute[0-affine]" -qMethod implementation
def enumerate_paths(self) -> Iterator[tuple[int, ...]]:
"""Yield every ``source -> sink`` path as a tuple of node indices."""
succ: dict[int, list[int]] = {}
for u, v in self.edges:
succ.setdefault(u, []).append(v)
for vs in succ.values():
vs.sort()
def dfs(node: int, acc: tuple[int, ...]) -> Iterator[tuple[int, ...]]:
if node == self.sink:
yield acc
return
for nxt in succ.get(node, []):
yield from dfs(nxt, acc + (nxt,))
yield from dfs(self.source, (self.source,))path_costmethod
path_cost(self, nodes: object) -> floatTotal edge weight of a source -> sink path given as node indices.
Parameters
| Name | Type & default | Contract |
|---|---|---|
nodespositional-or-keyword | objectRequired | See the operation contract and implementation below. |
Returns: float
Executed regression · oracle agreement
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_oracle_agreement(problem: str, seed: int) -> None:
rec = probe_oracle_agreement(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_oracle_agreement[0-shortest_path]" -qMethod implementation
def path_cost(self, nodes: object) -> float:
"""Total edge weight of a ``source -> sink`` path given as node indices."""
seq = [int(x) for x in np.asarray(nodes, dtype=int).reshape(-1)]
return float(sum(self.edges[(seq[i], seq[i + 1])] for i in range(len(seq) - 1)))count_pathsmethod
count_paths(self) -> intExact number of source -> sink paths (topological-order DP).
Returns: int
Executed regression · logspace path count matches exact
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_logspace_path_count_matches_exact(problem: str, seed: int) -> None:
rec = probe_path_count(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_logspace_path_count_matches_exact[0-shortest_path]" -qMethod implementation
def count_paths(self) -> int:
"""Exact number of ``source -> sink`` paths (topological-order DP)."""
succ: dict[int, list[int]] = {}
for u, v in self.edges:
succ.setdefault(u, []).append(v)
counts = [0] * self.num_nodes
counts[self.sink] = 1
for node in range(self.num_nodes - 1, -1, -1):
if node == self.sink:
continue
counts[node] = sum(counts[v] for v in succ.get(node, []))
return int(counts[self.source])Read the implementation
class DAG:
r"""A weighted DAG for shortest / longest path, nodes in topological order.
``edges`` maps ``(u, v) -> weight`` with ``u < v`` (topological order). Paths run
from :attr:`source` (default ``0``) to :attr:`sink` (default ``num_nodes - 1``).
"""
num_nodes: int
edges: dict[tuple[int, int], float]
source: int = 0
sink: int = field(default=None) # type: ignore[assignment]
def __post_init__(self) -> None:
if self.num_nodes < 1:
raise ValueError(f"num_nodes must be >= 1, got {self.num_nodes}")
edges = {(int(u), int(v)): float(w) for (u, v), w in self.edges.items()}
for u, v in edges:
if not 0 <= u < self.num_nodes or not 0 <= v < self.num_nodes:
raise ValueError(f"edge ({u}, {v}) out of range [0, {self.num_nodes})")
if u >= v:
raise ValueError(
f"edge ({u}, {v}) violates topological order (require u < v); "
"relabel nodes so every edge points to a higher index"
)
sink = self.num_nodes - 1 if self.sink is None else int(self.sink)
object.__setattr__(self, "edges", edges)
object.__setattr__(self, "sink", sink)
def incoming(self, v: int) -> list[int]:
"""Sorted predecessors ``u`` with an edge ``u -> v``."""
return sorted(u for (u, tgt) in self.edges if tgt == v)
def weight_matrix(self) -> FloatArray:
"""Dense ``(num_nodes, num_nodes)`` weights, ``+inf`` where no edge exists."""
w = np.full((self.num_nodes, self.num_nodes), np.inf)
for (u, v), weight in self.edges.items():
w[u, v] = weight
return w
def enumerate_paths(self) -> Iterator[tuple[int, ...]]:
"""Yield every ``source -> sink`` path as a tuple of node indices."""
succ: dict[int, list[int]] = {}
for u, v in self.edges:
succ.setdefault(u, []).append(v)
for vs in succ.values():
vs.sort()
def dfs(node: int, acc: tuple[int, ...]) -> Iterator[tuple[int, ...]]:
if node == self.sink:
yield acc
return
for nxt in succ.get(node, []):
yield from dfs(nxt, acc + (nxt,))
yield from dfs(self.source, (self.source,))
def path_cost(self, nodes: object) -> float:
"""Total edge weight of a ``source -> sink`` path given as node indices."""
seq = [int(x) for x in np.asarray(nodes, dtype=int).reshape(-1)]
return float(sum(self.edges[(seq[i], seq[i + 1])] for i in range(len(seq) - 1)))
def count_paths(self) -> int:
"""Exact number of ``source -> sink`` paths (topological-order DP)."""
succ: dict[int, list[int]] = {}
for u, v in self.edges:
succ.setdefault(u, []).append(v)
counts = [0] * self.num_nodes
counts[self.sink] = 1
for node in range(self.num_nodes - 1, -1, -1):
if node == self.sink:
continue
counts[node] = sum(counts[v] for v in succ.get(node, []))
return int(counts[self.source])count_paths
omnibias.struct.count_pathsSource ↗count_paths(problem: ChainTrellis | DAG | CTCLattice, n_steps: int | None=None) -> intExact number of complete paths / alignments -- the N in log(N) / beta.
For a CTCLattice the alignment length n_steps (= T) is required.
Parameters
| Name | Type & default | Contract |
|---|---|---|
problempositional-or-keyword | ChainTrellis | DAG | CTCLatticeRequired | See the operation contract and implementation below. |
n_stepspositional-or-keyword | int | NoneDefault: None | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
n_steps is None, raisesValueError('count_paths on a CTCLattice requires n_steps (= T)').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · logspace path count matches exact
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_logspace_path_count_matches_exact(problem: str, seed: int) -> None:
rec = probe_path_count(problem, seed)
assert rec.ok, recpython -m pytest "packages/omnibias-struct/tests/test_refinement_probes.py::test_logspace_path_count_matches_exact[0-ctc]" -qRegression example · stepwise bound equals global for a chain
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_stepwise_bound_equals_global_for_a_chain() -> None:
trellis = random_chain(0)
beta = 4.0
assert abs(stepwise_gap_bound(trellis, beta) - logsumexp_gap_bound(count_paths(trellis), beta)) < 1e-9python -m pytest packages/omnibias-struct/tests/test_core_harden.py -k test_stepwise_bound_equals_global_for_a_chain -qRead the implementation
def count_paths(problem: ChainTrellis | DAG | CTCLattice, n_steps: int | None = None) -> int:
r"""Exact number of complete paths / alignments -- the ``N`` in ``log(N) / beta``.
For a :class:`CTCLattice` the alignment length ``n_steps`` (``= T``) is required.
"""
if isinstance(problem, CTCLattice):
if n_steps is None:
raise ValueError("count_paths on a CTCLattice requires n_steps (= T)")
return problem.count_alignments(n_steps)
return problem.count_paths()TropicalGapCertificate
omnibias.struct.TropicalGapCertificateSource ↗class TropicalGapCertificateDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
betadataclass field | floatRequired | See the operation contract and implementation below. |
bounddataclass field | floatRequired | See the operation contract and implementation below. |
measureddataclass field | floatRequired | See the operation contract and implementation below. |
Executed regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qFields & methods
betafield
beta: floatDeclared float field on TropicalGapCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗boundfield
bound: floatDeclared float field on TropicalGapCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗measuredfield
measured: floatDeclared float field on TropicalGapCertificate. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗is_soundproperty
is_sound(self) -> boolSee the class contract above and the exact method implementation below.
Returns: bool
Executed regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qMethod implementation
def is_sound(self) -> bool:
return self.bound + 1e-12 >= self.measuredRead the implementation
class TropicalGapCertificate:
beta: float
bound: float
measured: float
@property
def is_sound(self) -> bool:
return self.bound + 1e-12 >= self.measuredTropicalLinear
omnibias.struct.TropicalLinearSource ↗class TropicalLinearDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
Tropical polynomial max_i (a_i + m_i . x).
Terminology: beta -> inf hardens softmax into argmax (temperature /
feasibility collapse). Do not conflate with founding bias collapse
(delta -> 0).
Parameters
| Name | Type & default | Contract |
|---|---|---|
coeffsdataclass field | FloatArrayRequired | See the operation contract and implementation below. |
exponentsdataclass field | FloatArrayRequired | See the operation contract and implementation below. |
Executed regression · refuse large
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_refuse_large() -> None:
with pytest.raises(ValueError, match="refuse"):
TropicalLinear(np.zeros(12), np.zeros((12, 2)))python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_refuse_large" -qRegression example · g2 subdivision agrees with arrangement sampler
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g2_subdivision_agrees_with_arrangement_sampler() -> None:
poly = TropicalLinear(
np.array([0.0, 0.2, -0.1, 0.4]),
np.array([[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0], [0.2, 0.8]]),
)
cells = dual_subdivision(poly, n_samples=8000, seed=0)
assert len(cells) >= 2
# Difference arrangement of the tropical terms.
n = poly.n
normals = []
offsets = []
for i in range(n):
for j in range(i + 1, n):
normals.append(poly.exponents[i] - poly.exponents[j])
offsets.append(poly.coeffs[j] - poly.coeffs[i])
arr = Arrangement(np.asarray(normals), np.asarray(offsets))
arr_cells = enumerate_cells_vertices(arr)
# Each tropical full-dim cell sits inside some arrangement cell; counts are comparable.
assert len(cells) <= len(arr_cells)
verts = newton_polytope(poly)
assert len(verts) >= 3python -m pytest packages/omnibias-struct/tests/test_tropical.py -k test_g2_subdivision_agrees_with_arrangement_sampler -qFields & methods
coeffsfield
coeffs: FloatArrayDeclared FloatArray field on TropicalLinear. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗exponentsfield
exponents: FloatArrayDeclared FloatArray field on TropicalLinear. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
m.ndim != 2 or m.shape[0] != a.shape[0], raisesValueError('exponents must have shape (n, D)').
Executed regression · refuse large
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_refuse_large() -> None:
with pytest.raises(ValueError, match="refuse"):
TropicalLinear(np.zeros(12), np.zeros((12, 2)))python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_refuse_large" -qMethod implementation
def __post_init__(self) -> None:
a = np.asarray(self.coeffs, dtype=np.float64).reshape(-1)
m = np.asarray(self.exponents, dtype=np.float64)
if m.ndim != 2 or m.shape[0] != a.shape[0]:
raise ValueError("exponents must have shape (n, D)")
_check_size(int(a.shape[0]), int(m.shape[1]))
object.__setattr__(self, "coeffs", a)
object.__setattr__(self, "exponents", m)nproperty
n(self) -> intSee the class contract above and the exact method implementation below.
Returns: int
Executed regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qMethod implementation
def n(self) -> int:
return int(self.coeffs.shape[0])dimproperty
dim(self) -> intSee the class contract above and the exact method implementation below.
Returns: int
Executed regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qMethod implementation
def dim(self) -> int:
return int(self.exponents.shape[1])Read the implementation
class TropicalLinear:
"""Tropical polynomial ``max_i (a_i + m_i . x)``.
Terminology: ``beta -> inf`` hardens softmax into argmax (temperature /
feasibility collapse). Do not conflate with founding bias collapse
(``delta -> 0``).
"""
coeffs: FloatArray
exponents: FloatArray
def __post_init__(self) -> None:
a = np.asarray(self.coeffs, dtype=np.float64).reshape(-1)
m = np.asarray(self.exponents, dtype=np.float64)
if m.ndim != 2 or m.shape[0] != a.shape[0]:
raise ValueError("exponents must have shape (n, D)")
_check_size(int(a.shape[0]), int(m.shape[1]))
object.__setattr__(self, "coeffs", a)
object.__setattr__(self, "exponents", m)
@property
def n(self) -> int:
return int(self.coeffs.shape[0])
@property
def dim(self) -> int:
return int(self.exponents.shape[1])TropicalPathResult
omnibias.struct.TropicalPathResultSource ↗class TropicalPathResultDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
Decoded tropical objective after a temperature homotopy.
Parameters
| Name | Type & default | Contract |
|---|---|---|
xdataclass field | FloatArrayRequired | See the operation contract and implementation below. |
decodeddataclass field | floatRequired | See the operation contract and implementation below. |
winnerdataclass field | intRequired | See the operation contract and implementation below. |
n_evalsdataclass field | intRequired | See the operation contract and implementation below. |
gapdataclass field | TropicalGapCertificateRequired | See the operation contract and implementation below. |
methoddataclass field | strRequired | See the operation contract and implementation below. |
Fields & methods
xfield
x: FloatArrayDeclared FloatArray field on TropicalPathResult. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗decodedfield
decoded: floatDeclared float field on TropicalPathResult. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗winnerfield
winner: intDeclared int field on TropicalPathResult. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗n_evalsfield
n_evals: intDeclared int field on TropicalPathResult. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗gapfield
gap: TropicalGapCertificateDeclared TropicalGapCertificate field on TropicalPathResult. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗methodfield
method: strDeclared str field on TropicalPathResult. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.
View source ↗Read the implementation
class TropicalPathResult:
"""Decoded tropical objective after a temperature homotopy."""
x: FloatArray
decoded: float
winner: int
n_evals: int
gap: TropicalGapCertificate
method: strTropicalSchedule
omnibias.struct.TropicalScheduleSource ↗class TropicalScheduleDataclass constructor fields; inherited fields, if any, are declared by the base class. A field(...) expression describes a default factory or field options, not a literal argument default.
Temperature homotopy; duck-compatible with AnnealSchedule.
omnibias-struct cannot import omnibias-discrete (discrete already
depends on struct). Pass an AnnealSchedule anyway: from_anneal
and as_tropical_schedule read the same field names and
betas().
Parameters
| Name | Type & default | Contract |
|---|---|---|
beta0dataclass field | floatDefault: 0.5 | See the operation contract and implementation below. |
beta_growthdataclass field | floatDefault: 1.6 | See the operation contract and implementation below. |
stagesdataclass field | intDefault: 8 | See the operation contract and implementation below. |
stepsdataclass field | intDefault: 24 | See the operation contract and implementation below. |
step_safetydataclass field | floatDefault: 0.9 | See the operation contract and implementation below. |
Executed regression · discrete schedule drives tropical operators
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_discrete_schedule_drives_tropical_operators() -> None:
schedule = AnnealSchedule.fast()
tropical = as_tropical_schedule(schedule)
assert tropical.betas() == schedule.betas()python -m pytest "packages/omnibias-discrete/tests/test_tropical_integration.py::test_discrete_schedule_drives_tropical_operators" -qRegression example · g4 path follow beats anneal evals
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest packages/omnibias-struct/tests/test_tropical.py -k test_g4_path_follow_beats_anneal_evals -qFields & methods
beta0field
beta0: float = 0.5Declared float field on TropicalSchedule. Default expression: 0.5.
beta_growthfield
beta_growth: float = 1.6Declared float field on TropicalSchedule. Default expression: 1.6.
stagesfield
stages: int = 8Declared int field on TropicalSchedule. Default expression: 8.
stepsfield
steps: int = 24Declared int field on TropicalSchedule. Default expression: 24.
step_safetyfield
step_safety: float = 0.9Declared float field on TropicalSchedule. Default expression: 0.9.
__post_init__method
__post_init__(self) -> NoneSee the class contract above and the exact method implementation below.
Returns: None
Validation & failure cases
- When
self.beta0 <= 0.0, raisesValueError('beta0 must be > 0'). - When
self.beta_growth < 1.0, raisesValueError('beta_growth must be >= 1'). - When
self.stages < 1 or self.steps < 1, raisesValueError('stages and steps must be >= 1'). - When
not 0.0 < self.step_safety <= 1.0, raisesValueError('step_safety must be in (0, 1]').
Executed regression · discrete schedule drives tropical operators
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_discrete_schedule_drives_tropical_operators() -> None:
schedule = AnnealSchedule.fast()
tropical = as_tropical_schedule(schedule)
assert tropical.betas() == schedule.betas()python -m pytest "packages/omnibias-discrete/tests/test_tropical_integration.py::test_discrete_schedule_drives_tropical_operators" -qMethod implementation
def __post_init__(self) -> None:
if self.beta0 <= 0.0:
raise ValueError("beta0 must be > 0")
if self.beta_growth < 1.0:
raise ValueError("beta_growth must be >= 1")
if self.stages < 1 or self.steps < 1:
raise ValueError("stages and steps must be >= 1")
if not 0.0 < self.step_safety <= 1.0:
raise ValueError("step_safety must be in (0, 1]")betasmethod
betas(self) -> list[float]See the class contract above and the exact method implementation below.
Returns: list[float]
Executed regression · discrete schedule drives tropical operators
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_discrete_schedule_drives_tropical_operators() -> None:
schedule = AnnealSchedule.fast()
tropical = as_tropical_schedule(schedule)
assert tropical.betas() == schedule.betas()python -m pytest "packages/omnibias-discrete/tests/test_tropical_integration.py::test_discrete_schedule_drives_tropical_operators" -qMethod implementation
def betas(self) -> list[float]:
out, beta = [], self.beta0
for _ in range(self.stages):
out.append(beta)
beta *= self.beta_growth
return outfrom_annealmethod
from_anneal(cls, schedule: Any) -> TropicalScheduleWire AnnealSchedule (or any duck-typed schedule) into this driver.
Parameters
| Name | Type & default | Contract |
|---|---|---|
schedulepositional-or-keyword | AnyRequired | See the operation contract and implementation below. |
Returns: TropicalSchedule
Executed regression · discrete schedule drives tropical operators
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_discrete_schedule_drives_tropical_operators() -> None:
schedule = AnnealSchedule.fast()
tropical = as_tropical_schedule(schedule)
assert tropical.betas() == schedule.betas()python -m pytest "packages/omnibias-discrete/tests/test_tropical_integration.py::test_discrete_schedule_drives_tropical_operators" -qMethod implementation
def from_anneal(cls, schedule: Any) -> TropicalSchedule:
"""Wire ``AnnealSchedule`` (or any duck-typed schedule) into this driver."""
return cls(
beta0=float(schedule.beta0),
beta_growth=float(schedule.beta_growth),
stages=int(schedule.stages),
steps=int(schedule.steps),
step_safety=float(schedule.step_safety),
)Read the implementation
class TropicalSchedule:
"""Temperature homotopy; duck-compatible with ``AnnealSchedule``.
``omnibias-struct`` cannot import ``omnibias-discrete`` (discrete already
depends on struct). Pass an ``AnnealSchedule`` anyway: ``from_anneal``
and :func:`as_tropical_schedule` read the same field names and
``betas()``.
"""
beta0: float = 0.5
beta_growth: float = 1.6
stages: int = 8
steps: int = 24
step_safety: float = 0.9
def __post_init__(self) -> None:
if self.beta0 <= 0.0:
raise ValueError("beta0 must be > 0")
if self.beta_growth < 1.0:
raise ValueError("beta_growth must be >= 1")
if self.stages < 1 or self.steps < 1:
raise ValueError("stages and steps must be >= 1")
if not 0.0 < self.step_safety <= 1.0:
raise ValueError("step_safety must be in (0, 1]")
def betas(self) -> list[float]:
out, beta = [], self.beta0
for _ in range(self.stages):
out.append(beta)
beta *= self.beta_growth
return out
@classmethod
def from_anneal(cls, schedule: Any) -> TropicalSchedule:
"""Wire ``AnnealSchedule`` (or any duck-typed schedule) into this driver."""
return cls(
beta0=float(schedule.beta0),
beta_growth=float(schedule.beta_growth),
stages=int(schedule.stages),
steps=int(schedule.steps),
step_safety=float(schedule.step_safety),
)as_tropical_schedule
omnibias.struct.as_tropical_scheduleSource ↗as_tropical_schedule(schedule: Any | None=None) -> TropicalScheduleAccept TropicalSchedule, AnnealSchedule, or None (defaults).
Parameters
| Name | Type & default | Contract |
|---|---|---|
schedulepositional-or-keyword | Any | NoneDefault: None | See the operation contract and implementation below. |
TropicalScheduleExecuted regression · discrete schedule drives tropical operators
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_discrete_schedule_drives_tropical_operators() -> None:
schedule = AnnealSchedule.fast()
tropical = as_tropical_schedule(schedule)
assert tropical.betas() == schedule.betas()python -m pytest "packages/omnibias-discrete/tests/test_tropical_integration.py::test_discrete_schedule_drives_tropical_operators" -qRegression example · anneal schedule duck type
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_anneal_schedule_duck_type() -> None:
class Schedule:
beta0 = 1.0
beta_growth = 2.0
stages = 4
steps = 6
step_safety = 0.9
wired = as_tropical_schedule(Schedule())
assert wired.betas() == [1.0, 2.0, 4.0, 8.0]python -m pytest packages/omnibias-struct/tests/test_tropical.py -k test_anneal_schedule_duck_type -qRead the implementation
def as_tropical_schedule(schedule: Any | None = None) -> TropicalSchedule:
"""Accept ``TropicalSchedule``, ``AnnealSchedule``, or ``None`` (defaults)."""
if schedule is None:
return TropicalSchedule()
if isinstance(schedule, TropicalSchedule):
return schedule
return TropicalSchedule.from_anneal(schedule)certify_tropical_gap
omnibias.struct.certify_tropical_gapSource ↗certify_tropical_gap(poly: TropicalLinear, x: FloatArray, *, beta: float) -> TropicalGapCertificateSound log(n)/beta bound on relaxed - tropical.
Parameters
| Name | Type & default | Contract |
|---|---|---|
polypositional-or-keyword | TropicalLinearRequired | See the operation contract and implementation below. |
xpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betakeyword-only | floatRequired | See the operation contract and implementation below. |
TropicalGapCertificateExecuted regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qRegression example · g1 gap soundness
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g1_gap_soundness() -> None:
poly = _poly()
rng = np.random.default_rng(1)
grid = np.stack(
np.meshgrid(np.linspace(-1.5, 1.5, 21), np.linspace(-1.5, 1.5, 21), indexing="ij"),
axis=-1,
).reshape(-1, 2)
extra = rng.normal(size=(40, 2))
x = np.concatenate([grid, extra], axis=0)
for beta in (0.5, 2.0, 20.0):
cert = certify_tropical_gap(poly, x, beta=beta)
assert cert.is_sound
assert cert.bound == pytest.approx(homotopy_gap_bound(poly, beta=beta))
assert float(np.max(relaxed_value(poly, x, beta=beta) - tropical_value(poly, x))) <= cert.bound + 1e-12python -m pytest packages/omnibias-struct/tests/test_tropical.py -k test_g1_gap_soundness -qRead the implementation
def certify_tropical_gap(
poly: TropicalLinear, x: FloatArray, *, beta: float
) -> TropicalGapCertificate:
"""Sound ``log(n)/beta`` bound on ``relaxed - tropical``."""
rel = relaxed_value(poly, x, beta=beta)
hard = tropical_value(poly, x)
measured = float(np.max(rel - hard))
bound = homotopy_gap_bound(poly, beta=beta)
return TropicalGapCertificate(beta=beta, bound=bound, measured=measured)dual_subdivision
omnibias.struct.dual_subdivisionSource ↗dual_subdivision(poly: TropicalLinear, *, n_samples: int=4000, seed: int=0) -> tuple[tuple[int, ...], ...]Full-dimensional cells (unique argmax index) found by sampling.
A lower bound on the dual subdivision, never a completeness claim.
Parameters
| Name | Type & default | Contract |
|---|---|---|
polypositional-or-keyword | TropicalLinearRequired | See the operation contract and implementation below. |
n_sampleskeyword-only | intDefault: 4000 | See the operation contract and implementation below. |
seedkeyword-only | intDefault: 0 | See the operation contract and implementation below. |
tuple[tuple[int, ...], ...]Executed regression · g2 subdivision agrees with arrangement sampler
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g2_subdivision_agrees_with_arrangement_sampler() -> None:
poly = TropicalLinear(
np.array([0.0, 0.2, -0.1, 0.4]),
np.array([[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0], [0.2, 0.8]]),
)
cells = dual_subdivision(poly, n_samples=8000, seed=0)
assert len(cells) >= 2
# Difference arrangement of the tropical terms.
n = poly.n
normals = []
offsets = []
for i in range(n):
for j in range(i + 1, n):
normals.append(poly.exponents[i] - poly.exponents[j])
offsets.append(poly.coeffs[j] - poly.coeffs[i])
arr = Arrangement(np.asarray(normals), np.asarray(offsets))
arr_cells = enumerate_cells_vertices(arr)
# Each tropical full-dim cell sits inside some arrangement cell; counts are comparable.
assert len(cells) <= len(arr_cells)
verts = newton_polytope(poly)
assert len(verts) >= 3python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g2_subdivision_agrees_with_arrangement_sampler" -qRead the implementation
def dual_subdivision(
poly: TropicalLinear, *, n_samples: int = 4000, seed: int = 0
) -> tuple[tuple[int, ...], ...]:
"""Full-dimensional cells (unique argmax index) found by sampling.
A lower bound on the dual subdivision, never a completeness claim.
"""
rng = np.random.default_rng(seed)
x = rng.normal(size=(n_samples, poly.dim))
s = scores(poly, x)
winners = np.argmax(s, axis=-1)
top2 = np.partition(s, -2, axis=-1)[:, -2:]
unique = top2[:, 1] - top2[:, 0] > 1e-10
cells = tuple(sorted({(int(w),) for w, ok in zip(winners, unique, strict=True) if ok}))
return cellshomotopy_gap_bound
omnibias.struct.homotopy_gap_boundSource ↗homotopy_gap_bound(poly: TropicalLinear, *, beta: float) -> floatlog(n)/beta, reusing logsumexp_gap_bound.
Parameters
| Name | Type & default | Contract |
|---|---|---|
polypositional-or-keyword | TropicalLinearRequired | See the operation contract and implementation below. |
betakeyword-only | floatRequired | See the operation contract and implementation below. |
floatExecuted regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qRegression example · g1 gap soundness
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g1_gap_soundness() -> None:
poly = _poly()
rng = np.random.default_rng(1)
grid = np.stack(
np.meshgrid(np.linspace(-1.5, 1.5, 21), np.linspace(-1.5, 1.5, 21), indexing="ij"),
axis=-1,
).reshape(-1, 2)
extra = rng.normal(size=(40, 2))
x = np.concatenate([grid, extra], axis=0)
for beta in (0.5, 2.0, 20.0):
cert = certify_tropical_gap(poly, x, beta=beta)
assert cert.is_sound
assert cert.bound == pytest.approx(homotopy_gap_bound(poly, beta=beta))
assert float(np.max(relaxed_value(poly, x, beta=beta) - tropical_value(poly, x))) <= cert.bound + 1e-12python -m pytest packages/omnibias-struct/tests/test_tropical.py -k test_g1_gap_soundness -qRead the implementation
def homotopy_gap_bound(poly: TropicalLinear, *, beta: float) -> float:
"""``log(n)/beta``, reusing :func:`logsumexp_gap_bound`."""
return logsumexp_gap_bound(poly.n, beta)newton_polytope
omnibias.struct.newton_polytopeSource ↗newton_polytope(poly: TropicalLinear) -> tuple[tuple[float, ...], ...]Vertices of the convex hull of the exponent vectors.
Parameters
| Name | Type & default | Contract |
|---|---|---|
polypositional-or-keyword | TropicalLinearRequired | See the operation contract and implementation below. |
tuple[tuple[float, ...], ...]Executed regression · g2 subdivision agrees with arrangement sampler
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g2_subdivision_agrees_with_arrangement_sampler() -> None:
poly = TropicalLinear(
np.array([0.0, 0.2, -0.1, 0.4]),
np.array([[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0], [0.2, 0.8]]),
)
cells = dual_subdivision(poly, n_samples=8000, seed=0)
assert len(cells) >= 2
# Difference arrangement of the tropical terms.
n = poly.n
normals = []
offsets = []
for i in range(n):
for j in range(i + 1, n):
normals.append(poly.exponents[i] - poly.exponents[j])
offsets.append(poly.coeffs[j] - poly.coeffs[i])
arr = Arrangement(np.asarray(normals), np.asarray(offsets))
arr_cells = enumerate_cells_vertices(arr)
# Each tropical full-dim cell sits inside some arrangement cell; counts are comparable.
assert len(cells) <= len(arr_cells)
verts = newton_polytope(poly)
assert len(verts) >= 3python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g2_subdivision_agrees_with_arrangement_sampler" -qRead the implementation
def newton_polytope(poly: TropicalLinear) -> tuple[tuple[float, ...], ...]:
"""Vertices of the convex hull of the exponent vectors."""
pts = [tuple(float(v) for v in row) for row in poly.exponents]
unique = list(dict.fromkeys(pts))
if len(unique) <= 1 or poly.dim == 1:
return tuple(unique)
if poly.dim == 2:
return _convex_hull_2d(unique)
return _extreme_points(unique)path_follow
omnibias.struct.path_followSource ↗path_follow(poly: TropicalLinear, x0: FloatArray, *, box: float=2.0, schedule: Any | None=None, newton_steps: int=2, polish_steps: int=4) -> TropicalPathResultSecond-order path-follow along the same AnnealSchedule homotopy.
Each Newton step is one closed-form Hessian/grad pass plus one
accept/reject value eval. A short polish at the final beta
matches the first-order decode.
Parameters
| Name | Type & default | Contract |
|---|---|---|
polypositional-or-keyword | TropicalLinearRequired | See the operation contract and implementation below. |
x0positional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
boxkeyword-only | floatDefault: 2.0 | See the operation contract and implementation below. |
schedulekeyword-only | Any | NoneDefault: None | See the operation contract and implementation below. |
newton_stepskeyword-only | intDefault: 2 | See the operation contract and implementation below. |
polish_stepskeyword-only | intDefault: 4 | See the operation contract and implementation below. |
TropicalPathResultExplicit validation & failure cases
- When
newton_steps < 1, raisesValueError('newton_steps must be >= 1'). - When
polish_steps < 0, raisesValueError('polish_steps must be >= 0'). - When
int(x.shape[0]) != poly.dim, raisesValueError(f'x0 dim {int(x.shape[0])} != poly.dim {poly.dim}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qRead the implementation
def path_follow(
poly: TropicalLinear,
x0: FloatArray,
*,
box: float = 2.0,
schedule: Any | None = None,
newton_steps: int = 2,
polish_steps: int = 4,
) -> TropicalPathResult:
"""Second-order path-follow along the same ``AnnealSchedule`` homotopy.
Each Newton step is one closed-form Hessian/grad pass plus one
accept/reject value eval. A short polish at the final ``beta``
matches the first-order decode.
"""
if newton_steps < 1:
raise ValueError("newton_steps must be >= 1")
if polish_steps < 0:
raise ValueError("polish_steps must be >= 0")
sched = as_tropical_schedule(schedule)
x = _clip_box(np.asarray(x0, dtype=np.float64).reshape(-1), box)
if int(x.shape[0]) != poly.dim:
raise ValueError(f"x0 dim {int(x.shape[0])} != poly.dim {poly.dim}")
lip = _lipschitz(poly)
n_evals = 0
betas = sched.betas()
for beta in betas:
x, stage_evals = _newton_stage(
poly,
x,
beta,
box=box,
lip=lip,
safety=sched.step_safety,
steps=newton_steps,
)
n_evals += stage_evals
if polish_steps:
x, polish_evals = _newton_stage(
poly,
x,
betas[-1],
box=box,
lip=lip,
safety=sched.step_safety,
steps=polish_steps,
)
n_evals += polish_evals
return _decode(poly, x, beta=betas[-1], n_evals=n_evals, method="path_follow")relaxed_value
omnibias.struct.relaxed_valueSource ↗relaxed_value(poly: TropicalLinear, x: FloatArray, *, beta: float) -> FloatArray(1/beta) log sum_i exp(beta (a_i + m_i x)).
Parameters
| Name | Type & default | Contract |
|---|---|---|
polypositional-or-keyword | TropicalLinearRequired | See the operation contract and implementation below. |
xpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betakeyword-only | floatRequired | See the operation contract and implementation below. |
FloatArrayExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError('beta must be > 0 (temperature collapse axis)').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qRegression example · g1 gap soundness
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g1_gap_soundness() -> None:
poly = _poly()
rng = np.random.default_rng(1)
grid = np.stack(
np.meshgrid(np.linspace(-1.5, 1.5, 21), np.linspace(-1.5, 1.5, 21), indexing="ij"),
axis=-1,
).reshape(-1, 2)
extra = rng.normal(size=(40, 2))
x = np.concatenate([grid, extra], axis=0)
for beta in (0.5, 2.0, 20.0):
cert = certify_tropical_gap(poly, x, beta=beta)
assert cert.is_sound
assert cert.bound == pytest.approx(homotopy_gap_bound(poly, beta=beta))
assert float(np.max(relaxed_value(poly, x, beta=beta) - tropical_value(poly, x))) <= cert.bound + 1e-12python -m pytest packages/omnibias-struct/tests/test_tropical.py -k test_g1_gap_soundness -qRead the implementation
def relaxed_value(poly: TropicalLinear, x: FloatArray, *, beta: float) -> FloatArray:
"""``(1/beta) log sum_i exp(beta (a_i + m_i x))``."""
if beta <= 0.0:
raise ValueError("beta must be > 0 (temperature collapse axis)")
s = scores(poly, x)
scaled = beta * s
m = np.max(scaled, axis=-1, keepdims=True)
return (m.squeeze(-1) + np.log(np.exp(scaled - m).sum(axis=-1))) / betarelaxed_weights
omnibias.struct.relaxed_weightsSource ↗relaxed_weights(poly: TropicalLinear, x: FloatArray, *, beta: float) -> FloatArrayThe module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
polypositional-or-keyword | TropicalLinearRequired | See the operation contract and implementation below. |
xpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
betakeyword-only | floatRequired | See the operation contract and implementation below. |
FloatArrayExplicit validation & failure cases
- When
beta <= 0.0, raisesValueError('beta must be > 0 (temperature collapse axis)').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qRead the implementation
def relaxed_weights(poly: TropicalLinear, x: FloatArray, *, beta: float) -> FloatArray:
if beta <= 0.0:
raise ValueError("beta must be > 0 (temperature collapse axis)")
s = scores(poly, x)
scaled = beta * s
m = np.max(scaled, axis=-1, keepdims=True)
e = np.exp(scaled - m)
return e / e.sum(axis=-1, keepdims=True)surrounding_tropical
omnibias.struct.surrounding_tropicalSource ↗surrounding_tropical(n: int=6, dim: int=2, *, seed: int=0) -> TropicalLinearPWL family whose exponent hull contains 0 (unique unconstrained min).
Directions surround the origin so tropical_value has a unique
unconstrained minimizer; that is the G4 comparison family.
Parameters
| Name | Type & default | Contract |
|---|---|---|
npositional-or-keyword | intDefault: 6 | See the operation contract and implementation below. |
dimpositional-or-keyword | intDefault: 2 | See the operation contract and implementation below. |
seedkeyword-only | intDefault: 0 | See the operation contract and implementation below. |
TropicalLinearExplicit validation & failure cases
- When
n < dim + 1, raisesValueError('need n >= dim+1 so conv(exponents) can contain 0').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qRegression example · g4 parity
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_parity() -> None:
pytest.importorskip("jax")
import jax
import jax.numpy as jnp
import torch
from omnibias.struct.jax.tropical import relaxed_value as rv_jax
from omnibias.struct.torch.tropical import relaxed_value as rv_torch
jax.config.update("jax_enable_x64", True)
poly = _poly()
x = np.array([[0.1, -0.2], [0.3, 0.4]])
t = rv_torch(poly, torch.as_tensor(x, dtype=torch.float64), beta=2.0)
j = rv_jax(poly, jnp.asarray(x, dtype=jnp.float64), beta=2.0)
np.testing.assert_allclose(t.detach().cpu().numpy(), np.asarray(j), rtol=0.0, atol=1e-12)python -m pytest packages/omnibias-struct/tests/test_tropical.py -k test_g4_parity -qRead the implementation
def surrounding_tropical(n: int = 6, dim: int = 2, *, seed: int = 0) -> TropicalLinear:
"""PWL family whose exponent hull contains 0 (unique unconstrained min).
Directions surround the origin so ``tropical_value`` has a unique
unconstrained minimizer; that is the G4 comparison family.
"""
if n < dim + 1:
raise ValueError("need n >= dim+1 so conv(exponents) can contain 0")
rng = np.random.default_rng(seed)
if dim == 1:
signs = np.ones((n, 1), dtype=np.float64)
signs[1::2, 0] = -1.0
exponents = signs
elif dim == 2:
jitter = rng.uniform(-0.1, 0.1, size=n)
angles = np.linspace(0.0, 2.0 * np.pi, n, endpoint=False) + jitter
exponents = np.stack((np.cos(angles), np.sin(angles)), axis=1)
else:
raw = rng.normal(size=(n, dim))
norms = np.linalg.norm(raw, axis=1, keepdims=True)
exponents = raw / np.maximum(norms, 1e-12)
coeffs = rng.normal(size=n) * 0.25
return TropicalLinear(coeffs, exponents)tropical_anneal_descent
omnibias.struct.tropical_anneal_descentSource ↗tropical_anneal_descent(poly: TropicalLinear, x0: FloatArray, *, box: float=2.0, schedule: Any | None=None) -> TropicalPathResultFirst-order temperature homotopy; mirrors anneal_descent.
Uses TropicalSchedule or a duck-typed AnnealSchedule.
Each gradient step counts as one objective evaluation.
Parameters
| Name | Type & default | Contract |
|---|---|---|
polypositional-or-keyword | TropicalLinearRequired | See the operation contract and implementation below. |
x0positional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
boxkeyword-only | floatDefault: 2.0 | See the operation contract and implementation below. |
schedulekeyword-only | Any | NoneDefault: None | See the operation contract and implementation below. |
TropicalPathResultExplicit validation & failure cases
- When
int(x.shape[0]) != poly.dim, raisesValueError(f'x0 dim {int(x.shape[0])} != poly.dim {poly.dim}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qRead the implementation
def tropical_anneal_descent(
poly: TropicalLinear,
x0: FloatArray,
*,
box: float = 2.0,
schedule: Any | None = None,
) -> TropicalPathResult:
"""First-order temperature homotopy; mirrors ``anneal_descent``.
Uses :class:`TropicalSchedule` or a duck-typed ``AnnealSchedule``.
Each gradient step counts as one objective evaluation.
"""
sched = as_tropical_schedule(schedule)
x = _clip_box(np.asarray(x0, dtype=np.float64).reshape(-1), box)
if int(x.shape[0]) != poly.dim:
raise ValueError(f"x0 dim {int(x.shape[0])} != poly.dim {poly.dim}")
lip = _lipschitz(poly)
n_evals = 0
betas = sched.betas()
for beta in betas:
eta = sched.step_safety / (beta * lip + 1e-12)
for _ in range(sched.steps):
grad = np.asarray(relaxed_grad(poly, x, beta=beta)).reshape(-1)
x = _clip_box(x - eta * grad, box)
n_evals += 1
return _decode(poly, x, beta=betas[-1], n_evals=n_evals, method="anneal")tropical_value
omnibias.struct.tropical_valueSource ↗tropical_value(poly: TropicalLinear, x: FloatArray) -> FloatArrayThe module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.
Parameters
| Name | Type & default | Contract |
|---|---|---|
polypositional-or-keyword | TropicalLinearRequired | See the operation contract and implementation below. |
xpositional-or-keyword | FloatArrayRequired | See the operation contract and implementation below. |
FloatArrayExecuted regression · g4 path follow beats anneal evals
Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g4_path_follow_beats_anneal_evals() -> None:
sched = TropicalSchedule()
wins = 0
for seed in range(5):
poly = surrounding_tropical(6, 2, seed=seed)
rng = np.random.default_rng(100 + seed)
x0 = rng.uniform(-0.8, 0.8, size=2)
annealed = tropical_anneal_descent(poly, x0, schedule=sched)
followed = path_follow(poly, x0, schedule=sched)
assert followed.gap.is_sound
assert annealed.gap.is_sound
assert abs(followed.decoded - annealed.decoded) <= 1e-4
if annealed.n_evals >= 2 * followed.n_evals:
wins += 1
assert wins == 5python -m pytest "packages/omnibias-struct/tests/test_tropical.py::test_g4_path_follow_beats_anneal_evals" -qRegression example · g1 gap soundness
This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.
def test_g1_gap_soundness() -> None:
poly = _poly()
rng = np.random.default_rng(1)
grid = np.stack(
np.meshgrid(np.linspace(-1.5, 1.5, 21), np.linspace(-1.5, 1.5, 21), indexing="ij"),
axis=-1,
).reshape(-1, 2)
extra = rng.normal(size=(40, 2))
x = np.concatenate([grid, extra], axis=0)
for beta in (0.5, 2.0, 20.0):
cert = certify_tropical_gap(poly, x, beta=beta)
assert cert.is_sound
assert cert.bound == pytest.approx(homotopy_gap_bound(poly, beta=beta))
assert float(np.max(relaxed_value(poly, x, beta=beta) - tropical_value(poly, x))) <= cert.bound + 1e-12python -m pytest packages/omnibias-struct/tests/test_tropical.py -k test_g1_gap_soundness -qRead the implementation
def tropical_value(poly: TropicalLinear, x: FloatArray) -> FloatArray:
return np.max(scores(poly, x), axis=-1)