Skip to content

Transforms

These functions reweight and normalize stochastic morphisms. condition multiplies each row by evidence weights and renormalizes it, which conditions the output distribution on that evidence. mix forms a mixture of morphisms, factor reweights a morphism, and normalize renormalizes its rows. Inferring the input instead needs a prior over inputs weighted by the evidence likelihood of each, that is, Bayesian inversion (Cho and Jacobs, 2019).

transforms

Transformations on stochastic morphisms.

Provides operations like conditioning, mixing, factoring, and normalization that wrap existing morphisms into new ones.

ConditionedMorphism

ConditionedMorphism(inner: FiniteMorphism, evidence: Tensor)

Bases: FiniteMorphism

A morphism conditioned on evidence via Bayesian update.

Given a morphism f: A → B and evidence tensor e over B, produces f|e: A → B where:

f|e(a, b) = f(a, b) · e(b) / Σ_{b'} f(a, b') · e(b')

This is pointwise multiplication followed by row-renormalization.

PARAMETER DESCRIPTION
inner

The unconditioned morphism.

TYPE: FiniteMorphism

evidence

Evidence tensor broadcastable to the codomain shape. Values should be non-negative (likelihoods).

TYPE: Tensor

Source code in src/quivers/stochastic/transforms.py
def __init__(self, inner: FiniteMorphism, evidence: torch.Tensor) -> None:
    inner = _require_finite(inner)
    super().__init__(inner.domain, inner.codomain, algebra=inner._algebra)
    self._inner = inner
    self._evidence = evidence

tensor property

tensor: Tensor

Conditioned (posterior) tensor.

RETURNS DESCRIPTION
Tensor

Row-normalized tensor after pointwise evidence multiplication.

module

module() -> Module

Return the nn.Module holding this morphism's parameters.

RETURNS DESCRIPTION
Module

The parameter container.

Source code in src/quivers/stochastic/transforms.py
def module(self) -> nn.Module:
    """Return the ``nn.Module`` holding this morphism's parameters.

    Returns
    -------
    nn.Module
        The parameter container.
    """
    return _ConditionedModule(self._inner.module())

MixtureMorphism

MixtureMorphism(left: FiniteMorphism, right: FiniteMorphism, learnable: bool = True, init_logit: float = 0.0)

Bases: FiniteMorphism

Convex combination of two morphisms with a learnable weight.

Given morphisms f, g: A → B and a mixing weight p ∈ [0, 1]:

mix(p, f, g)(a, b) = p · f(a, b) + (1 - p) · g(a, b)

The weight p is parameterized via a sigmoid-transformed scalar.

PARAMETER DESCRIPTION
left

First component morphism.

TYPE: FiniteMorphism

right

Second component morphism (same domain and codomain).

TYPE: FiniteMorphism

learnable

If True (default), the mixing weight is a learnable parameter. If False, it is fixed at the initial value.

TYPE: bool DEFAULT: True

init_logit

Initial value for the unconstrained logit of p. Default 0.0 (p = 0.5).

TYPE: float DEFAULT: 0.0

RAISES DESCRIPTION
TypeError

If left and right differ in domain or codomain.

Source code in src/quivers/stochastic/transforms.py
def __init__(
    self,
    left: FiniteMorphism,
    right: FiniteMorphism,
    learnable: bool = True,
    init_logit: float = 0.0,
) -> None:
    left = _require_finite(left)
    right = _require_finite(right)
    if left.domain != right.domain or left.codomain != right.codomain:
        raise TypeError(
            f"cannot mix morphisms with different types: "
            f"{left.domain!r} -> {left.codomain!r} vs "
            f"{right.domain!r} -> {right.codomain!r}"
        )

    super().__init__(left.domain, left.codomain, algebra=left._algebra)
    self._left = left
    self._right = right

    self._mix_module = _MixedModule(left.module(), right.module())

    if learnable:
        self._mix_module.register_parameter(
            "logit_p", nn.Parameter(torch.tensor(init_logit))
        )

    else:
        self._mix_module.register_buffer("logit_p", torch.tensor(init_logit))

weight property

weight: Tensor

The mixing weight p ∈ (0, 1).

tensor property

tensor: Tensor

Convex combination: p · left + (1 - p) · right.

RETURNS DESCRIPTION
Tensor

Mixed tensor, row-stochastic if inputs are.

module

module() -> Module

Return the nn.Module holding this morphism's parameters.

RETURNS DESCRIPTION
Module

The parameter container.

Source code in src/quivers/stochastic/transforms.py
def module(self) -> nn.Module:
    """Return the ``nn.Module`` holding this morphism's parameters.

    Returns
    -------
    nn.Module
        The parameter container.
    """
    return self._mix_module

FactoredMorphism

FactoredMorphism(inner: FiniteMorphism, weights: Tensor)

Bases: FiniteMorphism

A morphism with pointwise likelihood weighting.

Given a morphism f: A → B and a weight tensor w over B:

factor(f, w)(a, b) = f(a, b) · w(b)

This is unnormalized: the result is not necessarily row-stochastic. Use normalize afterward if normalization is needed.

PARAMETER DESCRIPTION
inner

The base morphism.

TYPE: FiniteMorphism

weights

Non-negative weight tensor broadcastable to the codomain shape.

TYPE: Tensor

Source code in src/quivers/stochastic/transforms.py
def __init__(self, inner: FiniteMorphism, weights: torch.Tensor) -> None:
    inner = _require_finite(inner)
    super().__init__(inner.domain, inner.codomain, algebra=inner._algebra)
    self._inner = inner
    self._weights = weights

tensor property

tensor: Tensor

Pointwise-weighted tensor (unnormalized).

RETURNS DESCRIPTION
Tensor

f(a, b) · w(b) for each (a, b).

module

module() -> Module

Return the nn.Module holding this morphism's parameters.

RETURNS DESCRIPTION
Module

The parameter container.

Source code in src/quivers/stochastic/transforms.py
def module(self) -> nn.Module:
    """Return the ``nn.Module`` holding this morphism's parameters.

    Returns
    -------
    nn.Module
        The parameter container.
    """
    return _FactoredModule(self._inner.module())

NormalizedMorphism

NormalizedMorphism(inner: FiniteMorphism)

Bases: FiniteMorphism

A morphism with row-renormalized tensor.

Divides each codomain fiber by its sum so that rows sum to 1.

PARAMETER DESCRIPTION
inner

The unnormalized morphism.

TYPE: FiniteMorphism

Source code in src/quivers/stochastic/transforms.py
def __init__(self, inner: FiniteMorphism) -> None:
    inner = _require_finite(inner)
    super().__init__(inner.domain, inner.codomain, algebra=inner._algebra)
    self._inner = inner

tensor property

tensor: Tensor

Row-normalized tensor.

RETURNS DESCRIPTION
Tensor

Tensor where codomain fibers sum to 1.

module

module() -> Module

Return the nn.Module holding this morphism's parameters.

RETURNS DESCRIPTION
Module

The parameter container.

Source code in src/quivers/stochastic/transforms.py
def module(self) -> nn.Module:
    """Return the ``nn.Module`` holding this morphism's parameters.

    Returns
    -------
    nn.Module
        The parameter container.
    """
    return _NormalizedModule(self._inner.module())

condition

condition(f: FiniteMorphism, evidence: Tensor) -> ConditionedMorphism

Condition a morphism on evidence (Bayesian update).

Computes the posterior: f|e(a, b) ∝ f(a, b) · e(b), renormalized so rows sum to 1.

PARAMETER DESCRIPTION
f

The prior morphism A → B.

TYPE: FiniteMorphism

evidence

Non-negative evidence tensor over B.

TYPE: Tensor

RETURNS DESCRIPTION
ConditionedMorphism

The conditioned morphism.

Examples:

>>> A = FinSet(name="A", cardinality=2)
>>> B = FinSet(name="B", cardinality=3)
>>> f = StochasticMorphism(A, B)
>>> e = torch.tensor([1.0, 0.0, 1.0])  # observe B != 1
>>> g = condition(f, e)
>>> g.tensor.sum(dim=-1)  # still row-stochastic
Source code in src/quivers/stochastic/transforms.py
def condition(f: FiniteMorphism, evidence: torch.Tensor) -> ConditionedMorphism:
    """Condition a morphism on evidence (Bayesian update).

    Computes the posterior: f|e(a, b) ∝ f(a, b) · e(b),
    renormalized so rows sum to 1.

    Parameters
    ----------
    f : FiniteMorphism
        The prior morphism A → B.
    evidence : torch.Tensor
        Non-negative evidence tensor over B.

    Returns
    -------
    ConditionedMorphism
        The conditioned morphism.

    Examples
    --------
    >>> A = FinSet(name="A", cardinality=2)
    >>> B = FinSet(name="B", cardinality=3)
    >>> f = StochasticMorphism(A, B)
    >>> e = torch.tensor([1.0, 0.0, 1.0])  # observe B != 1
    >>> g = condition(f, e)
    >>> g.tensor.sum(dim=-1)  # still row-stochastic
    """
    return ConditionedMorphism(f, evidence)

mix

mix(left: FiniteMorphism, right: FiniteMorphism, learnable: bool = True, init_logit: float = 0.0) -> MixtureMorphism

Create a convex combination (mixture) of two morphisms.

Produces h: A → B where h(a,b) = p·f(a,b) + (1-p)·g(a,b). The mixing weight p is learnable by default.

PARAMETER DESCRIPTION
left

First component.

TYPE: FiniteMorphism

right

Second component (same type as left).

TYPE: FiniteMorphism

learnable

Whether the mixing weight is trainable.

TYPE: bool DEFAULT: True

init_logit

Initial logit value for the mixing weight.

TYPE: float DEFAULT: 0.0

RETURNS DESCRIPTION
MixtureMorphism

The mixture morphism.

Source code in src/quivers/stochastic/transforms.py
def mix(
    left: FiniteMorphism,
    right: FiniteMorphism,
    learnable: bool = True,
    init_logit: float = 0.0,
) -> MixtureMorphism:
    """Create a convex combination (mixture) of two morphisms.

    Produces h: A → B where h(a,b) = p·f(a,b) + (1-p)·g(a,b).
    The mixing weight p is learnable by default.

    Parameters
    ----------
    left : FiniteMorphism
        First component.
    right : FiniteMorphism
        Second component (same type as left).
    learnable : bool
        Whether the mixing weight is trainable.
    init_logit : float
        Initial logit value for the mixing weight.

    Returns
    -------
    MixtureMorphism
        The mixture morphism.
    """
    return MixtureMorphism(left, right, learnable=learnable, init_logit=init_logit)

factor

factor(f: FiniteMorphism, weights: Tensor) -> FactoredMorphism

Apply pointwise likelihood weighting to a morphism.

Computes: factor(f, w)(a, b) = f(a, b) · w(b). The result is unnormalized.

PARAMETER DESCRIPTION
f

The base morphism.

TYPE: FiniteMorphism

weights

Non-negative weight tensor over the codomain.

TYPE: Tensor

RETURNS DESCRIPTION
FactoredMorphism

The weighted morphism.

Source code in src/quivers/stochastic/transforms.py
def factor(f: FiniteMorphism, weights: torch.Tensor) -> FactoredMorphism:
    """Apply pointwise likelihood weighting to a morphism.

    Computes: factor(f, w)(a, b) = f(a, b) · w(b).
    The result is unnormalized.

    Parameters
    ----------
    f : FiniteMorphism
        The base morphism.
    weights : torch.Tensor
        Non-negative weight tensor over the codomain.

    Returns
    -------
    FactoredMorphism
        The weighted morphism.
    """
    return FactoredMorphism(f, weights)

normalize

Renormalize a morphism so codomain fibers sum to 1.

PARAMETER DESCRIPTION
f

The unnormalized morphism.

TYPE: FiniteMorphism

RETURNS DESCRIPTION
NormalizedMorphism

The row-normalized morphism.

Source code in src/quivers/stochastic/transforms.py
def normalize(f: FiniteMorphism) -> NormalizedMorphism:
    """Renormalize a morphism so codomain fibers sum to 1.

    Parameters
    ----------
    f : FiniteMorphism
        The unnormalized morphism.

    Returns
    -------
    NormalizedMorphism
        The row-normalized morphism.
    """
    return NormalizedMorphism(f)

Cited sources

Kenta Cho and Bart Jacobs. Disintegration and Bayesian Inversion via String Diagrams. Mathematical Structures in Computer Science, 29(7):938–971, 2019. URL: https://doi.org/10.1017/S0960129518000488, doi:10.1017/S0960129518000488.