Skip to content

Deterministic Morphisms

A deterministic kernel sends each input to a Dirac measure at a function's output, so a transformation such as softmax can take part in a probabilistic program (let steps) without a further random draw. Its output is still random when its input is. The module gives deterministic kernels for cumulative sums of monotone splines, the softmax projection onto the simplex, and covariance reconstruction from a correlation Cholesky factor and scales.

LearnedFunction is the learned case: a parameter source applied to the input's coordinates, followed by an output nonlinearity. It is what a morphism f : X -> Y [role=function] declaration compiles to, and a program's let z = f(a, b) calls its apply_values with one value per domain factor. Its weights are ordinary module parameters, fit as point estimates, unless it is constructed with latent=<name>: its weights are then read from the sites network_weight_sites names, passed to each evaluation, as a [weights=latent] declaration draws them.

SequenceFunction is the learned case over whole sequences, what a [role=function] declaration with param_source=self_attention or param_source=positions(N) compiles to. Its input keeps a position axis before the coordinate axis, shape (..., T, d), and its network reads every position at once: a SelfAttentionSource mixes the positions, and a PositionSource adds a learned vector to each. A program's let h = attn(u) passes it one sequence.

deterministic

Deterministic morphisms in :math:\mathbf{Kern}.

Each builder returns a ContinuousMorphism whose runtime realisation is a Dirac kernel concentrated on a deterministic image: cumsum_morphism for ordinal monotone splines, softmax_morphism for the standard simplex projection, cholesky_quad_form_morphism for covariance reconstruction from a correlation Cholesky factor and a positive-scale vector.

Categorically a deterministic morphism :math:f : X \to Y is the unit-Kleisli image of a measurable map; its log-density is :math:-\infty everywhere except at :math:y = f(x) and zero there. The variational backend treats the sampling path as an identity reparameterization of the deterministic image and the log-density as a no-op (the surrounding KL terms absorb the Dirac indicator).

FunctionOutput

FunctionOutput = Literal['identity', 'tanh', 'sigmoid', 'softplus', 'relu']

The nonlinearity a LearnedFunction applies to its network's output.

DeterministicMorphism

DeterministicMorphism(domain: AnySpace, codomain: AnySpace, apply: Callable[[Tensor], Tensor], name: str, *, mappable: bool = False)

Bases: ContinuousMorphism

Helper base for deterministic morphisms f : X → Y.

A deterministic morphism in :math:\mathbf{Kern} is a Dirac kernel concentrated on :math:f(x). Its log-density is :math:-\infty everywhere except at :math:y = f(x) and :math:0 (= :math:\log 1) there; for gradient-based inference we treat the sampling path as an identity reparameterization of the deterministic image.

PARAMETER DESCRIPTION
domain

The input space.

TYPE: AnySpace

codomain

The output space.

TYPE: AnySpace

apply

The map x -> f(x).

TYPE: Callable[[Tensor], Tensor]

name

The morphism's name.

TYPE: str

mappable

Whether apply can be evaluated at many positions in one pass: it is a tensor computation that branches on no value.

TYPE: bool DEFAULT: False

Source code in src/quivers/continuous/deterministic.py
def __init__(
    self,
    domain: AnySpace,
    codomain: AnySpace,
    apply: Callable[[torch.Tensor], torch.Tensor],
    name: str,
    *,
    mappable: bool = False,
) -> None:
    super().__init__(domain, codomain)
    self.mappable = mappable
    self._apply_fn = apply
    self._name = name

point_mass_value

point_mass_value(x: Tensor) -> Tensor

The Dirac's location, :math:f(x).

Reporting it lets a composition through this morphism integrate over its codomain exactly, by evaluating the next kernel at the single point carrying all the mass, instead of approximating an integral that has no spread to resolve.

Source code in src/quivers/continuous/deterministic.py
def point_mass_value(self, x: torch.Tensor) -> torch.Tensor:
    """The Dirac's location, :math:`f(x)`.

    Reporting it lets a composition through this morphism
    integrate over its codomain exactly, by evaluating the next
    kernel at the single point carrying all the mass, instead of
    approximating an integral that has no spread to resolve.
    """
    return self._apply_fn(x)

LearnedFunction

LearnedFunction(domain: AnySpace, codomain: AnySpace, source: ParamSource, output: FunctionOutput = 'identity', latent: str | None = None)

Bases: DeterministicMorphism

A learned deterministic map f : X -> Y between continuous spaces.

The map applies a parameter source to the input's coordinates and then an output nonlinearity, :math:f(x) = \sigma(g_\theta(x)), with :math:g_\theta a LinearSource (the affine map :math:W x + b), an MLPSource, or an IdentitySource. As a kernel it is the Dirac kernel at :math:f(x): it contributes no density and no site, a composition through it is exact (see point_mass_value), and a scan over it is a deterministic recurrence. Its weights are module parameters, fit as point estimates by the objective that trains the model around it.

PARAMETER DESCRIPTION
domain

The input space. A ProductSpace takes its factors in order, concatenated into one coordinate vector.

TYPE: AnySpace

codomain

The output space, as wide as the source's output.

TYPE: AnySpace

source

The network from input coordinates to output coordinates.

TYPE: ParamSource

output

The nonlinearity applied to the network's output.

TYPE: FunctionOutput DEFAULT: 'identity'

latent

When given, the network's weights are latent: they are read from the sites network_weight_sites names after this morphism name, passed to each evaluation, rather than from the source's own parameters, which then go unused.

TYPE: str | None DEFAULT: None

RAISES DESCRIPTION
TypeError

If the domain or codomain is not continuous.

ValueError

If the source's output width is not the codomain's width, or output is not a FunctionOutput.

Source code in src/quivers/continuous/deterministic.py
def __init__(
    self,
    domain: AnySpace,
    codomain: AnySpace,
    source: ParamSource,
    output: FunctionOutput = "identity",
    latent: str | None = None,
) -> None:
    widths = function_factor_widths(domain)
    width = _event_width(codomain)
    if int(source.param_dim) != width:
        raise ValueError(
            f"LearnedFunction: the source writes {source.param_dim} "
            f"coordinates, but the codomain {codomain!s} is {width} wide"
        )
    if output not in _OUTPUTS:
        raise ValueError(
            f"LearnedFunction: unknown output nonlinearity {output!r}; "
            f"expected one of {sorted(_OUTPUTS)}"
        )
    super().__init__(
        domain, codomain, self._point, name="LearnedFunction", mappable=True
    )
    self.source = source
    self._output: FunctionOutput = output
    self._factor_widths = widths
    self._width = width
    self._latent_sites: dict[str, str] = (
        network_weight_sites(source, latent) if latent is not None else {}
    )

latent_sites property

latent_sites: dict[str, str]

The site each network parameter is drawn at, when latent.

RETURNS DESCRIPTION
dict[str, str]

Parameter path to site name; empty for point weights.

output property

The nonlinearity applied to the network's output.

RETURNS DESCRIPTION
FunctionOutput

Its name.

factor_widths property

factor_widths: tuple[int, ...]

The width of each factor of the domain, in order.

RETURNS DESCRIPTION
tuple[int, ...]

One width per factor.

evaluate

evaluate(x: Tensor, weights: Mapping[str, Tensor] | None = None) -> Tensor

Apply the map to a batch of inputs.

PARAMETER DESCRIPTION
x

Inputs, shape (batch, domain_dim), or (batch,) for a one-wide domain; any leading axes before the coordinate axis are kept.

TYPE: Tensor

weights

For latent weights, each site's drawn value by site name; None for point weights.

TYPE: Mapping[str, Tensor] | None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Shape (batch, codomain_dim), with the leading axes of x.

RAISES DESCRIPTION
ValueError

If the coordinate axis is not the domain's width, or latent weights are missing, misshaped, or given for point weights.

Source code in src/quivers/continuous/deterministic.py
def evaluate(
    self, x: torch.Tensor, weights: Mapping[str, torch.Tensor] | None = None
) -> torch.Tensor:
    """Apply the map to a batch of inputs.

    Parameters
    ----------
    x : torch.Tensor
        Inputs, shape ``(batch, domain_dim)``, or ``(batch,)`` for a
        one-wide domain; any leading axes before the coordinate axis
        are kept.
    weights : Mapping[str, torch.Tensor] | None
        For latent weights, each site's drawn value by site name;
        ``None`` for point weights.

    Returns
    -------
    torch.Tensor
        Shape ``(batch, codomain_dim)``, with the leading axes of
        ``x``.

    Raises
    ------
    ValueError
        If the coordinate axis is not the domain's width, or latent
        weights are missing, misshaped, or given for point weights.
    """
    dimension = sum(self._factor_widths)
    if x.dim() == 1 and dimension == 1:
        x = x.unsqueeze(-1)
    if x.dim() == 0 or int(x.shape[-1]) != dimension:
        raise ValueError(
            f"LearnedFunction: expected inputs whose last axis is the "
            f"domain's {dimension} coordinates, got shape {tuple(x.shape)}"
        )
    if not x.is_floating_point():
        x = x.to(torch.get_default_dtype())
    lead = x.shape[:-1]
    flat = x.reshape(-1, dimension)
    if self._latent_sites:
        if weights is None:
            raise ValueError(
                "LearnedFunction: the network's weights are latent; pass "
                f"the drawn values of {sorted(self._latent_sites.values())}"
            )
        parameters = dict(self.source.named_parameters())
        drawn: dict[str, torch.Tensor] = {}
        for path, site in self._latent_sites.items():
            if site not in weights:
                raise ValueError(f"LearnedFunction: no value for weight {site!r}")
            value = torch.as_tensor(weights[site])
            shape = parameters[path].shape
            if value.numel() != shape.numel():
                raise ValueError(
                    f"LearnedFunction: weight {site!r} has shape "
                    f"{tuple(value.shape)}, but the layer takes {tuple(shape)}"
                )
            drawn[path] = value.reshape(shape).to(flat.dtype)
        raw = functional_call(self.source, drawn, (flat,))
    elif weights is not None:
        raise ValueError(
            "LearnedFunction: the network's weights are point estimates, so "
            "it reads no drawn weights"
        )
    else:
        raw = self.source(flat)
    image = _OUTPUTS[self._output](raw)
    return image.reshape(*lead, self._width)

apply_values

apply_values(*values: Tensor, weights: Mapping[str, Tensor] | None = None) -> Tensor

Apply the map to one value per domain factor.

This is how a program's let y = f(a, b) calls the map: each argument is one factor's value, a scalar for a one-wide factor or a vector of the factor's width, possibly led by axes the arguments share.

PARAMETER DESCRIPTION
*values

One value per factor, in the domain's order.

TYPE: Tensor DEFAULT: ()

weights

For latent weights, each site's drawn value by site name.

TYPE: Mapping[str, Tensor] | None DEFAULT: None

RETURNS DESCRIPTION
Tensor

The image, shape (*lead, codomain_dim) for the arguments' shared leading axes lead.

RAISES DESCRIPTION
ValueError

If the number of values is not the number of factors, or a value's trailing axis is not its factor's width.

Source code in src/quivers/continuous/deterministic.py
def apply_values(
    self,
    *values: torch.Tensor,
    weights: Mapping[str, torch.Tensor] | None = None,
) -> torch.Tensor:
    """Apply the map to one value per domain factor.

    This is how a program's ``let y = f(a, b)`` calls the map: each
    argument is one factor's value, a scalar for a one-wide factor
    or a vector of the factor's width, possibly led by axes the
    arguments share.

    Parameters
    ----------
    *values : torch.Tensor
        One value per factor, in the domain's order.
    weights : Mapping[str, torch.Tensor] | None
        For latent weights, each site's drawn value by site name.

    Returns
    -------
    torch.Tensor
        The image, shape ``(*lead, codomain_dim)`` for the arguments'
        shared leading axes ``lead``.

    Raises
    ------
    ValueError
        If the number of values is not the number of factors, or a
        value's trailing axis is not its factor's width.
    """
    if len(values) != len(self._factor_widths):
        raise ValueError(
            f"LearnedFunction: the domain has {len(self._factor_widths)} "
            f"factors, but the call passes {len(values)} arguments"
        )
    shaped: list[torch.Tensor] = []
    for position, (value, width) in enumerate(
        zip(values, self._factor_widths, strict=True)
    ):
        tensor = torch.as_tensor(value)
        if not tensor.is_floating_point():
            tensor = tensor.to(torch.get_default_dtype())
        if tensor.dim() == 0 and width == 1:
            tensor = tensor.reshape(1)
        if tensor.dim() == 0 or int(tensor.shape[-1]) != width:
            raise ValueError(
                f"LearnedFunction: argument {position} has shape "
                f"{tuple(tensor.shape)}, but its domain factor is "
                f"{width} wide"
            )
        shaped.append(tensor)
    lead = torch.broadcast_shapes(*(tensor.shape[:-1] for tensor in shaped))
    joined = torch.cat(
        [tensor.expand(*lead, tensor.shape[-1]) for tensor in shaped], dim=-1
    )
    return self.evaluate(joined, weights)

SequenceFunction

SequenceFunction(domain: AnySpace, codomain: AnySpace, source: SelfAttentionSource | PositionSource)

Bases: LearnedFunction

A learned deterministic map from a sequence of rows to a sequence.

Where a LearnedFunction maps each row on its own, a sequence function reads every row of a sequence at once: the axis before the coordinate axis is the position axis, and the image at a position may depend on every other position. Its network is a SelfAttentionSource, which mixes the positions, or a PositionSource, which adds a learned vector per position. Like a learned function it contributes no site and no density, and its weights are module parameters fit as point estimates.

PARAMETER DESCRIPTION
domain

The space of one row of the input sequence; not a product.

TYPE: AnySpace

codomain

The space of one row of the output sequence.

TYPE: AnySpace

source

The network, from a sequence of domain rows to a sequence of codomain rows.

TYPE: SelfAttentionSource | PositionSource

RAISES DESCRIPTION
TypeError

If the domain or codomain is not continuous.

ValueError

If the domain is a product, or the source's output width is not the codomain's width.

Source code in src/quivers/continuous/deterministic.py
def __init__(
    self,
    domain: AnySpace,
    codomain: AnySpace,
    source: SelfAttentionSource | PositionSource,
) -> None:
    if isinstance(domain, ProductSpace):
        raise ValueError(
            f"SequenceFunction: a sequence function reads one sequence, "
            f"but its domain {domain!s} is a product"
        )
    super().__init__(domain, codomain, source)

evaluate

evaluate(x: Tensor, weights: Mapping[str, Tensor] | None = None) -> Tensor

Apply the map to a batch of sequences.

PARAMETER DESCRIPTION
x

Sequences, shape (..., T, domain_dim): the axis before the coordinate axis is the position axis, and any axes before it are kept.

TYPE: Tensor

weights

Must be None: a sequence function's weights are point estimates.

TYPE: Mapping[str, Tensor] | None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Shape (..., T, codomain_dim).

RAISES DESCRIPTION
ValueError

If x has no position axis, its rows are not the domain's width, or drawn weights are passed.

Source code in src/quivers/continuous/deterministic.py
def evaluate(
    self, x: torch.Tensor, weights: Mapping[str, torch.Tensor] | None = None
) -> torch.Tensor:
    """Apply the map to a batch of sequences.

    Parameters
    ----------
    x : torch.Tensor
        Sequences, shape ``(..., T, domain_dim)``: the axis before the
        coordinate axis is the position axis, and any axes before it
        are kept.
    weights : Mapping[str, torch.Tensor] | None
        Must be ``None``: a sequence function's weights are point
        estimates.

    Returns
    -------
    torch.Tensor
        Shape ``(..., T, codomain_dim)``.

    Raises
    ------
    ValueError
        If ``x`` has no position axis, its rows are not the domain's
        width, or drawn weights are passed.
    """
    if weights is not None:
        raise ValueError(
            "SequenceFunction: the network's weights are point estimates, "
            "so it reads no drawn weights"
        )
    (width,) = self.factor_widths
    if x.dim() < 2 or int(x.shape[-1]) != width:
        raise ValueError(
            f"SequenceFunction: expected a sequence of {width}-wide rows, "
            f"shape (..., T, {width}), got {tuple(x.shape)}"
        )
    if not x.is_floating_point():
        x = x.to(torch.get_default_dtype())
    return self.source(x)

apply_values

apply_values(*values: Tensor, weights: Mapping[str, Tensor] | None = None) -> Tensor

Apply the map to one sequence, as a program's let call does.

PARAMETER DESCRIPTION
*values

The one sequence, shape (..., T, domain_dim).

TYPE: Tensor DEFAULT: ()

weights

Must be None.

TYPE: Mapping[str, Tensor] | None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Shape (..., T, codomain_dim).

RAISES DESCRIPTION
ValueError

If the call passes other than one value, or evaluate refuses it.

Source code in src/quivers/continuous/deterministic.py
def apply_values(
    self,
    *values: torch.Tensor,
    weights: Mapping[str, torch.Tensor] | None = None,
) -> torch.Tensor:
    """Apply the map to one sequence, as a program's let call does.

    Parameters
    ----------
    *values : torch.Tensor
        The one sequence, shape ``(..., T, domain_dim)``.
    weights : Mapping[str, torch.Tensor] | None
        Must be ``None``.

    Returns
    -------
    torch.Tensor
        Shape ``(..., T, codomain_dim)``.

    Raises
    ------
    ValueError
        If the call passes other than one value, or `evaluate`
        refuses it.
    """
    if len(values) != 1:
        raise ValueError(
            f"SequenceFunction: a sequence function reads one sequence, "
            f"but the call passes {len(values)} arguments"
        )
    return self.evaluate(torch.as_tensor(values[0]), weights)

cumsum_morphism

cumsum_morphism(dim: int) -> DeterministicMorphism

Cumulative sum cumsum : Euclidean(dim) → Euclidean(dim).

Maps :math:(x_1, \dots, x_K) to :math:(x_1, x_1 + x_2, \dots, \sum_i x_i). The canonical monotonic-spline parameterization for ordinal covariates (coef ~ Normal(0, sigma) followed by cumsum(coef - coef[0]) gives a 0-anchored, monotonically-increasing effect across the ordered levels).

Source code in src/quivers/continuous/deterministic.py
def cumsum_morphism(dim: int) -> DeterministicMorphism:
    """Cumulative sum ``cumsum : Euclidean(dim) → Euclidean(dim)``.

    Maps :math:`(x_1, \\dots, x_K)` to
    :math:`(x_1, x_1 + x_2, \\dots, \\sum_i x_i)`. The canonical
    monotonic-spline parameterization for ordinal covariates
    (``coef ~ Normal(0, sigma)`` followed by ``cumsum(coef - coef[0])``
    gives a 0-anchored, monotonically-increasing effect across the
    ordered levels).
    """
    space = Euclidean(name="cumsum", dim=dim)
    return DeterministicMorphism(
        space, space, lambda x: torch.cumsum(x, dim=-1), name="cumsum", mappable=True
    )

softmax_morphism

softmax_morphism(dim: int) -> DeterministicMorphism

Softmax softmax : Euclidean(dim) → Simplex(dim).

The standard exponential normalizer onto the probability simplex. Useful for closed-form class-probability computations in posterior blocks where one would otherwise need a log-sum-exp aggregation by hand.

Source code in src/quivers/continuous/deterministic.py
def softmax_morphism(dim: int) -> DeterministicMorphism:
    """Softmax ``softmax : Euclidean(dim) → Simplex(dim)``.

    The standard exponential normalizer onto the probability
    simplex. Useful for closed-form class-probability computations
    in posterior blocks where one would otherwise need a
    log-sum-exp aggregation by hand.
    """
    src = Euclidean(name="softmax_in", dim=dim)
    tgt = Simplex(name="softmax_out", dim=dim)
    return DeterministicMorphism(
        src, tgt, lambda x: torch.softmax(x, dim=-1), name="softmax", mappable=True
    )

cholesky_quad_form_morphism

cholesky_quad_form_morphism(dim: int) -> ContinuousMorphism

Covariance reconstruction (L, s) -> diag(s) L L^T diag(s).

Given a Cholesky factor :math:L of a :math:K \times K correlation matrix and a positive-scale vector :math:s \in (0, \infty)^K, returns the corresponding covariance matrix :math:\Sigma = D R D^T with :math:R = L L^T and :math:D = \mathrm{diag}(s).

Domain is the product CholeskyFactor(K) <quivers.continuous.spaces.CholeskyFactor> * PositiveReals(K) <quivers.continuous.spaces.PositiveReals>; codomain is Euclidean(K * K) <quivers.continuous.spaces.Euclidean> flattened in row-major order so the result composes with downstream quivers.continuous.families.ConditionalMultivariateNormal consumers that accept a flat covariance vector.

Source code in src/quivers/continuous/deterministic.py
def cholesky_quad_form_morphism(dim: int) -> ContinuousMorphism:
    """Covariance reconstruction ``(L, s) -> diag(s) L L^T diag(s)``.

    Given a Cholesky factor :math:`L` of a :math:`K \\times K`
    correlation matrix and a positive-scale vector
    :math:`s \\in (0, \\infty)^K`, returns the corresponding
    covariance matrix :math:`\\Sigma = D R D^T` with
    :math:`R = L L^T` and :math:`D = \\mathrm{diag}(s)`.

    Domain is the product
    `CholeskyFactor(K) <quivers.continuous.spaces.CholeskyFactor>` ``*``
    `PositiveReals(K) <quivers.continuous.spaces.PositiveReals>`;
    codomain is `Euclidean(K * K) <quivers.continuous.spaces.Euclidean>`
    flattened in row-major order so the result composes with
    downstream
    [`quivers.continuous.families.ConditionalMultivariateNormal`][quivers.continuous.families.ConditionalMultivariateNormal]
    consumers that accept a flat covariance vector.
    """
    cholesky = CholeskyFactor(name="L", dim=dim)
    scale = PositiveReals(name="scale", dim=dim)
    source = ProductSpace(components=(cholesky, scale))
    target = Euclidean(name="cov", dim=dim * dim)

    def _apply(xs: torch.Tensor) -> torch.Tensor:
        # xs : (batch, K*K + K) — the cholesky's flat lower-tri plus
        # the K-vector of scales, concatenated in that order. We
        # rehydrate L from the lower-triangular packing, apply the
        # quadratic form, then flatten.
        batch = xs.shape[0]
        chol_flat = xs[:, : dim * dim]
        scale_vec = xs[:, dim * dim :]
        L = chol_flat.reshape(batch, dim, dim)
        mask = torch.tril(torch.ones(dim, dim, device=xs.device, dtype=xs.dtype))
        L = L * mask
        R = L @ L.transpose(-1, -2)
        D = scale_vec.unsqueeze(-1) * torch.eye(dim, device=xs.device, dtype=xs.dtype)
        cov = D @ R @ D
        return cov.reshape(batch, dim * dim)

    return DeterministicMorphism(
        source, target, _apply, name="cholesky_quad_form", mappable=True
    )

function_factor_widths

function_factor_widths(space: AnySpace) -> tuple[int, ...]

The width of each factor of a learned function's domain.

PARAMETER DESCRIPTION
space

The domain; a ProductSpace lists its factors in order.

TYPE: AnySpace

RETURNS DESCRIPTION
tuple[int, ...]

One width per factor, the one width of a space that is not a product.

RAISES DESCRIPTION
TypeError

If a factor is not continuous.

Source code in src/quivers/continuous/deterministic.py
def function_factor_widths(space: AnySpace) -> tuple[int, ...]:
    """The width of each factor of a learned function's domain.

    Parameters
    ----------
    space : AnySpace
        The domain; a `ProductSpace` lists its factors in order.

    Returns
    -------
    tuple[int, ...]
        One width per factor, the one width of a space that is not a
        product.

    Raises
    ------
    TypeError
        If a factor is not continuous.
    """
    if isinstance(space, ProductSpace):
        return tuple(_event_width(component) for component in space.components)
    return (_event_width(space),)

learned_function_draw_message

learned_function_draw_message(name: str) -> str

The refusal of a sample or observe that draws from a function.

PARAMETER DESCRIPTION
name

The learned function's name.

TYPE: str

RETURNS DESCRIPTION
str

The message every path raises.

Source code in src/quivers/continuous/deterministic.py
def learned_function_draw_message(name: str) -> str:
    """The refusal of a ``sample`` or ``observe`` that draws from a function.

    Parameters
    ----------
    name : str
        The learned function's name.

    Returns
    -------
    str
        The message every path raises.
    """
    return (
        f"the learned function {name!r} is deterministic, so no step draws "
        f"from it; bind its value with `let v = {name}(x)` and draw from a "
        f"family around it, as in `let s <- sample Normal(loc=v, scale=1.0)`"
    )

weight_site_names

weight_site_names(name: str, depth: int) -> tuple[tuple[str, str], ...]

The site names of a network's weights and biases, layer by layer.

PARAMETER DESCRIPTION
name

The network's morphism name.

TYPE: str

depth

The number of hidden layers.

TYPE: int

RETURNS DESCRIPTION
tuple[tuple[str, str], ...]

One (weight, bias) pair per layer, hidden layers first: <name>_param_layer<k>_weight and <name>_param_layer<k>_bias, then <name>_param_weight and <name>_param_bias.

Source code in src/quivers/continuous/deterministic.py
def weight_site_names(name: str, depth: int) -> tuple[tuple[str, str], ...]:
    """The site names of a network's weights and biases, layer by layer.

    Parameters
    ----------
    name : str
        The network's morphism name.
    depth : int
        The number of hidden layers.

    Returns
    -------
    tuple[tuple[str, str], ...]
        One ``(weight, bias)`` pair per layer, hidden layers first:
        ``<name>_param_layer<k>_weight`` and ``<name>_param_layer<k>_bias``,
        then ``<name>_param_weight`` and ``<name>_param_bias``.
    """
    layers = [
        (f"{name}_param_layer{k}_weight", f"{name}_param_layer{k}_bias")
        for k in range(depth)
    ]
    layers.append((f"{name}_param_weight", f"{name}_param_bias"))
    return tuple(layers)

network_weight_sites

network_weight_sites(source: Module, name: str) -> dict[str, str]

The site each weight and bias of a network is drawn at.

PARAMETER DESCRIPTION
source

The network, whose affine layers are torch.nn.Linear modules applied in registration order.

TYPE: Module

name

The network's morphism name.

TYPE: str

RETURNS DESCRIPTION
dict[str, str]

Each parameter's path in source to its site name.

RAISES DESCRIPTION
ValueError

If a layer has no bias or the network has no affine layer.

Source code in src/quivers/continuous/deterministic.py
def network_weight_sites(source: nn.Module, name: str) -> dict[str, str]:
    """The site each weight and bias of a network is drawn at.

    Parameters
    ----------
    source : nn.Module
        The network, whose affine layers are `torch.nn.Linear` modules
        applied in registration order.
    name : str
        The network's morphism name.

    Returns
    -------
    dict[str, str]
        Each parameter's path in ``source`` to its site name.

    Raises
    ------
    ValueError
        If a layer has no bias or the network has no affine layer.
    """
    linears = [
        (path, module)
        for path, module in source.named_modules()
        if isinstance(module, nn.Linear)
    ]
    if not linears:
        raise ValueError(f"network {name!r} has no affine layer to draw weights for")
    sites: dict[str, str] = {}
    names = weight_site_names(name, len(linears) - 1)
    for (path, module), (weight, bias) in zip(linears, names, strict=True):
        if module.bias is None:
            raise ValueError(f"network {name!r}: layer {path!r} has no bias")
        prefix = f"{path}." if path else ""
        sites[f"{prefix}weight"] = weight
        sites[f"{prefix}bias"] = bias
    return sites