omnibias.core.contraction
Coefficient recurrences, activation contracts, jet algebra, and verified arithmetic shared by the numerical backends.
import omnibias.core.contractionModule contract & mathematical conventions
Combinatorics for the deep-network Laplacian / poly-Laplacian fast lane.
omnibias.core.multi_index materialises *every* mixed partial up to a
total order -- the right tool for "give me the whole jet", but the wrong one
for an operator that only ever *contracts* the jet down to one number (the
Laplacian, or its k-th iterate). This module supplies the
backend-agnostic bookkeeping the deep_field_laplacian /
deep_field_polylaplacian kernels in omnibias.jax.laplacian and
omnibias.torch.laplacian need to do that contraction directly, so a
deep network's Laplacian at any input dimension D never has to pay the
comb(D + 2k, D) multi-index ceiling.
Three routes are exposed, mirroring the tiers documented on the field operators:
- **Tier A (forward, k = 1 only)** -- the classic forward-Laplacian
recursion carries a Jacobian and one scalar per hidden unit, at
O(B * H * D), with no combinatorial term at all. It has no ceiling and applies at everyD, soselect_modealways returns"forward"fork = 1. - **Tier B (support-grouped local jets, k >= 2, exact while it fits a budget)**
-- the multinomial expansion
Delta^k = (sum_i d_i^2)^k = k! * sum_{|a|=k} D^(2a) f / a!is evaluated exactly by grouping the termsaby their *support* (the axes witha_i > 0, at mostkof them) and reading each group off one small local multivariate jet restricted to that support.polylaplacian_support_termsreturns that grouping;support_jet_countis the number of local-jet evaluations it costs. - **Tier C (estimator, k >= 2, unbounded D)** -- the spherical identity in
polylaplacian_normalizerturnsDelta^k finto a normalised expectation of a *directional*2k-th derivative over the unit sphere, estimated by sampling directions;omnibias.core.verified.sampledsupplies the concentration bound around the sample mean.
Every function here is pure Python (no numpy / torch / jax), so both backend
kernels share the exact same combinatorics and stay bit-identical by
construction, the same discipline as omnibias.core.multi_index.
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.
DEFAULT_SUPPORT_BUDGET
omnibias.core.contraction.DEFAULT_SUPPORT_BUDGETSource ↗DEFAULT_SUPPORT_BUDGET: int = 20000Number of local-jet evaluations above which select_mode prefers
the unbiased estimator (Tier C) over the exact support-grouped route (Tier B).
This is deliberately smaller than omnibias.core.multi_index.MAX_MULTI_INDICES:
support cost is dominated by the *number of support sets*, not by the size
of any one jet, so a much smaller ceiling already protects against runaway
work.
Regression example · select mode picks support within budget
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_mode_picks_support_within_budget() -> None:
# dim=4, k=2: support_jet_count = comb(4,1) + comb(4,2) = 4 + 6 = 10, tiny.
assert select_mode(4, 2, budget=DEFAULT_SUPPORT_BUDGET) == "support"python -m pytest packages/omnibias-core/tests/test_contraction.py -k test_select_mode_picks_support_within_budget -qRead the implementation
DEFAULT_SUPPORT_BUDGET: int = 20_000Mode
omnibias.core.contraction.ModeSource ↗Mode = Literal['forward', 'support', 'estimator']This exported constant is defined by the expression above. Its exact value and annotation come from the pinned source; use it with the module contract.
Read the implementation
Mode = Literal["forward", "support", "estimator"]PolylaplacianReport
omnibias.core.contraction.PolylaplacianReportSource ↗class PolylaplacianReportDataclass 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.
Metadata returned by deep_field_polylaplacian_with_report.
Attributes
mode : Mode Resolved tier after select_mode (or an explicit mode override).
dim : int Ambient input dimension D.
k : int Poly-Laplacian order.
budget : int Support-jet budget used for the Tier B/C decision.
n_directions : int | None Sample count when mode == "estimator", else None.
concentration : ConcentrationReport | None Hoeffding enclosure around the Tier C sample mean, when applicable.
Parameters
| Name | Type & default | Contract |
|---|---|---|
modedataclass field | ModeRequired | Mode Resolved tier after select_mode (or an explicit mode override). |
dimdataclass field | intRequired | int Ambient input dimension D. |
kdataclass field | intRequired | int Poly-Laplacian order. |
budgetdataclass field | intRequired | int Support-jet budget used for the Tier B/C decision. |
n_directionsdataclass field | int | NoneDefault: None | int | None Sample count when mode == "estimator", else None. |
concentrationdataclass field | ConcentrationReport | NoneDefault: None | ConcentrationReport | None Hoeffding enclosure around the Tier C sample mean, when applicable. |
Fields & methods
n_directionsfield
n_directions: int | None = NoneSample count when mode == "estimator", else None.
concentrationfield
concentration: ConcentrationReport | None = NoneHoeffding enclosure around the Tier C sample mean, when applicable.
Read the implementation
class PolylaplacianReport:
"""Metadata returned by ``deep_field_polylaplacian_with_report``.
Attributes
----------
mode : Mode
Resolved tier after ``select_mode`` (or an explicit ``mode`` override).
dim : int
Ambient input dimension ``D``.
k : int
Poly-Laplacian order.
budget : int
Support-jet budget used for the Tier B/C decision.
n_directions : int | None
Sample count when ``mode == "estimator"``, else ``None``.
concentration : ConcentrationReport | None
Hoeffding enclosure around the Tier C sample mean, when applicable.
"""
mode: Mode
dim: int
k: int
budget: int
n_directions: int | None = None
concentration: ConcentrationReport | None = Nonepolylaplacian_multinomial_terms
omnibias.core.contraction.polylaplacian_multinomial_termsSource ↗polylaplacian_multinomial_terms(n_spatial: int, k: int) -> tuple[tuple[tuple[int, ...], int], ...]Multinomial expansion of Delta^k = (sum_i d_i^2)^k.
Returns (beta, k! / beta!) pairs over n_spatial axes with
|beta| = k, so that Delta^k f = sum_beta (k! / beta!) D^(2 beta) f.
Shared by both JetMLPVectorField twins (promoted out of the
previously duplicated private _polylaplacian_terms in
field-network adapters) and by
polylaplacian_support_terms below, which further groups these
terms by support so a deep field never needs the full order-2k jet.
Parameters
| Name | Type & default | Contract |
|---|---|---|
n_spatialpositional-or-keyword | intRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[tuple[tuple[int, ...], int], ...]Explicit validation & failure cases
- When
n_spatial < 1, raisesValueError(f'n_spatial must be >= 1, got {n_spatial}'). - 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 · multinomial terms rejects bad inputs
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_multinomial_terms_rejects_bad_inputs() -> None:
with pytest.raises(ValueError, match="n_spatial must be"):
polylaplacian_multinomial_terms(0, 1)
with pytest.raises(ValueError, match="k must be"):
polylaplacian_multinomial_terms(2, 0)python -m pytest "packages/omnibias-core/tests/test_contraction.py::test_multinomial_terms_rejects_bad_inputs" -qRegression example · multinomial terms k1 is identity expansion
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_multinomial_terms_k1_is_identity_expansion() -> None:
"""k=1: Delta f = sum_i d_i^2 f, one term per axis, coefficient 1."""
terms = polylaplacian_multinomial_terms(4, 1)
assert len(terms) == 4
for beta, coeff in terms:
assert coeff == 1
assert sum(beta) == 1python -m pytest packages/omnibias-core/tests/test_contraction.py -k test_multinomial_terms_k1_is_identity_expansion -qRead the implementation
def polylaplacian_multinomial_terms(
n_spatial: int, k: int
) -> tuple[tuple[tuple[int, ...], int], ...]:
r"""Multinomial expansion of ``Delta^k = (sum_i d_i^2)^k``.
Returns ``(beta, k! / beta!)`` pairs over ``n_spatial`` axes with
``|beta| = k``, so that ``Delta^k f = sum_beta (k! / beta!) D^(2 beta) f``.
Shared by both ``JetMLPVectorField`` twins (promoted out of the
previously duplicated private ``_polylaplacian_terms`` in
field-network adapters) and by
:func:`polylaplacian_support_terms` below, which further groups these
terms by support so a deep field never needs the full order-``2k`` jet.
"""
if n_spatial < 1:
raise ValueError(f"n_spatial must be >= 1, got {n_spatial}")
if k < 1:
raise ValueError(f"k must be >= 1, got {k}")
k_fact = factorial(k)
return tuple(
(beta, k_fact // multi_index_factorial(beta))
for beta in multi_indices(n_spatial, k)
if sum(beta) == k
)polylaplacian_normalizer
omnibias.core.contraction.polylaplacian_normalizerSource ↗polylaplacian_normalizer(dim: int, k: int) -> floatConstant relating Delta^k f to a directional-derivative expectation.
\Delta^k f(x) = \frac{2^k\,k!\,\prod_{j=0}^{k-1}(D + 2j)}{(2k)!}\; \mathbb{E}_{v \sim S^{D-1}}\!\left[\partial_v^{2k} f(x)\right]
Derivation sketch: for g ~ N(0, I_D), v = g / \|g\| is uniform on
the sphere and independent of \|g\|; matching the even Gaussian
moments E[g^alpha] for |alpha| = 2k against the multinomial
expansion Delta^k f = k! sum_{|a|=k} D^(2a) f / a! gives the constant
above (E[\|g\|^{2k}] = prod_{j=0}^{k-1}(D + 2j) is the standard
chi-squared moment). Checked directly against
polylaplacian_multinomial_terms at k = 1, 2 in the test suite
(k = 1 collapses to the familiar Delta f = D * E_v[partial_v^2 f]).
Parameters
dim : int Ambient input dimension D >= 1.
k : int Poly-Laplacian order >= 1.
Parameters
| Name | Type & default | Contract |
|---|---|---|
dimpositional-or-keyword | intRequired | int Ambient input dimension D >= 1. |
kpositional-or-keyword | intRequired | int Poly-Laplacian order >= 1. |
floatExplicit validation & failure cases
- When
dim < 1, raisesValueError(f'dim must be >= 1, got {dim}'). - 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 · normalizer k1 collapses to dimension
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_normalizer_k1_collapses_to_dimension() -> None:
"""``Delta f = D * E_v[partial_v^2 f]`` at k=1, for every D."""
for dim in (1, 2, 3, 8, 30):
assert polylaplacian_normalizer(dim, 1) == pytest.approx(float(dim))python -m pytest "packages/omnibias-core/tests/test_contraction.py::test_normalizer_k1_collapses_to_dimension" -qRegression example · normalizer rejects bad inputs
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_normalizer_rejects_bad_inputs() -> None:
with pytest.raises(ValueError, match="dim must be"):
polylaplacian_normalizer(0, 1)
with pytest.raises(ValueError, match="k must be"):
polylaplacian_normalizer(3, 0)python -m pytest packages/omnibias-core/tests/test_contraction.py -k test_normalizer_rejects_bad_inputs -qRead the implementation
def polylaplacian_normalizer(dim: int, k: int) -> float:
r"""Constant relating ``Delta^k f`` to a directional-derivative expectation.
.. math::
\Delta^k f(x) = \frac{2^k\,k!\,\prod_{j=0}^{k-1}(D + 2j)}{(2k)!}\;
\mathbb{E}_{v \sim S^{D-1}}\!\left[\partial_v^{2k} f(x)\right]
Derivation sketch: for ``g ~ N(0, I_D)``, ``v = g / \|g\|`` is uniform on
the sphere and independent of ``\|g\|``; matching the even Gaussian
moments ``E[g^alpha]`` for ``|alpha| = 2k`` against the multinomial
expansion ``Delta^k f = k! sum_{|a|=k} D^(2a) f / a!`` gives the constant
above (``E[\|g\|^{2k}] = prod_{j=0}^{k-1}(D + 2j)`` is the standard
chi-squared moment). Checked directly against
:func:`polylaplacian_multinomial_terms` at ``k = 1, 2`` in the test suite
(``k = 1`` collapses to the familiar ``Delta f = D * E_v[partial_v^2 f]``).
Parameters
----------
dim : int
Ambient input dimension ``D >= 1``.
k : int
Poly-Laplacian order ``>= 1``.
"""
if dim < 1:
raise ValueError(f"dim must be >= 1, got {dim}")
if k < 1:
raise ValueError(f"k must be >= 1, got {k}")
rising = 1
for j in range(k):
rising *= dim + 2 * j
return float(2**k * factorial(k) * rising) / factorial(2 * k)polylaplacian_support_terms
omnibias.core.contraction.polylaplacian_support_termsSource ↗polylaplacian_support_terms(dim: int, k: int) -> tuple[tuple[tuple[int, ...], tuple[tuple[tuple[int, ...], int], ...]], ...]Group the |a| = k multinomial terms of Delta^k by support.
Delta^k f = sum_{|a|=k} (k! / a!) D^(2a) f, and every surviving a
has at most k nonzero entries (since each is >= 1 and they sum to
k). Grouping by the *support* S = {i : a_i > 0} (an increasing
tuple of axis indices, |S| <= min(k, dim)) means every a sharing a
support can be read off **one** local multivariate jet of dimension
|S| and order 2k -- restricting the network's first affine layer
to the columns in S (see deep_field_polylaplacian in
omnibias.jax.laplacian / omnibias.torch.laplacian) -- rather
than one jet per a or, worse, the full order-2k jet over all
dim axes.
Returns
tuple of (support, terms) support is an increasing tuple of axis indices. terms is a tuple of (a_local, coeff) pairs where a_local is the multi-index restricted to support (same length and order as support, every entry >= 1) and coeff = k! / a_local! is its multinomial weight. Cached on (dim, k): the grouping is pure combinatorics, shared by every point in a batch.
Parameters
| Name | Type & default | Contract |
|---|---|---|
dimpositional-or-keyword | intRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
tuple[tuple[tuple[int, ...], tuple[tuple[tuple[int, ...], int], ...]], ...]Explicit validation & failure cases
- When
dim < 1, raisesValueError(f'dim must be >= 1, got {dim}'). - 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 · support terms rejects bad inputs
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_support_terms_rejects_bad_inputs() -> None:
with pytest.raises(ValueError, match="dim must be"):
polylaplacian_support_terms(0, 1)
with pytest.raises(ValueError, match="k must be"):
polylaplacian_support_terms(3, 0)python -m pytest "packages/omnibias-core/tests/test_contraction.py::test_support_terms_rejects_bad_inputs" -qRegression example · support terms is cached
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_support_terms_is_cached() -> None:
a = polylaplacian_support_terms(4, 2)
b = polylaplacian_support_terms(4, 2)
assert a is bpython -m pytest packages/omnibias-core/tests/test_contraction.py -k test_support_terms_is_cached -qRead the implementation
def polylaplacian_support_terms(
dim: int, k: int
) -> tuple[tuple[tuple[int, ...], tuple[tuple[tuple[int, ...], int], ...]], ...]:
r"""Group the ``|a| = k`` multinomial terms of ``Delta^k`` by support.
``Delta^k f = sum_{|a|=k} (k! / a!) D^(2a) f``, and every surviving ``a``
has at most ``k`` nonzero entries (since each is ``>= 1`` and they sum to
``k``). Grouping by the *support* ``S = {i : a_i > 0}`` (an increasing
tuple of axis indices, ``|S| <= min(k, dim)``) means every ``a`` sharing a
support can be read off **one** local multivariate jet of dimension
``|S|`` and order ``2k`` -- restricting the network's first affine layer
to the columns in ``S`` (see ``deep_field_polylaplacian`` in
:mod:`omnibias.jax.laplacian` / :mod:`omnibias.torch.laplacian``) -- rather
than one jet per ``a`` or, worse, the full order-``2k`` jet over all
``dim`` axes.
Returns
-------
tuple of ``(support, terms)``
``support`` is an increasing tuple of axis indices. ``terms`` is a
tuple of ``(a_local, coeff)`` pairs where ``a_local`` is the
multi-index restricted to ``support`` (same length and order as
``support``, every entry ``>= 1``) and ``coeff = k! / a_local!`` is
its multinomial weight. Cached on ``(dim, k)``: the grouping is pure
combinatorics, shared by every point in a batch.
"""
if dim < 1:
raise ValueError(f"dim must be >= 1, got {dim}")
if k < 1:
raise ValueError(f"k must be >= 1, got {k}")
from itertools import combinations
k_fact = factorial(k)
s_max = min(k, dim)
groups: list[tuple[tuple[int, ...], tuple[tuple[tuple[int, ...], int], ...]]] = []
for s in range(1, s_max + 1):
for support in combinations(range(dim), s):
terms = tuple(
(a_local, k_fact // multi_index_factorial(a_local))
for a_local in _positive_compositions(k, s)
)
groups.append((support, terms))
return tuple(groups)select_mode
omnibias.core.contraction.select_modeSource ↗select_mode(dim: int, k: int, *, budget: int | None=None) -> ModeChoose the cheapest ceiling-free route for Delta^k at this (dim, k).
k = 1 always returns "forward" (Tier A has no ceiling at any
dimension). For k >= 2, "support" (Tier B, exact) is returned
while support_jet_count stays within budget
(DEFAULT_SUPPORT_BUDGET when budget is None); beyond that
it returns "estimator" (Tier C, unbiased in expectation, unbounded
dim).
Parameters
| Name | Type & default | Contract |
|---|---|---|
dimpositional-or-keyword | intRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
budgetkeyword-only | int | NoneDefault: None | See the operation contract and implementation below. |
ModeExplicit validation & failure cases
- When
dim < 1, raisesValueError(f'dim must be >= 1, got {dim}'). - When
k < 1, raisesValueError(f'k must be >= 1, got {k}'). - When
resolved_budget < 1, raisesValueError(f'budget must be >= 1, got {resolved_budget}').
These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.
Executed regression · select mode k1 is always forward
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_select_mode_k1_is_always_forward() -> None:
for dim in (1, 2, 100, 5000):
assert select_mode(dim, 1) == "forward"python -m pytest "packages/omnibias-core/tests/test_contraction.py::test_select_mode_k1_is_always_forward" -qRegression example · select mode picks estimator beyond budget
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_mode_picks_estimator_beyond_budget() -> None:
# A large dim/k combination whose support_jet_count exceeds a small budget.
assert select_mode(200, 3, budget=100) == "estimator"python -m pytest packages/omnibias-core/tests/test_contraction.py -k test_select_mode_picks_estimator_beyond_budget -qRead the implementation
def select_mode(
dim: int, k: int, *, budget: int | None = None
) -> Mode:
"""Choose the cheapest ceiling-free route for ``Delta^k`` at this ``(dim, k)``.
``k = 1`` always returns ``"forward"`` (Tier A has no ceiling at any
dimension). For ``k >= 2``, ``"support"`` (Tier B, exact) is returned
while :func:`support_jet_count` stays within ``budget``
(:data:`DEFAULT_SUPPORT_BUDGET` when ``budget`` is ``None``); beyond that
it returns ``"estimator"`` (Tier C, unbiased in expectation, unbounded
``dim``).
"""
if dim < 1:
raise ValueError(f"dim must be >= 1, got {dim}")
if k < 1:
raise ValueError(f"k must be >= 1, got {k}")
if k == 1:
return "forward"
resolved_budget = DEFAULT_SUPPORT_BUDGET if budget is None else budget
if resolved_budget < 1:
raise ValueError(f"budget must be >= 1, got {resolved_budget}")
if support_jet_count(dim, k) <= resolved_budget:
return "support"
return "estimator"support_jet_count
omnibias.core.contraction.support_jet_countSource ↗support_jet_count(dim: int, k: int) -> intNumber of local-jet evaluations polylaplacian_support_terms costs.
Equal to sum_{s=1}^{min(k, dim)} comb(dim, s) -- one local
multivariate jet per *support set* of size s (each costing
comb(s + 2k, s), bounded purely by k since s <= k). This is
the quantity select_mode checks against a budget: it grows
polynomially in dim for fixed k (O(dim^k)), unlike the
comb(dim + 2k, dim) the full multivariate jet would need.
Parameters
| Name | Type & default | Contract |
|---|---|---|
dimpositional-or-keyword | intRequired | See the operation contract and implementation below. |
kpositional-or-keyword | intRequired | See the operation contract and implementation below. |
intExplicit validation & failure cases
- When
dim < 1, raisesValueError(f'dim must be >= 1, got {dim}'). - 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 · select mode picks estimator beyond budget
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_select_mode_picks_estimator_beyond_budget() -> None:
# A large dim/k combination whose support_jet_count exceeds a small budget.
assert select_mode(200, 3, budget=100) == "estimator"python -m pytest "packages/omnibias-core/tests/test_contraction.py::test_select_mode_picks_estimator_beyond_budget" -qRegression example · select mode boundary is inclusive
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_mode_boundary_is_inclusive() -> None:
dim, k = 6, 2
size = support_jet_count(dim, k)
assert select_mode(dim, k, budget=size) == "support"
assert select_mode(dim, k, budget=size - 1) == "estimator"python -m pytest packages/omnibias-core/tests/test_contraction.py -k test_select_mode_boundary_is_inclusive -qRead the implementation
def support_jet_count(dim: int, k: int) -> int:
"""Number of local-jet evaluations :func:`polylaplacian_support_terms` costs.
Equal to ``sum_{s=1}^{min(k, dim)} comb(dim, s)`` -- one local
multivariate jet per *support set* of size ``s`` (each costing
``comb(s + 2k, s)``, bounded purely by ``k`` since ``s <= k``). This is
the quantity :func:`select_mode` checks against a budget: it grows
polynomially in ``dim`` for fixed ``k`` (``O(dim^k)``), unlike the
``comb(dim + 2k, dim)`` the full multivariate jet would need.
"""
if dim < 1:
raise ValueError(f"dim must be >= 1, got {dim}")
if k < 1:
raise ValueError(f"k must be >= 1, got {k}")
s_max = min(k, dim)
return sum(comb(dim, s) for s in range(1, s_max + 1))