Skip to main content

omnibias.jax.architectures.pinn

0.5.0rc1Release candidatePython >=3.10Apache-2.0

JAX activation derivatives, functional network jets, direct contractions, and parameter-differentiable numerical models.

import omnibias.jax.architectures.pinn
Module contract & mathematical conventions

Deep, arbitrary-order omnibias PINNs for JAX -- algebraically corresponding twins of torch.

JetMLP is the JAX counterpart of omnibias.torch.architectures.pinn.JetMLP: a deep fully-connected network whose *every* mixed input partial D^alpha u(x) up to total order N comes **exactly** from one forward pass of omnibias.jax.jet_mv.mlp_jet_mv -- no jax.grad stacking, no finite differences. Because both backends call the same Faa di Bruno multivariate-jet kernel, the derivatives are *algebraically corresponding* across torch and JAX in double precision (enable jax_enable_x64).

Spectral-bias mitigation mirrors the torch surface:

  • FourierFeatureMLP lifts the input through a random Fourier-feature encoding gamma(x) = [cos(B x), sin(B x)] (Tancik et al. 2020). Because cos(z) = sin(z + pi/2) the encoding is a single omnibias sin layer, so the composite still yields every closed-form derivative through mlp_jet_mv. Build one with make_fourier_feature_mlp.
  • make_siren builds a SIREN (Sitzmann et al. 2020): a JetMLP with sin activations and the SIREN initialisation; its derivative tower is exact for every order (sin^{(n)}(z) = sin(z + n pi/2)).

Each network is a frozen dataclass registered as a JAX pytree (its weight/bias arrays are the leaves), so it flows through jax.grad / jax.jit for training while omnibias supplies the spatial differential operator.

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.

CLASS

FourierFeatureMLP​

omnibias.jax.architectures.FourierFeatureMLPSource ↗
class FourierFeatureMLP

Dataclass 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.

Spectral-bias-mitigating MLP with a sin-encoded random Fourier front end (JAX).

The input is lifted by gamma(x) = [cos(B x), sin(B x)] (Tancik et al. 2020) and a standard MLP body acts on it. Because cos(z) = sin(z + pi/2) the encoding is a single omnibias sin layer (gamma(x) = sin([B; B] x + [pi/2; 0])), so D^alpha u(x) stays exactly closed form to arbitrary order through omnibias.jax.jet_mv.mlp_jet_mv. mathematically equivalent twin of omnibias.torch.architectures.pinn.FourierFeatureMLP.

Parameters

w_ff, b_ff The sin-encoding layer: w_ff has shape (2 F_total, in_dim) and equals [B; B]; b_ff is [pi/2 * 1_{F_total}; 0_{F_total}]. weights, biases Body parameters (hidden layers + affine readout). base_spec Body activation with a closed-form derivative fast path. in_dim, out_dim Input coordinate count and output component count. num_features Fourier features per band (F); the encoding width is 2 * F * len(scales). scales Frequency bands used to build B (kept for introspection).

Backend scope: this identifies the corresponding mathematical construction. It does not guarantee bitwise-equal floating-point results across devices, compilers, dtypes, or backend versions. Validate the selected path with an appropriate absolute and relative tolerance.

Parameters

NameType & defaultContract
w_ffdataclass fieldArrayRequiredThe sin-encoding layer: w_ff has shape (2 F_total, in_dim) and equals [B; B]; b_ff is [pi/2 * 1_{F_total}; 0_{F_total}].
b_ffdataclass fieldArrayRequiredSee the operation contract and implementation below.
weightsdataclass fieldtuple[Array, ...]RequiredBody parameters (hidden layers + affine readout).
biasesdataclass fieldtuple[Array, ...]RequiredSee the operation contract and implementation below.
base_specdataclass fieldJaxActivationSpecRequiredBody activation with a closed-form derivative fast path.
in_dimdataclass fieldintRequiredInput coordinate count and output component count.
out_dimdataclass fieldintRequiredSee the operation contract and implementation below.
num_featuresdataclass fieldintRequiredFourier features per band (F); the encoding width is 2 * F * len(scales).
scalesdataclass fieldtuple[float, ...]RequiredFrequency bands used to build B (kept for introspection).
Executed regression · fourier value equals jet row0

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_fourier_value_equals_jet_row0() -> None:
    net = make_fourier_feature_mlp(2, num_features=8, hidden=16, depth=2, seed=1)
    x = _x(2)
    jet = net.jet(x, 2)
    assert jnp.allclose(jet[:, 0, :], net.value(x), atol=1e-13)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_fourier_value_equals_jet_row0" -q
Regression example · fourier pytree grad flows

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_fourier_pytree_grad_flows() -> None:
    net = make_fourier_feature_mlp(2, num_features=6, hidden=10, depth=2, seed=9)
    x = _x(10, b=4)

    def loss(n: FourierFeatureMLP) -> jax.Array:
        v, g, h = n.value_grad_hessian(x)
        return jnp.mean((g[:, 1, 0] - 0.1 * h[:, 0, 0, 0]) ** 2)

    grads = jax.grad(loss)(net)
    assert jnp.all(jnp.isfinite(grads.w_ff))
    for w in grads.weights:
        assert jnp.all(jnp.isfinite(w))
python -m pytest packages/omnibias-jax/tests/test_spectral_pinn.py -k test_fourier_pytree_grad_flows -q

Fields & methods

w_fffield
w_ff: Array

The sin-encoding layer: w_ff has shape (2 F_total, in_dim) and equals [B; B]; b_ff is [pi/2 * 1_{F_total}; 0_{F_total}].

View source ↗
b_fffield
b_ff: Array

Declared Array field on FourierFeatureMLP. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
weightsfield
weights: tuple[Array, ...]

Body parameters (hidden layers + affine readout).

View source ↗
biasesfield
biases: tuple[Array, ...]

Declared tuple[Array, ...] field on FourierFeatureMLP. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
base_specfield
base_spec: JaxActivationSpec

Body activation with a closed-form derivative fast path.

View source ↗
in_dimfield
in_dim: int

Input coordinate count and output component count.

View source ↗
out_dimfield
out_dim: int

Declared int field on FourierFeatureMLP. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
num_featuresfield
num_features: int

Fourier features per band (F); the encoding width is 2 * F * len(scales).

View source ↗
scalesfield
scales: tuple[float, ...]

Frequency bands used to build B (kept for introspection).

View source ↗
feature_dimproperty
feature_dim(self) -> int

Width of the Fourier encoding 2 * F * len(scales).

Returns: int

Executed regression · fourier multiscale shapes and grad

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_fourier_multiscale_shapes_and_grad(scales: float | tuple[float, ...]) -> None:
    net = make_fourier_feature_mlp(
        2, num_features=4, hidden=10, depth=2, frequency_scale=scales, seed=6
    )
    n_bands = 1 if isinstance(scales, float) else len(scales)
    assert net.feature_dim == 2 * 4 * n_bands
    x = _x(7, b=5)
    g = net.gradient(x).squeeze(-1)
    g_ad = jax.vmap(jax.jacfwd(_val(net)))(x)
    assert jnp.allclose(g, g_ad, atol=1e-10)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_fourier_multiscale_shapes_and_grad[1.0]" -q
Method implementation
    def feature_dim(self) -> int:
        """Width of the Fourier encoding ``2 * F * len(scales)``."""
        return int(self.w_ff.shape[0])
View source ↗
depthproperty
depth(self) -> int

Number of hidden (activated) body layers.

Returns: int

Method implementation
    def depth(self) -> int:
        """Number of hidden (activated) body layers."""
        return len(self.weights) - 1
View source ↗
valuemethod
value(self, x: Array) -> Array

Plain network value u(x), shape (..., out_dim).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: Array

Executed regression · fourier value equals jet row0

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_fourier_value_equals_jet_row0() -> None:
    net = make_fourier_feature_mlp(2, num_features=8, hidden=16, depth=2, seed=1)
    x = _x(2)
    jet = net.jet(x, 2)
    assert jnp.allclose(jet[:, 0, :], net.value(x), atol=1e-13)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_fourier_value_equals_jet_row0" -q
Method implementation
    def value(self, x: Array) -> Array:
        """Plain network value ``u(x)``, shape ``(..., out_dim)``."""
        return _value_from_layers(self._layer_specs(), x)
View source ↗
__call__method
__call__(self, x: Array) -> Array

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: Array

Method implementation
    def __call__(self, x: Array) -> Array:
        return self.value(x)
View source ↗
jetmethod
jet(self, x: Array, order: int) -> Array

Batched multivariate jet, shape (B, M, out_dim).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.
orderpositional-or-keywordintRequiredSee the operation contract and implementation below.

Returns: Array

Executed regression · fourier value equals jet row0

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_fourier_value_equals_jet_row0() -> None:
    net = make_fourier_feature_mlp(2, num_features=8, hidden=16, depth=2, seed=1)
    x = _x(2)
    jet = net.jet(x, 2)
    assert jnp.allclose(jet[:, 0, :], net.value(x), atol=1e-13)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_fourier_value_equals_jet_row0" -q
Method implementation
    def jet(self, x: Array, order: int) -> Array:
        """Batched multivariate jet, shape ``(B, M, out_dim)``."""
        out: Array = jax.vmap(lambda xi: self._point_jet(xi, order))(x)
        return out
View source ↗
gradientmethod
gradient(self, x: Array) -> Array

Exact input gradient d u / d x_i, shape (B, in_dim, out_dim).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: Array

Executed regression · fourier jit compatible

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_fourier_jit_compatible() -> None:
    net = make_fourier_feature_mlp(2, num_features=6, hidden=10, depth=2, seed=8)
    x = _x(9, b=4)
    g_jit = jax.jit(lambda n, xx: n.gradient(xx))(net, x)
    assert jnp.allclose(g_jit, net.gradient(x), atol=1e-12)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_fourier_jit_compatible" -q
Method implementation
    def gradient(self, x: Array) -> Array:
        """Exact input gradient ``d u / d x_i``, shape ``(B, in_dim, out_dim)``."""
        dim = self.in_dim
        out: Array = jax.vmap(
            lambda xi: jet_gradient(self._point_jet(xi, 1), dim, 1)
        )(x)
        return out
View source ↗
hessianmethod
hessian(self, x: Array) -> Array

Exact input Hessian, shape (B, in_dim, in_dim, out_dim).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: Array

Executed regression · fourier hessian matches 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_fourier_hessian_matches_autograd() -> None:
    net = make_fourier_feature_mlp(2, num_features=8, hidden=16, depth=2, seed=4)
    x = _x(5, b=5)
    h = net.hessian(x).squeeze(-1)
    h_ad = jax.vmap(jax.hessian(_val(net)))(x)
    assert jnp.allclose(h, h_ad, atol=1e-9)
    assert jnp.allclose(h, jnp.transpose(h, (0, 2, 1)), atol=1e-11)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_fourier_hessian_matches_autograd" -q
Method implementation
    def hessian(self, x: Array) -> Array:
        """Exact input Hessian, shape ``(B, in_dim, in_dim, out_dim)``."""
        dim = self.in_dim
        out: Array = jax.vmap(
            lambda xi: jet_hessian(self._point_jet(xi, 2), dim, 2)
        )(x)
        return out
View source ↗
value_grad_hessianmethod
value_grad_hessian(self, x: Array) -> tuple[Array, Array, Array]

One jet -> (value, gradient, Hessian) for 2nd-order PDE residuals.

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: tuple[Array, Array, Array]

Executed regression · fourier pytree grad flows

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_fourier_pytree_grad_flows() -> None:
    net = make_fourier_feature_mlp(2, num_features=6, hidden=10, depth=2, seed=9)
    x = _x(10, b=4)

    def loss(n: FourierFeatureMLP) -> jax.Array:
        v, g, h = n.value_grad_hessian(x)
        return jnp.mean((g[:, 1, 0] - 0.1 * h[:, 0, 0, 0]) ** 2)

    grads = jax.grad(loss)(net)
    assert jnp.all(jnp.isfinite(grads.w_ff))
    for w in grads.weights:
        assert jnp.all(jnp.isfinite(w))
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_fourier_pytree_grad_flows" -q
Method implementation
    def value_grad_hessian(self, x: Array) -> tuple[Array, Array, Array]:
        """One jet -> ``(value, gradient, Hessian)`` for 2nd-order PDE residuals."""
        dim = self.in_dim

        def f(xi: Array) -> tuple[Array, Array, Array]:
            j = self._point_jet(xi, 2)
            return j[0], jet_gradient(j, dim, 2), jet_hessian(j, dim, 2)

        res = jax.vmap(f)(x)
        value_b: Array = res[0]
        grad_b: Array = res[1]
        hess_b: Array = res[2]
        return value_b, grad_b, hess_b
View source ↗
partialsmethod
partials(self, x: Array, order: int) -> dict[tuple[int, ...], Array]

All raw partials {alpha: D^alpha u(x)} to total order ((B, out_dim)).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.
orderpositional-or-keywordintRequiredSee the operation contract and implementation below.

Returns: dict[tuple[int, ...], Array]

Executed regression · fourier third order matches 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_fourier_third_order_matches_autograd() -> None:
    net = make_fourier_feature_mlp(2, num_features=6, hidden=12, depth=2, seed=5)
    x = _x(6, b=4)
    parts = net.partials(x, 3)
    jf = jax.jacfwd
    t3 = jax.vmap(jf(jf(jf(_val(net)))))(x)
    assert jnp.allclose(parts[(3, 0)].squeeze(-1), t3[:, 0, 0, 0], atol=1e-8)
    assert jnp.allclose(parts[(2, 1)].squeeze(-1), t3[:, 0, 0, 1], atol=1e-8)
    assert jnp.allclose(parts[(0, 3)].squeeze(-1), t3[:, 1, 1, 1], atol=1e-8)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_fourier_third_order_matches_autograd" -q
Method implementation
    def partials(self, x: Array, order: int) -> dict[tuple[int, ...], Array]:
        """All raw partials ``{alpha: D^alpha u(x)}`` to total ``order`` (``(B, out_dim)``)."""
        return _partials_from_jet(self.jet(x, order), self.in_dim, order)
View source ↗
Read the implementation
class FourierFeatureMLP:
    r"""Spectral-bias-mitigating MLP with a sin-encoded random Fourier front end (JAX).

    The input is lifted by ``gamma(x) = [cos(B x), sin(B x)]`` (Tancik et al. 2020) and
    a standard MLP body acts on it. Because ``cos(z) = sin(z + pi/2)`` the encoding is a
    single omnibias ``sin`` layer
    (``gamma(x) = sin([B; B] x + [pi/2; 0])``), so ``D^alpha u(x)`` stays exactly closed
    form to arbitrary order through :func:`omnibias.jax.jet_mv.mlp_jet_mv`. Bit-identical
    twin of :class:`omnibias.torch.architectures.pinn.FourierFeatureMLP`.

    Parameters
    ----------
    w_ff, b_ff
        The sin-encoding layer: ``w_ff`` has shape ``(2 F_total, in_dim)`` and equals
        ``[B; B]``; ``b_ff`` is ``[pi/2 * 1_{F_total}; 0_{F_total}]``.
    weights, biases
        Body parameters (hidden layers + affine readout).
    base_spec
        Body activation with a closed-form derivative fast path.
    in_dim, out_dim
        Input coordinate count and output component count.
    num_features
        Fourier features per band (``F``); the encoding width is ``2 * F * len(scales)``.
    scales
        Frequency bands used to build ``B`` (kept for introspection).
    """

    w_ff: Array
    b_ff: Array
    weights: tuple[Array, ...]
    biases: tuple[Array, ...]
    base_spec: JaxActivationSpec
    in_dim: int
    out_dim: int
    num_features: int
    scales: tuple[float, ...]

    @property
    def feature_dim(self) -> int:
        """Width of the Fourier encoding ``2 * F * len(scales)``."""
        return int(self.w_ff.shape[0])

    @property
    def depth(self) -> int:
        """Number of hidden (activated) body layers."""
        return len(self.weights) - 1

    def _layer_specs(self) -> list[LayerSpec]:
        sin_spec = get_activation("sin")
        specs: list[LayerSpec] = [(self.w_ff, self.b_ff, sin_spec)]
        n = len(self.weights)
        for i in range(n):
            specs.append(
                (self.weights[i], self.biases[i], None if i == n - 1 else self.base_spec)
            )
        return specs

    def _point_hidden_jet(self, xi: Array, order: int) -> Array:
        """Single-point jet through every layer *except* the affine readout.

        Shape ``(M, H)``.
        """
        return _point_hidden_jet_from_layers(self._layer_specs(), xi, order)

    def _apply_readout_jet(self, hidden_jet: Array) -> Array:
        """Push a (possibly batched) hidden jet through the live affine readout.

        ``hidden_jet`` has shape ``(M, H)`` or ``(B, M, H)``.
        """
        return _apply_readout_jet_from_layers(self._layer_specs(), hidden_jet)

    def _point_jet(self, xi: Array, order: int) -> Array:
        """Single-point multivariate jet, shape ``(M, out_dim)``."""
        return self._apply_readout_jet(self._point_hidden_jet(xi, order))

    def _check_fastpath(self, max_order: int) -> None:
        """Reject activations without a closed-form tower up to ``max_order``."""
        _check_layer_fastpaths(self._layer_specs(), max_order)

    def value(self, x: Array) -> Array:
        """Plain network value ``u(x)``, shape ``(..., out_dim)``."""
        return _value_from_layers(self._layer_specs(), x)

    def __call__(self, x: Array) -> Array:
        return self.value(x)

    def jet(self, x: Array, order: int) -> Array:
        """Batched multivariate jet, shape ``(B, M, out_dim)``."""
        out: Array = jax.vmap(lambda xi: self._point_jet(xi, order))(x)
        return out

    def gradient(self, x: Array) -> Array:
        """Exact input gradient ``d u / d x_i``, shape ``(B, in_dim, out_dim)``."""
        dim = self.in_dim
        out: Array = jax.vmap(
            lambda xi: jet_gradient(self._point_jet(xi, 1), dim, 1)
        )(x)
        return out

    def hessian(self, x: Array) -> Array:
        """Exact input Hessian, shape ``(B, in_dim, in_dim, out_dim)``."""
        dim = self.in_dim
        out: Array = jax.vmap(
            lambda xi: jet_hessian(self._point_jet(xi, 2), dim, 2)
        )(x)
        return out

    def value_grad_hessian(self, x: Array) -> tuple[Array, Array, Array]:
        """One jet -> ``(value, gradient, Hessian)`` for 2nd-order PDE residuals."""
        dim = self.in_dim

        def f(xi: Array) -> tuple[Array, Array, Array]:
            j = self._point_jet(xi, 2)
            return j[0], jet_gradient(j, dim, 2), jet_hessian(j, dim, 2)

        res = jax.vmap(f)(x)
        value_b: Array = res[0]
        grad_b: Array = res[1]
        hess_b: Array = res[2]
        return value_b, grad_b, hess_b

    def partials(self, x: Array, order: int) -> dict[tuple[int, ...], Array]:
        """All raw partials ``{alpha: D^alpha u(x)}`` to total ``order`` (``(B, out_dim)``)."""
        return _partials_from_jet(self.jet(x, order), self.in_dim, order)
Other public import paths
  • omnibias.jax.architectures.FourierFeatureMLP
  • omnibias.jax.architectures.pinn.FourierFeatureMLP
CLASS

JetMLP​

omnibias.jax.architectures.JetMLPSource ↗
class JetMLP

Dataclass 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.

Deep MLP with exact omnibias multivariate-jet input derivatives (JAX).

Parameters

weights, biases Per-linear parameters; len == depth + 1 (the last is the affine readout). weights[i] has shape (out_i, in_i) and biases[i] shape (out_i,). spec Base activation with a closed-form derivative fast path. in_dim, out_dim Input coordinate count and output component count.

Parameters

NameType & defaultContract
weightsdataclass fieldtuple[Array, ...]RequiredPer-linear parameters; len == depth + 1 (the last is the affine readout). weights[i] has shape (out_i, in_i) and biases[i] shape (out_i,).
biasesdataclass fieldtuple[Array, ...]RequiredSee the operation contract and implementation below.
specdataclass fieldJaxActivationSpecRequiredBase activation with a closed-form derivative fast path.
in_dimdataclass fieldintRequiredInput coordinate count and output component count.
out_dimdataclass fieldintRequiredSee the operation contract and implementation below.
Executed regression · depth property

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_depth_property() -> None:
    net = make_jet_mlp(2, 8, 1, depth=3, seed=0)
    assert net.depth == 3
    assert len(net.weights) == 4  # 3 hidden + 1 readout
python -m pytest "packages/omnibias-jax/tests/test_jet_pinn.py::test_depth_property" -q
Regression example · multi output box 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_multi_output_box_parity() -> None:
    tnet, jnet = _jetmlp_pair(2, 10, 3, 2, "tanh", seed=4)
    tfield = torch_hardbc.homogeneous_box(tnet, [0.0, 0.0], [1.0, 1.0])
    jfield = jax_hardbc.homogeneous_box(jnet, [0.0, 0.0], [1.0, 1.0])
    xt, xj = _xpair(seed=4, b=4, d=2)
    _assert_field_parity(tfield, jfield, xt, xj)
python -m pytest tests/test_hardbc_parity.py -k test_multi_output_box_parity -q

Fields & methods

weightsfield
weights: tuple[Array, ...]

Per-linear parameters; len == depth + 1 (the last is the affine readout). weights[i] has shape (out_i, in_i) and biases[i] shape (out_i,).

View source ↗
biasesfield
biases: tuple[Array, ...]

Declared tuple[Array, ...] field on JetMLP. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
specfield
spec: JaxActivationSpec

Base activation with a closed-form derivative fast path.

View source ↗
in_dimfield
in_dim: int

Input coordinate count and output component count.

View source ↗
out_dimfield
out_dim: int

Declared int field on JetMLP. A value must be provided when constructing the configuration, unless an inherited constructor supplies it.

View source ↗
depthproperty
depth(self) -> int

Number of hidden (activated) layers.

Returns: int

Executed regression · depth property

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_depth_property() -> None:
    net = make_jet_mlp(2, 8, 1, depth=3, seed=0)
    assert net.depth == 3
    assert len(net.weights) == 4  # 3 hidden + 1 readout
python -m pytest "packages/omnibias-jax/tests/test_jet_pinn.py::test_depth_property" -q
Method implementation
    def depth(self) -> int:
        """Number of hidden (activated) layers."""
        return len(self.weights) - 1
View source ↗
valuemethod
value(self, x: Array) -> Array

Plain network value u(x), shape (..., out_dim).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: Array

Executed regression · value equals jet row0

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_value_equals_jet_row0() -> None:
    net = make_jet_mlp(2, 16, 1, depth=3, seed=1)
    x = _x(2)
    jet = net.jet(x, 2)
    assert jnp.allclose(jet[:, 0, :], net.value(x), atol=1e-14)
python -m pytest "packages/omnibias-jax/tests/test_jet_pinn.py::test_value_equals_jet_row0" -q
Method implementation
    def value(self, x: Array) -> Array:
        """Plain network value ``u(x)``, shape ``(..., out_dim)``."""
        return _value_from_layers(self._layer_specs(), x)
View source ↗
__call__method
__call__(self, x: Array) -> Array

See the class contract above and the exact method implementation below.

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: Array

Method implementation
    def __call__(self, x: Array) -> Array:
        return self.value(x)
View source ↗
jetmethod
jet(self, x: Array, order: int) -> Array

Batched multivariate jet, shape (B, M, out_dim).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.
orderpositional-or-keywordintRequiredSee the operation contract and implementation below.

Returns: Array

Executed regression · value equals jet row0

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_value_equals_jet_row0() -> None:
    net = make_jet_mlp(2, 16, 1, depth=3, seed=1)
    x = _x(2)
    jet = net.jet(x, 2)
    assert jnp.allclose(jet[:, 0, :], net.value(x), atol=1e-14)
python -m pytest "packages/omnibias-jax/tests/test_jet_pinn.py::test_value_equals_jet_row0" -q
Method implementation
    def jet(self, x: Array, order: int) -> Array:
        """Batched multivariate jet, shape ``(B, M, out_dim)``."""
        out: Array = jax.vmap(lambda xi: self._point_jet(xi, order))(x)
        return out
View source ↗
gradientmethod
gradient(self, x: Array) -> Array

Exact input gradient d u / d x_i, shape (B, in_dim, out_dim).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: Array

Executed regression · jit compatible

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_jit_compatible() -> None:
    net = make_jet_mlp(2, 10, 1, depth=2, seed=2)
    x = _x(3, b=4)
    g_jit = jax.jit(lambda n, xx: n.gradient(xx))(net, x)
    assert jnp.allclose(g_jit, net.gradient(x), atol=1e-12)
python -m pytest "packages/omnibias-jax/tests/test_jet_pinn.py::test_jit_compatible" -q
Method implementation
    def gradient(self, x: Array) -> Array:
        """Exact input gradient ``d u / d x_i``, shape ``(B, in_dim, out_dim)``."""
        dim = self.in_dim
        out: Array = jax.vmap(
            lambda xi: jet_gradient(self._point_jet(xi, 1), dim, 1)
        )(x)
        return out
View source ↗
hessianmethod
hessian(self, x: Array) -> Array

Exact input Hessian, shape (B, in_dim, in_dim, out_dim).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: Array

Executed regression · activation sweep matches 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_activation_sweep_matches_autograd(activation: str) -> None:
    net = make_jet_mlp(2, 12, 1, depth=2, activation=activation, seed=2)
    x = _x(8, b=5)
    h = net.hessian(x).squeeze(-1)
    h_ad = jax.vmap(jax.hessian(_val(net)))(x)
    assert jnp.allclose(h, h_ad, atol=1e-9)
python -m pytest "packages/omnibias-jax/tests/test_jet_pinn.py::test_activation_sweep_matches_autograd[sigmoid]" -q
Method implementation
    def hessian(self, x: Array) -> Array:
        """Exact input Hessian, shape ``(B, in_dim, in_dim, out_dim)``."""
        dim = self.in_dim
        out: Array = jax.vmap(
            lambda xi: jet_hessian(self._point_jet(xi, 2), dim, 2)
        )(x)
        return out
View source ↗
value_grad_hessianmethod
value_grad_hessian(self, x: Array) -> tuple[Array, Array, Array]

One jet -> (value, gradient, Hessian) for 2nd-order PDE residuals.

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.

Returns: tuple[Array, Array, Array]

Executed regression · make residual fn 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_make_residual_fn_roundtrip() -> None:
    flat0, residual_fn = _poisson_residual_fn()
    r = residual_fn(flat0)
    assert r.shape[0] == 40  # 38 interior + 2 boundary
    assert jnp.all(jnp.isfinite(r))
python -m pytest "packages/omnibias-jax/tests/test_optim.py::test_make_residual_fn_roundtrip" -q
Method implementation
    def value_grad_hessian(self, x: Array) -> tuple[Array, Array, Array]:
        """One jet -> ``(value, gradient, Hessian)`` for 2nd-order PDE residuals."""
        dim = self.in_dim

        def f(xi: Array) -> tuple[Array, Array, Array]:
            j = self._point_jet(xi, 2)
            return j[0], jet_gradient(j, dim, 2), jet_hessian(j, dim, 2)

        res = jax.vmap(f)(x)
        value_b: Array = res[0]
        grad_b: Array = res[1]
        hess_b: Array = res[2]
        return value_b, grad_b, hess_b
View source ↗
partialsmethod
partials(self, x: Array, order: int) -> dict[tuple[int, ...], Array]

All raw partials {alpha: D^alpha u(x)} to total order ((B, out_dim)).

Parameters

NameType & defaultContract
xpositional-or-keywordArrayRequiredSee the operation contract and implementation below.
orderpositional-or-keywordintRequiredSee the operation contract and implementation below.

Returns: dict[tuple[int, ...], Array]

Executed regression · siren high order matches 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_siren_high_order_matches_autograd() -> None:
    net = make_siren(2, hidden=16, depth=2, omega_0=8.0, seed=3)
    x = _x(4, b=4)
    parts = net.partials(x, 4)
    jf = jax.jacfwd
    t4 = jax.vmap(jf(jf(jf(jf(_val(net))))))(x)
    assert jnp.allclose(parts[(4, 0)].squeeze(-1), t4[:, 0, 0, 0, 0], atol=1e-7)
    assert jnp.allclose(parts[(2, 2)].squeeze(-1), t4[:, 0, 0, 1, 1], atol=1e-7)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_siren_high_order_matches_autograd" -q
Method implementation
    def partials(self, x: Array, order: int) -> dict[tuple[int, ...], Array]:
        """All raw partials ``{alpha: D^alpha u(x)}`` to total ``order`` (``(B, out_dim)``)."""
        return _partials_from_jet(self.jet(x, order), self.in_dim, order)
View source ↗
Read the implementation
class JetMLP:
    r"""Deep MLP with exact omnibias multivariate-jet input derivatives (JAX).

    Parameters
    ----------
    weights, biases
        Per-linear parameters; ``len == depth + 1`` (the last is the affine
        readout). ``weights[i]`` has shape ``(out_i, in_i)`` and ``biases[i]``
        shape ``(out_i,)``.
    spec
        Base activation with a closed-form derivative fast path.
    in_dim, out_dim
        Input coordinate count and output component count.
    """

    weights: tuple[Array, ...]
    biases: tuple[Array, ...]
    spec: JaxActivationSpec
    in_dim: int
    out_dim: int

    @property
    def depth(self) -> int:
        """Number of hidden (activated) layers."""
        return len(self.weights) - 1

    def _layer_specs(self) -> list[LayerSpec]:
        n = len(self.weights)
        return [
            (self.weights[i], self.biases[i], None if i == n - 1 else self.spec)
            for i in range(n)
        ]

    def _point_hidden_jet(self, xi: Array, order: int) -> Array:
        """Single-point jet through every layer *except* the affine readout.

        Shape ``(M, H)``. The expensive Faà-di-Bruno work lives here; the live
        readout is applied by :meth:`_apply_readout_jet` so a cached
        :class:`~omnibias.fields._core.state.FieldState` stays valid across
        frozen-feature readout sweeps.
        """
        return _point_hidden_jet_from_layers(self._layer_specs(), xi, order)

    def _apply_readout_jet(self, hidden_jet: Array) -> Array:
        """Push a (possibly batched) hidden jet through the live affine readout.

        ``hidden_jet`` has shape ``(M, H)`` or ``(B, M, H)``; returns the same
        leading shape with trailing width ``out_dim``.
        """
        return _apply_readout_jet_from_layers(self._layer_specs(), hidden_jet)

    def _point_jet(self, xi: Array, order: int) -> Array:
        """Single-point multivariate jet, shape ``(M, out_dim)``.

        Default: hidden jet plus the live affine readout. Subclasses / wrappers
        that wrap the network (for example the hard-constraint ansatz
        ``u = g + b * net``) override this so every readout below stays exact
        and closed form. Twin of
        :meth:`omnibias.torch.architectures.pinn._JetMLPCore._point_jet`.
        """
        return self._apply_readout_jet(self._point_hidden_jet(xi, order))

    def _check_fastpath(self, max_order: int) -> None:
        """Reject activations without a closed-form tower up to ``max_order``."""
        _check_layer_fastpaths(self._layer_specs(), max_order)

    def value(self, x: Array) -> Array:
        """Plain network value ``u(x)``, shape ``(..., out_dim)``."""
        return _value_from_layers(self._layer_specs(), x)

    def __call__(self, x: Array) -> Array:
        return self.value(x)

    def jet(self, x: Array, order: int) -> Array:
        """Batched multivariate jet, shape ``(B, M, out_dim)``."""
        out: Array = jax.vmap(lambda xi: self._point_jet(xi, order))(x)
        return out

    def gradient(self, x: Array) -> Array:
        """Exact input gradient ``d u / d x_i``, shape ``(B, in_dim, out_dim)``."""
        dim = self.in_dim
        out: Array = jax.vmap(
            lambda xi: jet_gradient(self._point_jet(xi, 1), dim, 1)
        )(x)
        return out

    def hessian(self, x: Array) -> Array:
        """Exact input Hessian, shape ``(B, in_dim, in_dim, out_dim)``."""
        dim = self.in_dim
        out: Array = jax.vmap(
            lambda xi: jet_hessian(self._point_jet(xi, 2), dim, 2)
        )(x)
        return out

    def value_grad_hessian(self, x: Array) -> tuple[Array, Array, Array]:
        """One jet -> ``(value, gradient, Hessian)`` for 2nd-order PDE residuals."""
        dim = self.in_dim

        def f(xi: Array) -> tuple[Array, Array, Array]:
            j = self._point_jet(xi, 2)
            return j[0], jet_gradient(j, dim, 2), jet_hessian(j, dim, 2)

        res = jax.vmap(f)(x)
        value_b: Array = res[0]
        grad_b: Array = res[1]
        hess_b: Array = res[2]
        return value_b, grad_b, hess_b

    def partials(self, x: Array, order: int) -> dict[tuple[int, ...], Array]:
        """All raw partials ``{alpha: D^alpha u(x)}`` to total ``order`` (``(B, out_dim)``)."""
        return _partials_from_jet(self.jet(x, order), self.in_dim, order)
Other public import paths
  • omnibias.jax.architectures.JetMLP
  • omnibias.jax.architectures.pinn.JetMLP
FUNCTION

make_fourier_feature_mlp​

omnibias.jax.architectures.make_fourier_feature_mlpSource ↗
make_fourier_feature_mlp(in_dim: int, num_features: int=64, hidden: int=64, out_dim: int=1, depth: int=3, base: str | JaxActivationSpec='tanh', *, frequency_scale: float | Sequence[float]=1.0, seed: int=0, weight_init_scale: float=1.0, dtype: Any=jnp.float64) -> FourierFeatureMLP

Build a randomly-initialised FourierFeatureMLP.

The frequency matrix is B ~ N(0, (2 pi * scale)^2) per band, concatenated across frequency_scale for a multi-scale encoding; the body is Glorot-ish like make_jet_mlp. depth=0 gives a pure random-Fourier-feature model.

Parameters

NameType & defaultContract
in_dimpositional-or-keywordintRequiredSee the operation contract and implementation below.
num_featurespositional-or-keywordintDefault: 64See the operation contract and implementation below.
hiddenpositional-or-keywordintDefault: 64See the operation contract and implementation below.
out_dimpositional-or-keywordintDefault: 1See the operation contract and implementation below.
depthpositional-or-keywordintDefault: 3See the operation contract and implementation below.
basepositional-or-keywordstr | JaxActivationSpecDefault: 'tanh'See the operation contract and implementation below.
frequency_scalekeyword-onlyfloat | Sequence[float]Default: 1.0See the operation contract and implementation below.
seedkeyword-onlyintDefault: 0See the operation contract and implementation below.
weight_init_scalekeyword-onlyfloatDefault: 1.0See the operation contract and implementation below.
dtypekeyword-onlyAnyDefault: jnp.float64See the operation contract and implementation below.
ReturnsFourierFeatureMLP
Explicit validation & failure cases
  • When in_dim < 1, raises ValueError(f'in_dim must be >= 1, got {in_dim}').
  • When num_features < 1, raises ValueError(f'num_features must be >= 1, got {num_features}').
  • When hidden < 1, raises ValueError(f'hidden must be >= 1, got {hidden}').
  • When out_dim < 1, raises ValueError(f'out_dim must be >= 1, got {out_dim}').
  • When depth < 0, raises ValueError(f'depth (hidden layers after encoding) must be >= 0, got {depth}').

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · fourier value equals jet row0

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_fourier_value_equals_jet_row0() -> None:
    net = make_fourier_feature_mlp(2, num_features=8, hidden=16, depth=2, seed=1)
    x = _x(2)
    jet = net.jet(x, 2)
    assert jnp.allclose(jet[:, 0, :], net.value(x), atol=1e-13)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_fourier_value_equals_jet_row0" -q
Regression example · fourier jit compatible

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_fourier_jit_compatible() -> None:
    net = make_fourier_feature_mlp(2, num_features=6, hidden=10, depth=2, seed=8)
    x = _x(9, b=4)
    g_jit = jax.jit(lambda n, xx: n.gradient(xx))(net, x)
    assert jnp.allclose(g_jit, net.gradient(x), atol=1e-12)
python -m pytest packages/omnibias-jax/tests/test_spectral_pinn.py -k test_fourier_jit_compatible -q
Read the implementation
def make_fourier_feature_mlp(
    in_dim: int,
    num_features: int = 64,
    hidden: int = 64,
    out_dim: int = 1,
    depth: int = 3,
    base: str | JaxActivationSpec = "tanh",
    *,
    frequency_scale: float | Sequence[float] = 1.0,
    seed: int = 0,
    weight_init_scale: float = 1.0,
    dtype: Any = jnp.float64,
) -> FourierFeatureMLP:
    """Build a randomly-initialised :class:`FourierFeatureMLP`.

    The frequency matrix is ``B ~ N(0, (2 pi * scale)^2)`` per band, concatenated across
    ``frequency_scale`` for a multi-scale encoding; the body is Glorot-ish like
    :func:`make_jet_mlp`. ``depth=0`` gives a pure random-Fourier-feature model.
    """
    if in_dim < 1:
        raise ValueError(f"in_dim must be >= 1, got {in_dim}")
    if num_features < 1:
        raise ValueError(f"num_features must be >= 1, got {num_features}")
    if hidden < 1:
        raise ValueError(f"hidden must be >= 1, got {hidden}")
    if out_dim < 1:
        raise ValueError(f"out_dim must be >= 1, got {out_dim}")
    if depth < 0:
        raise ValueError(f"depth (hidden layers after encoding) must be >= 0, got {depth}")
    scales = _as_scales(frequency_scale)
    spec = get_activation(base)
    key = jax.random.PRNGKey(seed)

    bands: list[Array] = []
    for s in scales:
        key, bk = jax.random.split(key)
        bands.append(jax.random.normal(bk, (num_features, in_dim), dtype=dtype) * (2.0 * math.pi * s))
    b_mat = jnp.concatenate(bands, axis=0)  # (F_total, in_dim)
    f_total = int(b_mat.shape[0])
    w_ff = jnp.concatenate([b_mat, b_mat], axis=0)  # (2 F_total, in_dim)
    b_ff = jnp.concatenate(
        [jnp.full((f_total,), 0.5 * math.pi, dtype=dtype), jnp.zeros((f_total,), dtype=dtype)]
    )

    weights: list[Array] = []
    biases: list[Array] = []
    prev = 2 * f_total
    dims = [hidden] * depth + [out_dim]
    for d in dims:
        key, wk = jax.random.split(key)
        scale = weight_init_scale / math.sqrt(prev)
        weights.append(jax.random.normal(wk, (d, prev), dtype=dtype) * scale)
        biases.append(jnp.zeros((d,), dtype=dtype))
        prev = d
    return FourierFeatureMLP(
        w_ff=w_ff,
        b_ff=b_ff,
        weights=tuple(weights),
        biases=tuple(biases),
        base_spec=spec,
        in_dim=in_dim,
        out_dim=out_dim,
        num_features=num_features,
        scales=scales,
    )
Other public import paths
  • omnibias.jax.architectures.make_fourier_feature_mlp
  • omnibias.jax.architectures.pinn.make_fourier_feature_mlp
FUNCTION

make_jet_mlp​

omnibias.jax.architectures.make_jet_mlpSource ↗
make_jet_mlp(in_dim: int, hidden: int, out_dim: int=1, depth: int=3, activation: str | JaxActivationSpec='tanh', *, seed: int=0, weight_init_scale: float=1.0, dtype: Any=jnp.float64) -> JetMLP

Build a randomly-initialised JetMLP (Glorot-ish scaled normals).

Parameters

NameType & defaultContract
in_dimpositional-or-keywordintRequiredSee the operation contract and implementation below.
hiddenpositional-or-keywordintRequiredSee the operation contract and implementation below.
out_dimpositional-or-keywordintDefault: 1See the operation contract and implementation below.
depthpositional-or-keywordintDefault: 3See the operation contract and implementation below.
activationpositional-or-keywordstr | JaxActivationSpecDefault: 'tanh'See the operation contract and implementation below.
seedkeyword-onlyintDefault: 0See the operation contract and implementation below.
weight_init_scalekeyword-onlyfloatDefault: 1.0See the operation contract and implementation below.
dtypekeyword-onlyAnyDefault: jnp.float64See the operation contract and implementation below.
ReturnsJetMLP
Explicit validation & failure cases
  • When in_dim < 1 or hidden < 1 or out_dim < 1, raises ValueError('in_dim, hidden and out_dim must all be >= 1').
  • When depth < 1, raises ValueError(f'depth (number of hidden layers) must be >= 1, got {depth}').

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · depth property

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_depth_property() -> None:
    net = make_jet_mlp(2, 8, 1, depth=3, seed=0)
    assert net.depth == 3
    assert len(net.weights) == 4  # 3 hidden + 1 readout
python -m pytest "packages/omnibias-jax/tests/test_jet_pinn.py::test_depth_property" -q
Regression example · value equals jet row0

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_value_equals_jet_row0() -> None:
    net = make_jet_mlp(2, 16, 1, depth=3, seed=1)
    x = _x(2)
    jet = net.jet(x, 2)
    assert jnp.allclose(jet[:, 0, :], net.value(x), atol=1e-14)
python -m pytest packages/omnibias-jax/tests/test_jet_pinn.py -k test_value_equals_jet_row0 -q
Read the implementation
def make_jet_mlp(
    in_dim: int,
    hidden: int,
    out_dim: int = 1,
    depth: int = 3,
    activation: str | JaxActivationSpec = "tanh",
    *,
    seed: int = 0,
    weight_init_scale: float = 1.0,
    dtype: Any = jnp.float64,
) -> JetMLP:
    """Build a randomly-initialised :class:`JetMLP` (Glorot-ish scaled normals)."""
    if in_dim < 1 or hidden < 1 or out_dim < 1:
        raise ValueError("in_dim, hidden and out_dim must all be >= 1")
    if depth < 1:
        raise ValueError(f"depth (number of hidden layers) must be >= 1, got {depth}")
    spec = get_activation(activation)
    key = jax.random.PRNGKey(seed)
    dims = [hidden] * depth + [out_dim]
    weights: list[Array] = []
    biases: list[Array] = []
    prev = in_dim
    for d in dims:
        key, wk = jax.random.split(key)
        scale = weight_init_scale / math.sqrt(prev)
        weights.append(jax.random.normal(wk, (d, prev), dtype=dtype) * scale)
        biases.append(jnp.zeros((d,), dtype=dtype))
        prev = d
    return JetMLP(
        weights=tuple(weights), biases=tuple(biases), spec=spec, in_dim=in_dim, out_dim=out_dim
    )
Other public import paths
  • omnibias.jax.architectures.make_jet_mlp
  • omnibias.jax.architectures.pinn.make_jet_mlp
FUNCTION

make_siren​

omnibias.jax.architectures.make_sirenSource ↗
make_siren(in_dim: int, hidden: int, out_dim: int=1, depth: int=3, *, omega_0: float=30.0, seed: int=0, dtype: Any=jnp.float64) -> JetMLP

Build a SIREN (Sitzmann et al. 2020) as an omnibias JetMLP.

mathematically equivalent twin of omnibias.torch.architectures.pinn.make_siren: a sin-activation MLP whose first-layer frequency is scaled by omega_0 (folded into its weights), with weights U(-1/fan_in, 1/fan_in) on the first layer and U(-sqrt(6/fan_in)/omega_0, +...) thereafter and zero biases. Every input derivative is exact for all orders via sin^{(n)}(z) = sin(z + n pi/2).

Backend scope: this identifies the corresponding mathematical construction. It does not guarantee bitwise-equal floating-point results across devices, compilers, dtypes, or backend versions. Validate the selected path with an appropriate absolute and relative tolerance.

Parameters

NameType & defaultContract
in_dimpositional-or-keywordintRequiredSee the operation contract and implementation below.
hiddenpositional-or-keywordintRequiredSee the operation contract and implementation below.
out_dimpositional-or-keywordintDefault: 1See the operation contract and implementation below.
depthpositional-or-keywordintDefault: 3See the operation contract and implementation below.
omega_0keyword-onlyfloatDefault: 30.0See the operation contract and implementation below.
seedkeyword-onlyintDefault: 0See the operation contract and implementation below.
dtypekeyword-onlyAnyDefault: jnp.float64See the operation contract and implementation below.
ReturnsJetMLP
Explicit validation & failure cases
  • When in_dim < 1 or hidden < 1 or out_dim < 1, raises ValueError('in_dim, hidden and out_dim must all be >= 1').
  • When depth < 1, raises ValueError(f'depth (number of hidden layers) must be >= 1, got {depth}').
  • When omega_0 <= 0.0, raises ValueError(f'omega_0 must be > 0, got {omega_0}').

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · make siren validation

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_make_siren_validation() -> None:
    with pytest.raises(ValueError):
        make_siren(1, hidden=8, depth=0)
    with pytest.raises(ValueError):
        make_siren(1, hidden=8, depth=2, omega_0=0.0)
python -m pytest "packages/omnibias-jax/tests/test_spectral_pinn.py::test_make_siren_validation" -q
Regression example · siren gradient matches autograd

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_siren_gradient_matches_autograd() -> None:
    net = make_siren(1, hidden=24, depth=3, omega_0=10.0, seed=2)
    x = _x(3, b=6, d=1)
    g = net.gradient(x).reshape(-1)
    g_ad = jax.vmap(jax.jacfwd(_val(net)))(x).reshape(-1)
    assert jnp.allclose(g, g_ad, atol=1e-10)
python -m pytest packages/omnibias-jax/tests/test_spectral_pinn.py -k test_siren_gradient_matches_autograd -q
Read the implementation
def make_siren(
    in_dim: int,
    hidden: int,
    out_dim: int = 1,
    depth: int = 3,
    *,
    omega_0: float = 30.0,
    seed: int = 0,
    dtype: Any = jnp.float64,
) -> JetMLP:
    r"""Build a SIREN (Sitzmann et al. 2020) as an omnibias :class:`JetMLP`.

    Bit-identical twin of :func:`omnibias.torch.architectures.pinn.make_siren`: a
    ``sin``-activation MLP whose first-layer frequency is scaled by ``omega_0`` (folded
    into its weights), with weights ``U(-1/fan_in, 1/fan_in)`` on the first layer and
    ``U(-sqrt(6/fan_in)/omega_0, +...)`` thereafter and zero biases. Every input
    derivative is exact for all orders via ``sin^{(n)}(z) = sin(z + n pi/2)``.
    """
    if in_dim < 1 or hidden < 1 or out_dim < 1:
        raise ValueError("in_dim, hidden and out_dim must all be >= 1")
    if depth < 1:
        raise ValueError(f"depth (number of hidden layers) must be >= 1, got {depth}")
    if omega_0 <= 0.0:
        raise ValueError(f"omega_0 must be > 0, got {omega_0}")
    spec = get_activation("sin")
    key = jax.random.PRNGKey(seed)
    dims = [hidden] * depth + [out_dim]
    weights: list[Array] = []
    biases: list[Array] = []
    prev = in_dim
    for i, d in enumerate(dims):
        key, wk = jax.random.split(key)
        if i == 0:
            bound = 1.0 / prev
            w = jax.random.uniform(wk, (d, prev), dtype=dtype, minval=-bound, maxval=bound)
            w = w * omega_0  # fold omega_0 into the first-layer frequency
        else:
            bound = math.sqrt(6.0 / prev) / omega_0
            w = jax.random.uniform(wk, (d, prev), dtype=dtype, minval=-bound, maxval=bound)
        weights.append(w)
        biases.append(jnp.zeros((d,), dtype=dtype))
        prev = d
    return JetMLP(
        weights=tuple(weights), biases=tuple(biases), spec=spec, in_dim=in_dim, out_dim=out_dim
    )
Other public import paths
  • omnibias.jax.architectures.make_siren
  • omnibias.jax.architectures.pinn.make_siren