Skip to main content

omnibias.torch.blocks.conv

0.5.0rc1Release candidatePython >=3.10Apache-2.0

PyTorch activation derivatives, trainable operator layers, network jets, and direct differential-operator contractions.

import omnibias.torch.blocks.conv
Module contract & mathematical conventions

Operator-typed convolution layers: cmbConv1d, cmbConv2d.

Each is a standard nn.Conv*d followed by an OperatorBlock applied per output channel. The activation operator role determines the *kind* of feature each kernel is encouraged to learn:

  • op="grad" + base="tanh" -> Sobel-like edge kernels.
  • op="laplacian" + base="gaussian" -> Laplacian-of-Gaussian blob kernels.
  • op="derivative" + block_kwargs={"derivative_order": n} -> arbitrary closed-form nth activation derivative kernels.
  • op="band" + base="gaussian" -> Difference-of-Gaussian scale-space kernels.
  • op="integral" + base="gaussian" -> erf-window scale integrals.
  • op="identity" -> standard activation, drop-in for the base nonlinearity.

The OperatorBlock works on channel-last tensors, so we permute (B, C, ...) <-> (B, ..., C) around it.

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

AnalyticGaussianConv1d​

omnibias.torch.AnalyticGaussianConv1dSource ↗
class AnalyticGaussianConv1d(_AnalyticGaussianConvBase)

Depthwise 1-D convolution with an exact, continuous-scale Gaussian kernel.

The per-channel kernel taps are built in closed form from the learnable scale sigma via analytic_gaussian_taps (exact cell integration through the erf antiderivative / Gaussian derivative tower), so the layer is anti-aliased, sampling-free, and differentiable end-to-end in sigma. derivative_order=0 is a Gaussian blur; order=1 a derivative-of-Gaussian edge filter; order=2 a second-derivative (Laplacian-of-Gaussian in 1-D).

Layout: (B, channels, L) -> (B, channels, L_out) (depthwise/groups).

Parameters

NameType & defaultContract
channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
kernel_sizepositional-or-keywordintRequiredSee the operation contract and implementation below.
derivative_orderkeyword-onlyintDefault: 0See the operation contract and implementation below.
sigma_initkeyword-onlyfloatDefault: 1.0See the operation contract and implementation below.
learnable_sigmakeyword-onlyboolDefault: TrueSee the operation contract and implementation below.
stridekeyword-onlyintDefault: 1See the operation contract and implementation below.
paddingkeyword-onlyint | strDefault: 'same'See the operation contract and implementation below.
Executed regression · frozen scale has no 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_frozen_scale_has_no_grad() -> None:
    layer = AnalyticGaussianConv1d(2, 7, sigma_init=1.0, learnable_sigma=False)
    assert not layer.sigma.requires_grad
    names = dict(layer.named_buffers())
    assert "sigma" in names
python -m pytest "packages/omnibias-torch/tests/test_analytic_gaussian_conv.py::test_frozen_scale_has_no_grad" -q
Regression example · gradient flows to continuous scale 2d

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_gradient_flows_to_continuous_scale_2d() -> None:
    layer = AnalyticGaussianConv2d(2, 5, derivative_order=(0, 0), sigma_init=1.0).double()
    x = torch.randn(2, 2, 9, 9, dtype=DT)
    (layer(x) ** 2).sum().backward()
    assert layer.sigma.grad is not None
    assert float(layer.sigma.grad.abs().sum()) > 0.0
python -m pytest packages/omnibias-torch/tests/test_analytic_gaussian_conv.py -k test_gradient_flows_to_continuous_scale_2d -q

Fields & methods

__init__method
__init__(self, channels: int, kernel_size: int, *, derivative_order: int=0, sigma_init: float=1.0, learnable_sigma: bool=True, stride: int=1, padding: int | str='same') -> None

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

Parameters

NameType & defaultContract
channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
kernel_sizepositional-or-keywordintRequiredSee the operation contract and implementation below.
derivative_orderkeyword-onlyintDefault: 0See the operation contract and implementation below.
sigma_initkeyword-onlyfloatDefault: 1.0See the operation contract and implementation below.
learnable_sigmakeyword-onlyboolDefault: TrueSee the operation contract and implementation below.
stridekeyword-onlyintDefault: 1See the operation contract and implementation below.
paddingkeyword-onlyint | strDefault: 'same'See the operation contract and implementation below.

Returns: None

Executed regression · frozen scale has no 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_frozen_scale_has_no_grad() -> None:
    layer = AnalyticGaussianConv1d(2, 7, sigma_init=1.0, learnable_sigma=False)
    assert not layer.sigma.requires_grad
    names = dict(layer.named_buffers())
    assert "sigma" in names
python -m pytest "packages/omnibias-torch/tests/test_analytic_gaussian_conv.py::test_frozen_scale_has_no_grad" -q
Method implementation
    def __init__(
        self,
        channels: int,
        kernel_size: int,
        *,
        derivative_order: int = 0,
        sigma_init: float = 1.0,
        learnable_sigma: bool = True,
        stride: int = 1,
        padding: int | str = "same",
    ) -> None:
        super().__init__(channels, sigma_init, learnable_sigma)
        self.kernel_size = kernel_size
        self.derivative_order = derivative_order
        self.stride = stride
        self.padding = padding
View source ↗
forwardmethod
forward(self, x: Tensor) -> Tensor

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

Parameters

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

Returns: Tensor

Executed regression · gradient flows to continuous scale 1d

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_gradient_flows_to_continuous_scale_1d() -> None:
    layer = AnalyticGaussianConv1d(2, 7, sigma_init=1.3).double()
    x = torch.randn(4, 2, 20, dtype=DT)
    (layer(x) ** 2).sum().backward()
    assert layer.sigma.grad is not None
    assert torch.isfinite(layer.sigma.grad).all()
    assert float(layer.sigma.grad.abs().sum()) > 0.0
python -m pytest "packages/omnibias-torch/tests/test_analytic_gaussian_conv.py::test_gradient_flows_to_continuous_scale_1d" -q
Method implementation
    def forward(self, x: Tensor) -> Tensor:
        taps = analytic_gaussian_taps(self.kernel_size, self._safe_sigma(), self.derivative_order)
        weight = taps.unsqueeze(1).to(x.dtype)  # (C, 1, K) depthwise
        return F.conv1d(x, weight, stride=self.stride, padding=self.padding, groups=self.channels)
View source ↗
extra_reprmethod
extra_repr(self) -> str

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

Returns: str

Method implementation
    def extra_repr(self) -> str:
        return (
            f"channels={self.channels}, kernel_size={self.kernel_size}, "
            f"derivative_order={self.derivative_order}"
        )
View source ↗
kernel_sizeattribute
kernel_size: int = kernel_size

Public instance attribute assigned by __init__. The source assignment is kernel_size = kernel_size; it describes instance state, not a literal constructor default.

View source ↗
derivative_orderattribute
derivative_order: int = derivative_order

Public instance attribute assigned by __init__. The source assignment is derivative_order = derivative_order; it describes instance state, not a literal constructor default.

View source ↗
strideattribute
stride: int = stride

Public instance attribute assigned by __init__. The source assignment is stride = stride; it describes instance state, not a literal constructor default.

View source ↗
paddingattribute
padding: int | str = padding

Public instance attribute assigned by __init__. The source assignment is padding = padding; it describes instance state, not a literal constructor default.

View source ↗
Read the implementation
class AnalyticGaussianConv1d(_AnalyticGaussianConvBase):
    r"""Depthwise 1-D convolution with an exact, continuous-scale Gaussian kernel.

    The per-channel kernel taps are built in closed form from the learnable scale
    ``sigma`` via :func:`analytic_gaussian_taps` (exact cell integration through
    the ``erf`` antiderivative / Gaussian derivative tower), so the layer is
    anti-aliased, sampling-free, and differentiable end-to-end in ``sigma``.
    ``derivative_order=0`` is a Gaussian blur; ``order=1`` a derivative-of-Gaussian
    edge filter; ``order=2`` a second-derivative (Laplacian-of-Gaussian in 1-D).

    Layout: ``(B, channels, L) -> (B, channels, L_out)`` (depthwise/groups).
    """

    def __init__(
        self,
        channels: int,
        kernel_size: int,
        *,
        derivative_order: int = 0,
        sigma_init: float = 1.0,
        learnable_sigma: bool = True,
        stride: int = 1,
        padding: int | str = "same",
    ) -> None:
        super().__init__(channels, sigma_init, learnable_sigma)
        self.kernel_size = kernel_size
        self.derivative_order = derivative_order
        self.stride = stride
        self.padding = padding

    def forward(self, x: Tensor) -> Tensor:
        taps = analytic_gaussian_taps(self.kernel_size, self._safe_sigma(), self.derivative_order)
        weight = taps.unsqueeze(1).to(x.dtype)  # (C, 1, K) depthwise
        return F.conv1d(x, weight, stride=self.stride, padding=self.padding, groups=self.channels)

    def extra_repr(self) -> str:
        return (
            f"channels={self.channels}, kernel_size={self.kernel_size}, "
            f"derivative_order={self.derivative_order}"
        )
Other public import paths
  • omnibias.torch.AnalyticGaussianConv1d
  • omnibias.torch.blocks.AnalyticGaussianConv1d
  • omnibias.torch.blocks.conv.AnalyticGaussianConv1d
CLASS

AnalyticGaussianConv2d​

omnibias.torch.AnalyticGaussianConv2dSource ↗
class AnalyticGaussianConv2d(_AnalyticGaussianConvBase)

Depthwise 2-D separable analytic Gaussian / derivative-of-Gaussian conv.

The isotropic Gaussian is separable, so the 2-D kernel is the outer product of two 1-D analytic_gaussian_taps profiles (one per axis). derivative_order is (n_y, n_x): (0, 0) is an isotropic blur, (1, 0) / (0, 1) are gradient-of-Gaussian filters, and a Laplacian-of-Gaussian is the sum of a (2, 0) and a (0, 2) layer. Learnable continuous scale sigma.

Layout: (B, channels, H, W) -> (B, channels, H_out, W_out) (depthwise).

Parameters

NameType & defaultContract
channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
kernel_sizepositional-or-keywordint | tuple[int, int]RequiredSee the operation contract and implementation below.
derivative_orderkeyword-onlyint | tuple[int, int]Default: 0See the operation contract and implementation below.
sigma_initkeyword-onlyfloatDefault: 1.0See the operation contract and implementation below.
learnable_sigmakeyword-onlyboolDefault: TrueSee the operation contract and implementation below.
stridekeyword-onlyint | tuple[int, int]Default: 1See the operation contract and implementation below.
paddingkeyword-onlyint | strDefault: 'same'See the operation contract and implementation below.
Executed regression · gradient flows to continuous scale 2d

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_gradient_flows_to_continuous_scale_2d() -> None:
    layer = AnalyticGaussianConv2d(2, 5, derivative_order=(0, 0), sigma_init=1.0).double()
    x = torch.randn(2, 2, 9, 9, dtype=DT)
    (layer(x) ** 2).sum().backward()
    assert layer.sigma.grad is not None
    assert float(layer.sigma.grad.abs().sum()) > 0.0
python -m pytest "packages/omnibias-torch/tests/test_analytic_gaussian_conv.py::test_gradient_flows_to_continuous_scale_2d" -q
Regression example · conv2d is separable outer product

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_conv2d_is_separable_outer_product() -> None:
    rng = np.random.default_rng(1)
    c, k = 3, 5
    layer = AnalyticGaussianConv2d(c, k, derivative_order=(1, 0), sigma_init=1.1).double()
    x = torch.tensor(rng.standard_normal((2, c, 10, 11)), dtype=DT)
    out = layer(x).detach().numpy()
    sigma = layer.sigma.detach()
    ty = analytic_gaussian_taps(k, sigma, 1)  # (C, Kh)
    tx = analytic_gaussian_taps(k, sigma, 0)  # (C, Kw)
    ker = (ty.unsqueeze(-1) * tx.unsqueeze(-2)).numpy()  # (C, Kh, Kw)
    ref = _corr2d_same(x.numpy(), ker)
    np.testing.assert_allclose(out, ref, rtol=1e-12, atol=1e-12)
python -m pytest packages/omnibias-torch/tests/test_analytic_gaussian_conv.py -k test_conv2d_is_separable_outer_product -q

Fields & methods

__init__method
__init__(self, channels: int, kernel_size: int | tuple[int, int], *, derivative_order: int | tuple[int, int]=0, sigma_init: float=1.0, learnable_sigma: bool=True, stride: int | tuple[int, int]=1, padding: int | str='same') -> None

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

Parameters

NameType & defaultContract
channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
kernel_sizepositional-or-keywordint | tuple[int, int]RequiredSee the operation contract and implementation below.
derivative_orderkeyword-onlyint | tuple[int, int]Default: 0See the operation contract and implementation below.
sigma_initkeyword-onlyfloatDefault: 1.0See the operation contract and implementation below.
learnable_sigmakeyword-onlyboolDefault: TrueSee the operation contract and implementation below.
stridekeyword-onlyint | tuple[int, int]Default: 1See the operation contract and implementation below.
paddingkeyword-onlyint | strDefault: 'same'See the operation contract and implementation below.

Returns: None

Executed regression · gradient flows to continuous scale 2d

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_gradient_flows_to_continuous_scale_2d() -> None:
    layer = AnalyticGaussianConv2d(2, 5, derivative_order=(0, 0), sigma_init=1.0).double()
    x = torch.randn(2, 2, 9, 9, dtype=DT)
    (layer(x) ** 2).sum().backward()
    assert layer.sigma.grad is not None
    assert float(layer.sigma.grad.abs().sum()) > 0.0
python -m pytest "packages/omnibias-torch/tests/test_analytic_gaussian_conv.py::test_gradient_flows_to_continuous_scale_2d" -q
Method implementation
    def __init__(
        self,
        channels: int,
        kernel_size: int | tuple[int, int],
        *,
        derivative_order: int | tuple[int, int] = 0,
        sigma_init: float = 1.0,
        learnable_sigma: bool = True,
        stride: int | tuple[int, int] = 1,
        padding: int | str = "same",
    ) -> None:
        super().__init__(channels, sigma_init, learnable_sigma)
        kh, kw = (kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size
        ny, nx = (
            (derivative_order, derivative_order)
            if isinstance(derivative_order, int)
            else derivative_order
        )
        self.kernel_size = (kh, kw)
        self.derivative_order = (ny, nx)
        self.stride = stride
        self.padding = padding
View source ↗
forwardmethod
forward(self, x: Tensor) -> Tensor

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

Parameters

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

Returns: Tensor

Executed regression · gradient flows to continuous scale 2d

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_gradient_flows_to_continuous_scale_2d() -> None:
    layer = AnalyticGaussianConv2d(2, 5, derivative_order=(0, 0), sigma_init=1.0).double()
    x = torch.randn(2, 2, 9, 9, dtype=DT)
    (layer(x) ** 2).sum().backward()
    assert layer.sigma.grad is not None
    assert float(layer.sigma.grad.abs().sum()) > 0.0
python -m pytest "packages/omnibias-torch/tests/test_analytic_gaussian_conv.py::test_gradient_flows_to_continuous_scale_2d" -q
Method implementation
    def forward(self, x: Tensor) -> Tensor:
        sigma = self._safe_sigma()
        kh, kw = self.kernel_size
        ny, nx = self.derivative_order
        ty = analytic_gaussian_taps(kh, sigma, ny)  # (C, Kh)
        tx = analytic_gaussian_taps(kw, sigma, nx)  # (C, Kw)
        kernel2d = ty.unsqueeze(-1) * tx.unsqueeze(-2)  # (C, Kh, Kw)
        weight = kernel2d.unsqueeze(1).to(x.dtype)  # (C, 1, Kh, Kw)
        return F.conv2d(x, weight, stride=self.stride, padding=self.padding, groups=self.channels)
View source ↗
extra_reprmethod
extra_repr(self) -> str

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

Returns: str

Method implementation
    def extra_repr(self) -> str:
        return (
            f"channels={self.channels}, kernel_size={self.kernel_size}, "
            f"derivative_order={self.derivative_order}"
        )
View source ↗
kernel_sizeattribute
kernel_size = (kh, kw)

Public instance attribute assigned by __init__. The source assignment is kernel_size = (kh, kw); it describes instance state, not a literal constructor default.

View source ↗
derivative_orderattribute
derivative_order = (ny, nx)

Public instance attribute assigned by __init__. The source assignment is derivative_order = (ny, nx); it describes instance state, not a literal constructor default.

View source ↗
strideattribute
stride: int | tuple[int, int] = stride

Public instance attribute assigned by __init__. The source assignment is stride = stride; it describes instance state, not a literal constructor default.

View source ↗
paddingattribute
padding: int | str = padding

Public instance attribute assigned by __init__. The source assignment is padding = padding; it describes instance state, not a literal constructor default.

View source ↗
Read the implementation
class AnalyticGaussianConv2d(_AnalyticGaussianConvBase):
    r"""Depthwise 2-D separable analytic Gaussian / derivative-of-Gaussian conv.

    The isotropic Gaussian is separable, so the 2-D kernel is the outer product of
    two 1-D :func:`analytic_gaussian_taps` profiles (one per axis). ``derivative_order``
    is ``(n_y, n_x)``: ``(0, 0)`` is an isotropic blur, ``(1, 0)`` / ``(0, 1)`` are
    gradient-of-Gaussian filters, and a Laplacian-of-Gaussian is the sum of a
    ``(2, 0)`` and a ``(0, 2)`` layer. Learnable continuous scale ``sigma``.

    Layout: ``(B, channels, H, W) -> (B, channels, H_out, W_out)`` (depthwise).
    """

    def __init__(
        self,
        channels: int,
        kernel_size: int | tuple[int, int],
        *,
        derivative_order: int | tuple[int, int] = 0,
        sigma_init: float = 1.0,
        learnable_sigma: bool = True,
        stride: int | tuple[int, int] = 1,
        padding: int | str = "same",
    ) -> None:
        super().__init__(channels, sigma_init, learnable_sigma)
        kh, kw = (kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size
        ny, nx = (
            (derivative_order, derivative_order)
            if isinstance(derivative_order, int)
            else derivative_order
        )
        self.kernel_size = (kh, kw)
        self.derivative_order = (ny, nx)
        self.stride = stride
        self.padding = padding

    def forward(self, x: Tensor) -> Tensor:
        sigma = self._safe_sigma()
        kh, kw = self.kernel_size
        ny, nx = self.derivative_order
        ty = analytic_gaussian_taps(kh, sigma, ny)  # (C, Kh)
        tx = analytic_gaussian_taps(kw, sigma, nx)  # (C, Kw)
        kernel2d = ty.unsqueeze(-1) * tx.unsqueeze(-2)  # (C, Kh, Kw)
        weight = kernel2d.unsqueeze(1).to(x.dtype)  # (C, 1, Kh, Kw)
        return F.conv2d(x, weight, stride=self.stride, padding=self.padding, groups=self.channels)

    def extra_repr(self) -> str:
        return (
            f"channels={self.channels}, kernel_size={self.kernel_size}, "
            f"derivative_order={self.derivative_order}"
        )
Other public import paths
  • omnibias.torch.AnalyticGaussianConv2d
  • omnibias.torch.blocks.AnalyticGaussianConv2d
  • omnibias.torch.blocks.conv.AnalyticGaussianConv2d
FUNCTION

analytic_gaussian_taps​

omnibias.torch.analytic_gaussian_tapsSource ↗
analytic_gaussian_taps(kernel_size: int, sigma: Tensor, order: int=0) -> Tensor

Exact cell-integrated Gaussian / derivative-of-Gaussian kernel taps.

Returns taps of shape (*sigma.shape, kernel_size) for a continuous-scale Gaussian of standard deviation sigma (pixel units). Tap j is the *integral* of the (order-th derivative of the) unit-area Gaussian over the cell [j - 1/2, j + 1/2] -- exact, anti-aliased *area* sampling rather than point sampling:

w_j^{(0)} = \tfrac12\!\left[\operatorname{erf}\tfrac{j+1/2}{\sigma\sqrt2}
            - \operatorname{erf}\tfrac{j-1/2}{\sigma\sqrt2}\right],\qquad
w_j^{(n)} = \frac{g^{(n-1)}(b_j) - g^{(n-1)}(a_j)}{\sigma^{n}\sqrt{2\pi}},

with a_j = (j-1/2)/\sigma, b_j = (j+1/2)/\sigma and g(u)=e^{-u^2/2}. The order=0 smoother is the erf antiderivative (the gaussian spec.integral); order>=1 uses the closed-form Gaussian derivative tower (gaussian_nth_derivative), so derivative-of-Gaussian *is* the omnibias sigma tower. Differentiable in sigma -- a learnable continuous scale, no resampling.

Parameters

NameType & defaultContract
kernel_sizepositional-or-keywordintRequiredSee the operation contract and implementation below.
sigmapositional-or-keywordTensorRequiredSee the operation contract and implementation below.
orderpositional-or-keywordintDefault: 0See the operation contract and implementation below.
ReturnsTensor
Explicit validation & failure cases
  • When kernel_size < 1 or kernel_size % 2 == 0, raises ValueError(f'kernel_size must be a positive odd integer, got {kernel_size}').
  • When order < 0, raises ValueError(f'order must be >= 0, got {order}').

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

Executed regression · order1 is antisymmetric zero mean

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_order1_is_antisymmetric_zero_mean() -> None:
    taps = analytic_gaussian_taps(21, torch.tensor([1.3], dtype=DT), 1)[0]
    torch.testing.assert_close(taps, -taps.flip(0), rtol=1e-12, atol=1e-12)  # odd
    assert float(taps.sum()) == pytest.approx(0.0, abs=1e-12)
python -m pytest "packages/omnibias-torch/tests/test_analytic_gaussian_conv.py::test_order1_is_antisymmetric_zero_mean" -q
Regression example · order0 unit area and symmetry

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_order0_unit_area_and_symmetry() -> None:
    taps = analytic_gaussian_taps(41, torch.tensor([1.5], dtype=DT), 0)[0]
    assert float(taps.sum()) == pytest.approx(1.0, abs=1e-6)  # area -> 1 on a wide kernel
    torch.testing.assert_close(taps, taps.flip(0), rtol=1e-12, atol=1e-12)  # even
python -m pytest packages/omnibias-torch/tests/test_analytic_gaussian_conv.py -k test_order0_unit_area_and_symmetry -q
Read the implementation
def analytic_gaussian_taps(kernel_size: int, sigma: Tensor, order: int = 0) -> Tensor:
    r"""Exact cell-integrated Gaussian / derivative-of-Gaussian kernel taps.

    Returns taps of shape ``(*sigma.shape, kernel_size)`` for a continuous-scale
    Gaussian of standard deviation ``sigma`` (pixel units). Tap ``j`` is the
    *integral* of the (``order``-th derivative of the) unit-area Gaussian over the
    cell ``[j - 1/2, j + 1/2]`` -- exact, anti-aliased *area* sampling rather than
    point sampling:

    .. math::
        w_j^{(0)} = \tfrac12\!\left[\operatorname{erf}\tfrac{j+1/2}{\sigma\sqrt2}
                    - \operatorname{erf}\tfrac{j-1/2}{\sigma\sqrt2}\right],\qquad
        w_j^{(n)} = \frac{g^{(n-1)}(b_j) - g^{(n-1)}(a_j)}{\sigma^{n}\sqrt{2\pi}},

    with ``a_j = (j-1/2)/\sigma``, ``b_j = (j+1/2)/\sigma`` and ``g(u)=e^{-u^2/2}``.
    The ``order=0`` smoother is the ``erf`` antiderivative (the gaussian
    ``spec.integral``); ``order>=1`` uses the closed-form Gaussian derivative
    tower (:func:`gaussian_nth_derivative`), so derivative-of-Gaussian *is* the
    omnibias sigma tower. Differentiable in ``sigma`` -- a learnable continuous
    scale, no resampling.
    """
    if kernel_size < 1 or kernel_size % 2 == 0:
        raise ValueError(f"kernel_size must be a positive odd integer, got {kernel_size}")
    if order < 0:
        raise ValueError(f"order must be >= 0, got {order}")
    offsets = torch.arange(
        -(kernel_size // 2), kernel_size // 2 + 1, dtype=sigma.dtype, device=sigma.device
    )
    sig = sigma.unsqueeze(-1)
    a = (offsets - _HALF) / sig
    b = (offsets + _HALF) / sig
    if order == 0:
        return _HALF * (torch.erf(b / _SQRT_2) - torch.erf(a / _SQRT_2))
    gm = gaussian_nth_derivative(b, order - 1) - gaussian_nth_derivative(a, order - 1)
    return gm * (_INV_SQRT_2PI / sig.pow(order))
Other public import paths
  • omnibias.torch.analytic_gaussian_taps
  • omnibias.torch.blocks.analytic_gaussian_taps
  • omnibias.torch.blocks.conv.analytic_gaussian_taps
CLASS

cmbConv1d​

omnibias.torch.cmbConv1dSource ↗
class cmbConv1d(_CmbConvBase)

nn.Conv1d + per-channel OperatorBlock.

Layout: input (B, in_channels, L) -> output (B, out_channels, L_out).

Parameters

NameType & defaultContract
in_channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
out_channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
kernel_sizepositional-or-keywordintRequiredSee the operation contract and implementation below.
oppositional-or-keywordOpNameDefault: 'identity'See the operation contract and implementation below.
basepositional-or-keywordstr | ActivationSpec[Tensor]Default: 'tanh'See the operation contract and implementation below.
stridepositional-or-keywordintDefault: 1See the operation contract and implementation below.
paddingpositional-or-keywordint | strDefault: 0See the operation contract and implementation below.
dilationpositional-or-keywordintDefault: 1See the operation contract and implementation below.
biaspositional-or-keywordboolDefault: TrueSee the operation contract and implementation below.
block_kwargspositional-or-keyworddict[str, Any] | NoneDefault: NoneSee the operation contract and implementation below.
Executed regression · cmbconv1d shape

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_cmbconv1d_shape() -> None:
    layer = cmbConv1d(2, 4, kernel_size=3, padding=1, op="grad", base="tanh")
    out = layer(torch.randn(1, 2, 16))
    assert out.shape == (1, 4, 16)
python -m pytest "packages/omnibias-torch/tests/test_blocks.py::test_cmbconv1d_shape" -q
Regression example · cmbconv1d uses default dtype

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_cmbconv1d_uses_default_dtype(torch_default_float64) -> None:
    conv = cmbConv1d(
        in_channels=2, out_channels=4, kernel_size=3, op="grad", base="tanh"
    )
    assert conv.conv.weight.dtype == torch.float64
    assert conv.block.ombu.biases.dtype == torch.float64
python -m pytest packages/omnibias-torch/tests/test_audit_regressions.py -k test_cmbconv1d_uses_default_dtype -q

Fields & methods

__init__method
__init__(self, in_channels: int, out_channels: int, kernel_size: int, op: OpName='identity', base: str | ActivationSpec[Tensor]='tanh', stride: int=1, padding: int | str=0, dilation: int=1, bias: bool=True, block_kwargs: dict[str, Any] | None=None) -> None

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

Parameters

NameType & defaultContract
in_channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
out_channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
kernel_sizepositional-or-keywordintRequiredSee the operation contract and implementation below.
oppositional-or-keywordOpNameDefault: 'identity'See the operation contract and implementation below.
basepositional-or-keywordstr | ActivationSpec[Tensor]Default: 'tanh'See the operation contract and implementation below.
stridepositional-or-keywordintDefault: 1See the operation contract and implementation below.
paddingpositional-or-keywordint | strDefault: 0See the operation contract and implementation below.
dilationpositional-or-keywordintDefault: 1See the operation contract and implementation below.
biaspositional-or-keywordboolDefault: TrueSee the operation contract and implementation below.
block_kwargspositional-or-keyworddict[str, Any] | NoneDefault: NoneSee the operation contract and implementation below.

Returns: None

Executed regression · cmbconv1d shape

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_cmbconv1d_shape() -> None:
    layer = cmbConv1d(2, 4, kernel_size=3, padding=1, op="grad", base="tanh")
    out = layer(torch.randn(1, 2, 16))
    assert out.shape == (1, 4, 16)
python -m pytest "packages/omnibias-torch/tests/test_blocks.py::test_cmbconv1d_shape" -q
Method implementation
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size: int,
        op: OpName = "identity",
        base: str | ActivationSpec[Tensor] = "tanh",
        stride: int = 1,
        padding: int | str = 0,
        dilation: int = 1,
        bias: bool = True,
        block_kwargs: dict[str, Any] | None = None,
    ) -> None:
        super().__init__(op=op, base=base, out_channels=out_channels, block_kwargs=block_kwargs)
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.conv = nn.Conv1d(
            in_channels,
            out_channels,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            dilation=dilation,
            bias=bias,
        )
View source ↗
forwardmethod
forward(self, x: Tensor) -> Tensor

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

Parameters

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

Returns: Tensor

Executed regression · cmbconv1d shape

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_cmbconv1d_shape() -> None:
    layer = cmbConv1d(2, 4, kernel_size=3, padding=1, op="grad", base="tanh")
    out = layer(torch.randn(1, 2, 16))
    assert out.shape == (1, 4, 16)
python -m pytest "packages/omnibias-torch/tests/test_blocks.py::test_cmbconv1d_shape" -q
Method implementation
    def forward(self, x: Tensor) -> Tensor:
        z = self.conv(x)  # (B, out_channels, L_out)
        return self._apply_block_channel_last(z, channel_dim=1)
View source ↗
extra_reprmethod
extra_repr(self) -> str

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

Returns: str

Method implementation
    def extra_repr(self) -> str:
        return (
            f"in_channels={self.in_channels}, out_channels={self.out_channels}, "
            f"op={self.block.op!r}, base={self.block.base_name!r}"
        )
View source ↗
in_channelsattribute
in_channels: int = in_channels

Public instance attribute assigned by __init__. The source assignment is in_channels = in_channels; it describes instance state, not a literal constructor default.

View source ↗
out_channelsattribute
out_channels: int = out_channels

Public instance attribute assigned by __init__. The source assignment is out_channels = out_channels; it describes instance state, not a literal constructor default.

View source ↗
convattribute
conv = nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias)

Public instance attribute assigned by __init__. The source assignment is conv = nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias); it describes instance state, not a literal constructor default.

View source ↗
Read the implementation
class cmbConv1d(_CmbConvBase):
    """``nn.Conv1d`` + per-channel :class:`OperatorBlock`.

    Layout: input ``(B, in_channels, L)`` -> output ``(B, out_channels, L_out)``.
    """

    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size: int,
        op: OpName = "identity",
        base: str | ActivationSpec[Tensor] = "tanh",
        stride: int = 1,
        padding: int | str = 0,
        dilation: int = 1,
        bias: bool = True,
        block_kwargs: dict[str, Any] | None = None,
    ) -> None:
        super().__init__(op=op, base=base, out_channels=out_channels, block_kwargs=block_kwargs)
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.conv = nn.Conv1d(
            in_channels,
            out_channels,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            dilation=dilation,
            bias=bias,
        )

    def forward(self, x: Tensor) -> Tensor:
        z = self.conv(x)  # (B, out_channels, L_out)
        return self._apply_block_channel_last(z, channel_dim=1)

    def extra_repr(self) -> str:
        return (
            f"in_channels={self.in_channels}, out_channels={self.out_channels}, "
            f"op={self.block.op!r}, base={self.block.base_name!r}"
        )
Other public import paths
  • omnibias.torch.cmbConv1d
  • omnibias.torch.blocks.cmbConv1d
  • omnibias.torch.blocks.conv.cmbConv1d
CLASS

cmbConv2d​

omnibias.torch.cmbConv2dSource ↗
class cmbConv2d(_CmbConvBase)

nn.Conv2d + per-channel OperatorBlock.

Layout: input (B, in_channels, H, W) -> output (B, out_channels, H_out, W_out).

Parameters

NameType & defaultContract
in_channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
out_channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
kernel_sizepositional-or-keywordint | tuple[int, int]RequiredSee the operation contract and implementation below.
oppositional-or-keywordOpNameDefault: 'identity'See the operation contract and implementation below.
basepositional-or-keywordstr | ActivationSpec[Tensor]Default: 'gaussian'See the operation contract and implementation below.
stridepositional-or-keywordint | tuple[int, int]Default: 1See the operation contract and implementation below.
paddingpositional-or-keywordint | strDefault: 0See the operation contract and implementation below.
dilationpositional-or-keywordint | tuple[int, int]Default: 1See the operation contract and implementation below.
biaspositional-or-keywordboolDefault: TrueSee the operation contract and implementation below.
block_kwargspositional-or-keyworddict[str, Any] | NoneDefault: NoneSee the operation contract and implementation below.
Executed regression · cmbconv2d uses default dtype

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_cmbconv2d_uses_default_dtype(torch_default_float64) -> None:
    conv = cmbConv2d(
        in_channels=2,
        out_channels=4,
        kernel_size=3,
        op="laplacian",
        base="gaussian",
    )
    assert conv.conv.weight.dtype == torch.float64
    assert conv.block.ombu.biases.dtype == torch.float64
python -m pytest "packages/omnibias-torch/tests/test_audit_regressions.py::test_cmbconv2d_uses_default_dtype" -q
Regression example · cmblinear forward shape

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_cmblinear_forward_shape() -> None:
    layer = cmbLinear(5, 3, op="identity", base="tanh")
    out = layer(torch.randn(2, 5))
    assert out.shape == (2, 3)
python -m pytest packages/omnibias-torch/tests/test_blocks.py -k test_cmblinear_forward_shape -q

Fields & methods

__init__method
__init__(self, in_channels: int, out_channels: int, kernel_size: int | tuple[int, int], op: OpName='identity', base: str | ActivationSpec[Tensor]='gaussian', stride: int | tuple[int, int]=1, padding: int | str=0, dilation: int | tuple[int, int]=1, bias: bool=True, block_kwargs: dict[str, Any] | None=None) -> None

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

Parameters

NameType & defaultContract
in_channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
out_channelspositional-or-keywordintRequiredSee the operation contract and implementation below.
kernel_sizepositional-or-keywordint | tuple[int, int]RequiredSee the operation contract and implementation below.
oppositional-or-keywordOpNameDefault: 'identity'See the operation contract and implementation below.
basepositional-or-keywordstr | ActivationSpec[Tensor]Default: 'gaussian'See the operation contract and implementation below.
stridepositional-or-keywordint | tuple[int, int]Default: 1See the operation contract and implementation below.
paddingpositional-or-keywordint | strDefault: 0See the operation contract and implementation below.
dilationpositional-or-keywordint | tuple[int, int]Default: 1See the operation contract and implementation below.
biaspositional-or-keywordboolDefault: TrueSee the operation contract and implementation below.
block_kwargspositional-or-keyworddict[str, Any] | NoneDefault: NoneSee the operation contract and implementation below.

Returns: None

Executed regression · cmbconv2d uses default dtype

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_cmbconv2d_uses_default_dtype(torch_default_float64) -> None:
    conv = cmbConv2d(
        in_channels=2,
        out_channels=4,
        kernel_size=3,
        op="laplacian",
        base="gaussian",
    )
    assert conv.conv.weight.dtype == torch.float64
    assert conv.block.ombu.biases.dtype == torch.float64
python -m pytest "packages/omnibias-torch/tests/test_audit_regressions.py::test_cmbconv2d_uses_default_dtype" -q
Method implementation
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size: int | tuple[int, int],
        op: OpName = "identity",
        base: str | ActivationSpec[Tensor] = "gaussian",
        stride: int | tuple[int, int] = 1,
        padding: int | str = 0,
        dilation: int | tuple[int, int] = 1,
        bias: bool = True,
        block_kwargs: dict[str, Any] | None = None,
    ) -> None:
        super().__init__(op=op, base=base, out_channels=out_channels, block_kwargs=block_kwargs)
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.conv = nn.Conv2d(
            in_channels,
            out_channels,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            dilation=dilation,
            bias=bias,
        )
View source ↗
forwardmethod
forward(self, x: Tensor) -> Tensor

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

Parameters

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

Returns: Tensor

Executed regression · cmbconv2d shape and chain rule

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_cmbconv2d_shape_and_chain_rule() -> None:
    layer = cmbConv2d(2, 4, kernel_size=3, padding=1, op="laplacian", base="gaussian")
    x = torch.randn(2, 2, 8, 8)
    out = layer(x)
    assert out.shape == (2, 4, 8, 8)
    # Independently apply Hermite-2 * exp to the conv output
    z = layer.conv(x)
    ref = (z * z - 1.0) * torch.exp(-0.5 * z * z)
    assert torch.allclose(out, ref, atol=1e-5)
python -m pytest "packages/omnibias-torch/tests/test_blocks.py::test_cmbconv2d_shape_and_chain_rule" -q
Method implementation
    def forward(self, x: Tensor) -> Tensor:
        z = self.conv(x)  # (B, out_channels, H, W)
        return self._apply_block_channel_last(z, channel_dim=1)
View source ↗
extra_reprmethod
extra_repr(self) -> str

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

Returns: str

Method implementation
    def extra_repr(self) -> str:
        return (
            f"in_channels={self.in_channels}, out_channels={self.out_channels}, "
            f"op={self.block.op!r}, base={self.block.base_name!r}"
        )
View source ↗
in_channelsattribute
in_channels: int = in_channels

Public instance attribute assigned by __init__. The source assignment is in_channels = in_channels; it describes instance state, not a literal constructor default.

View source ↗
out_channelsattribute
out_channels: int = out_channels

Public instance attribute assigned by __init__. The source assignment is out_channels = out_channels; it describes instance state, not a literal constructor default.

View source ↗
convattribute
conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias)

Public instance attribute assigned by __init__. The source assignment is conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias); it describes instance state, not a literal constructor default.

Regression example · identity block matches base

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_identity_block_matches_base() -> None:
    block = OperatorBlock(op="identity", base="softplus", channels=4)
    z = torch.randn(3, 4)
    out = block(z)
    ref = torch.nn.functional.softplus(z)
    assert torch.allclose(out, ref, atol=1e-6)
python -m pytest packages/omnibias-torch/tests/test_blocks.py -k test_identity_block_matches_base -q
View source ↗
Read the implementation
class cmbConv2d(_CmbConvBase):
    """``nn.Conv2d`` + per-channel :class:`OperatorBlock`.

    Layout: input ``(B, in_channels, H, W)`` -> output ``(B, out_channels, H_out, W_out)``.
    """

    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size: int | tuple[int, int],
        op: OpName = "identity",
        base: str | ActivationSpec[Tensor] = "gaussian",
        stride: int | tuple[int, int] = 1,
        padding: int | str = 0,
        dilation: int | tuple[int, int] = 1,
        bias: bool = True,
        block_kwargs: dict[str, Any] | None = None,
    ) -> None:
        super().__init__(op=op, base=base, out_channels=out_channels, block_kwargs=block_kwargs)
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.conv = nn.Conv2d(
            in_channels,
            out_channels,
            kernel_size=kernel_size,
            stride=stride,
            padding=padding,
            dilation=dilation,
            bias=bias,
        )

    def forward(self, x: Tensor) -> Tensor:
        z = self.conv(x)  # (B, out_channels, H, W)
        return self._apply_block_channel_last(z, channel_dim=1)

    def extra_repr(self) -> str:
        return (
            f"in_channels={self.in_channels}, out_channels={self.out_channels}, "
            f"op={self.block.op!r}, base={self.block.base_name!r}"
        )
Other public import paths
  • omnibias.torch.cmbConv2d
  • omnibias.torch.blocks.cmbConv2d
  • omnibias.torch.blocks.conv.cmbConv2d