Skip to content

Carriers

Each of these carriers computes a statistic of all derivations in the same sum and product traversal that computes their weight. For fixed carrier width, the extra work per operation is bounded in the cost of the component arithmetic. The proofs below concern the algebraic operations, and the law grid tests their implementations at the stated numerical precision. Each is an OrderPreservingSemiring of the one algebra hierarchy whose product commutes, with its elements packed on one trailing axis, so it composes, sums, and reduces over empty axes like any other member, and its law claims carry evidence: the laws about the carrier by the arguments below, the laws about the implementation by the law grid.

Expectation

An element of ExpectationSemiring is \(\langle p, r \rangle\) with \(p\) in a commutative semiring \(K\) and \(r\) in a \(K\)-semimodule \(M\) (Semimodule), with

\[ \langle p_1, r_1 \rangle \otimes \langle p_2, r_2 \rangle = \langle p_1 p_2,\ p_1 r_2 \oplus p_2 r_1 \rangle, \qquad \langle p_1, r_1 \rangle \oplus \langle p_2, r_2 \rangle = \langle p_1 \oplus p_2,\ r_1 \oplus r_2 \rangle, \]

zero \(\langle 0, 0 \rangle\) and unit \(\langle 1, 0 \rangle\) (Eisner 2002; Li and Eisner 2009, section 3).

Theorem. If \(K\) is a commutative semiring and \(M\) a semimodule over it, these operations form a commutative semiring.

Proof. The sum is componentwise, so it is associative and commutative with unit \(\langle 0, 0 \rangle\). The product is commutative because \(p_1 p_2 = p_2 p_1\) and \(\oplus\) commutes. It is associative: both bracketings of three factors give \(\langle p_1 p_2 p_3,\ p_1 p_2 r_3 \oplus p_1 p_3 r_2 \oplus p_2 p_3 r_1 \rangle\) by the action's associativity and distributivity. \(\langle 1, 0 \rangle\) is a unit since \(1 \cdot r = r\) and \(p \cdot 0 = 0\). Distributivity: \(\langle p, r \rangle (\langle a, b \rangle \oplus \langle c, d \rangle) = \langle p(a \oplus c),\ p(b \oplus d) \oplus (a \oplus c) r \rangle\), which equals the sum of the two products by distributivity of \(K\) and of the action over both sums. The zero annihilates since \(0 \cdot r = 0\) and \(p \cdot 0 = 0\). QED

Over derivations \(d\) whose factors \(e\) carry \(\langle p_e, r_e \rangle\), the sum of products is \(\langle Z,\ \bigoplus_d \bigoplus_{e \in d} p(d \setminus e)\, r_e \rangle\), where \(p(d \setminus e)\) multiplies the weights of the other factors of \(d\). With \(p_e = \exp(\theta \cdot f_e)\) and \(r_e = p_e f_e\) the statistic is \(\sum_d p(d) \sum_{e \in d} f_e = \nabla_\theta Z\), the gradient that reverse mode computes through the sum. Both are checked against enumeration of every path and against autograd.

Star. Where \(p^* = 1 \oplus p p^*\) exists, \(\langle p, r \rangle^* = \langle p^*,\ p^* (p^* r) \rangle\): the statistic \(q\) of a solution of \(X = 1 \oplus \langle p, r \rangle X\) must satisfy \(q = p q \oplus p^* r\), and \(p (p^* p^* r) \oplus p^* r = p^* (p p^* \oplus 1) r = p^* p^* r\).

Second-order expectation

An element of SecondOrderExpectationSemiring is \(\langle p, r, s, t \rangle\) with \(r \in K^m\), \(s \in K^k\) and \(t \in K^{m \times k}\):

\[ \langle p_1, r_1, s_1, t_1 \rangle \otimes \langle p_2, r_2, s_2, t_2 \rangle = \langle p_1 p_2,\ p_1 r_2 \oplus p_2 r_1,\ p_1 s_2 \oplus p_2 s_1,\ p_1 t_2 \oplus p_2 t_1 \oplus r_1 s_2^{\mathsf T} \oplus r_2 s_1^{\mathsf T} \rangle \]

(Li and Eisner 2009, section 4). With each factor \(e\) carrying \(\langle p_e, p_e r_e, p_e s_e, p_e r_e s_e^{\mathsf T} \rangle\), the sum over derivations has last part \(\bigoplus_d p(d)\, r(d)\, s(d)^{\mathsf T}\), where \(r(d)\) and \(s(d)\) sum the statistics of the factors of \(d\); this is checked against enumeration of every path.

Theorem. Over a commutative semiring \(K\) these operations form a commutative semiring.

Proof. Write an element as \(p + \sum_i r_i \varepsilon_i + \sum_j s_j \eta_j + \sum_{ij} t_{ij} \varepsilon_i \eta_j\), a polynomial over \(K\) in commuting indeterminates whose monomials are among \(1\), \(\varepsilon_i\), \(\eta_j\) and \(\varepsilon_i \eta_j\). The product above is the polynomial product followed by dropping every other monomial: the \(\varepsilon_i \eta_j\) coefficient of the product collects \(p_1 t_2\), \(p_2 t_1\), \(r_{1i} s_{2j}\) and \(r_{2i} s_{1j}\). The dropped monomials are closed under multiplication by any monomial, so dropping them from a product gives the same result whether or not they were dropped from the factors first. Dropping is therefore a homomorphism of sums and products from the commutative polynomial semiring onto these elements, and the elements inherit associativity, commutativity, distributivity and the units. QED

Star. Where \(p^*\) exists, \(\langle p, r, s, t \rangle^* = \langle p^*, p^{*2} r, p^{*2} s, p^{*2} t \oplus 2 p^{*3} r s^{\mathsf T} \rangle\), with \(2 = 1 \oplus 1\): substituting into \(X = 1 \oplus x X\) and using only \(p^* = 1 \oplus p p^*\) and commutativity gives each part.

Products

ProductSemiring runs several commutative semirings side by side, operation by operation. A direct product of commutative semirings is a commutative semiring, since every law holds in each factor. The star of a product is the product of the stars, where each exists.

Signed logarithmic weight derivatives

SignedLogDualSemiring represents a real coefficient as a sign and the natural logarithm of its magnitude. The zero representation is \((0,-\infty)\). The primal and tangent have independent signs and magnitudes. A zero primal thus need not imply a zero tangent.

Carrier laws. Decode the two parts as \(p\) and \(d\) and interpret the pair as \(p+d\varepsilon\) in \(\mathbb{R}[\varepsilon]/(\varepsilon^2)\). Componentwise addition and the product \((p,d)(q,e)=(pq,pe+qd)\) are exactly the quotient's operations. Thus they inherit the commutative semiring laws in exact arithmetic. Interpreting one input as \((p,p')\) and applying these operations gives one directional derivative of each finite sum of products by the ordinary chain rule. A product may be pruned as algebraic zero only when both parts are zero.

For opposing magnitudes with logs \(h>l\), subtraction computes \(h+\log(-\operatorname{expm1}(l-h))\). A reduction first cancels equal represented magnitudes, so the three terms \(e^{1000}\), \(1\), and \(-e^{1000}\) can retain their unit remainder. The numerical implementation uses float64. A nonzero summand that rounds away raises FloatingPointError, as does a nonzero coefficient that cannot be decoded into linear float64. These checks do not certify a general error bound for floating-point reductions.

Pass the primal and tangent explicitly, then use an acyclic indexed or elimination plan's run method. The derivative is the tangent of the computed element. For instance, at \(x=0\) the factors \(x\), \(e^{1000}\), and \(e^{-1000}\) give primal zero and tangent one in the direction \(dx=1\). The individual large and small factors can stay in the log representation throughout that contraction. Direct autograd of the packed signs and log magnitudes is refused.

References

  • Eisner, J. (2002). Parameter estimation for probabilistic finite-state transducers. ACL. doi:10.3115/1073083.1073085
  • Li, Z., and Eisner, J. (2009). First- and second-order expectation semirings with applications to minimum-risk training on translation forests. EMNLP. doi:10.3115/1699510.1699517

carriers

Carriers of statistics: expectation, second-order expectation, products.

An expectation carrier pairs a weight p with a statistic r acted on by weights [Eisner (2002); Li and Eisner (2009)]:

<p1, r1> ⊗ <p2, r2> = <p1 p2, p1 r2 ⊕ p2 r1>,
<p1, r1> ⊕ <p2, r2> = <p1 ⊕ p2, r1 ⊕ r2>.

Summing products over derivations gives <Z, ⊕_d p(d) r(d)> where r(d) sums the statistics of a derivation's factors; with factor weights exp(θ · f) and statistics p f the second component is the gradient of Z in θ. The second-order carrier adds a second statistic and their products; the product carrier runs several semirings side by side. Each is an OrderPreservingSemiring of the one hierarchy whose product commutes, with packed elements on one trailing axis, and each gives its star from the star of its weights where that exists.

References

Eisner, J. (2002). Parameter estimation for probabilistic finite-state transducers. ACL, 1-8. doi:10.3115/1073083.1073085

Li, Z., and Eisner, J. (2009). First- and second-order expectation semirings with applications to minimum-risk training on translation forests. EMNLP, 40-51. doi:10.3115/1699510.1699517

ElementStar

ElementStar = Callable[[Tensor], Tensor]

The star p* = 1 ⊕ p ⊗ p* of the weights, elementwise.

ExpectationSemiring

ExpectationSemiring(module: Semimodule)

Bases: _Packed

Weights paired with statistics in a semimodule (Li and Eisner 2009).

An element is <p, r>, packed as [p, r_1, ..., r_d], with p in the weights' semiring and r in a semimodule over it of vectors of length d. The product is <p1 p2, p1 · r2 ⊕ p2 · r1>, the sum is componentwise, the zero is <0, 0> and the unit <1, 0>.

PARAMETER DESCRIPTION
module

The statistics, vectors over a commutative semiring with scalar elements.

TYPE: Semimodule

RAISES DESCRIPTION
TypeError

If the module's scalars are not a commutative Semiring with scalar elements, or its elements are not vectors.

Source code in src/quivers/core/carriers.py
def __init__(self, module: Semimodule) -> None:
    base = module.scalars
    if not isinstance(base, Semiring) or base.element_shape != ():
        raise TypeError(
            f"the weights of an expectation carrier are a commutative semiring "
            f"with scalar elements, not {base.name}"
        )
    if len(module.element_shape) != 1:
        raise TypeError(
            f"the statistics of an expectation carrier are vectors, not "
            f"elements of shape {module.element_shape}"
        )
    self._module = module
    self._base = base

base property

base: Semiring

The semiring of the weights.

RETURNS DESCRIPTION
Semiring

The weights.

module property

module: Semimodule

The semimodule of the statistics.

RETURNS DESCRIPTION
Semimodule

The statistics.

name property

name: str

Expectation(<module>).

RETURNS DESCRIPTION
str

The name.

evidence

evidence(law: Law) -> LawEvidence

The evidence for a law; laws about the carrier hold by a theorem.

PARAMETER DESCRIPTION
law

A law the structure claims.

TYPE: Law

RETURNS DESCRIPTION
LawEvidence

The argument when the laws of the weights and the statistics are established.

Source code in src/quivers/core/carriers.py
def evidence(self, law: Law) -> LawEvidence:
    """The evidence for a law; laws about the carrier hold by a theorem.

    Parameters
    ----------
    law : Law
        A law the structure claims.

    Returns
    -------
    LawEvidence
        The argument when the laws of the weights and the statistics
        are established.
    """
    if law.scope == "carrier":
        if _established(self._base, self._module):
            return Proved(
                argument=f"{_PROOFS}#proof-expectation", sources=(_LI_EISNER,)
            )
        return self.assumption(
            f"the laws of {self._base.name} or {self._module.name} are not "
            "established"
        )
    return super().evidence(law)

parts

parts(t: Tensor) -> tuple[Tensor, Tensor]

The weight and the statistic of each element.

PARAMETER DESCRIPTION
t

Packed elements.

TYPE: Tensor

RETURNS DESCRIPTION
tuple of torch.Tensor and torch.Tensor

p of the index shape and r with a trailing axis of d.

RAISES DESCRIPTION
ValueError

If t lacks the packed axis.

Source code in src/quivers/core/carriers.py
def parts(self, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """The weight and the statistic of each element.

    Parameters
    ----------
    t : torch.Tensor
        Packed elements.

    Returns
    -------
    tuple of torch.Tensor and torch.Tensor
        ``p`` of the index shape and ``r`` with a trailing axis of ``d``.

    Raises
    ------
    ValueError
        If ``t`` lacks the packed axis.
    """
    self._check(t)
    return t[..., 0], t[..., 1:]

pack

pack(p: Tensor, r: Tensor) -> Tensor

Elements from weights and statistics.

PARAMETER DESCRIPTION
p

Weights.

TYPE: Tensor

r

Statistics, with a trailing axis of d.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

<p, r> packed.

Source code in src/quivers/core/carriers.py
def pack(self, p: torch.Tensor, r: torch.Tensor) -> torch.Tensor:
    """Elements from weights and statistics.

    Parameters
    ----------
    p : torch.Tensor
        Weights.
    r : torch.Tensor
        Statistics, with a trailing axis of ``d``.

    Returns
    -------
    torch.Tensor
        ``<p, r>`` packed.
    """
    p, r = torch.broadcast_tensors(p.unsqueeze(-1), r)
    return torch.cat((p[..., :1], r), dim=-1)

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

<p1 p2, p1 · r2 ⊕ p2 · r1>.

PARAMETER DESCRIPTION
a

Packed elements.

TYPE: Tensor

b

Packed elements, broadcastable with a.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The product.

Source code in src/quivers/core/carriers.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """``<p1 p2, p1 · r2 ⊕ p2 · r1>``.

    Parameters
    ----------
    a : torch.Tensor
        Packed elements.
    b : torch.Tensor
        Packed elements, broadcastable with ``a``.

    Returns
    -------
    torch.Tensor
        The product.
    """
    p1, r1 = self.parts(a)
    p2, r2 = self.parts(b)
    weight = self._base.tensor_op(p1, p2)
    statistic = self._module.join_pair(
        self._module.act(p1, r2), self._module.act(p2, r1)
    )
    return self.pack(weight, statistic)

zero_like

zero_like(shape: tuple[int, ...], like: Tensor) -> Tensor

<0, 0> at every index.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device are used.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Shape (*shape, 1 + d).

Source code in src/quivers/core/carriers.py
def zero_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """``<0, 0>`` at every index.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device are used.

    Returns
    -------
    torch.Tensor
        Shape ``(*shape, 1 + d)``.
    """
    return self.pack(
        self._base.zero_like(shape, like), self._module.zero_like(shape, like)
    )

unit_like

unit_like(shape: tuple[int, ...], like: Tensor) -> Tensor

<1, 0> at every index.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device are used.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Shape (*shape, 1 + d).

Source code in src/quivers/core/carriers.py
def unit_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """``<1, 0>`` at every index.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device are used.

    Returns
    -------
    torch.Tensor
        Shape ``(*shape, 1 + d)``.
    """
    return self.pack(
        self._base.unit_like(shape, like), self._module.zero_like(shape, like)
    )

contains

contains(t: Tensor) -> Tensor

Whether the weight and the statistic are in their carriers.

PARAMETER DESCRIPTION
t

Packed elements.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

One truth value per element.

Source code in src/quivers/core/carriers.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Whether the weight and the statistic are in their carriers.

    Parameters
    ----------
    t : torch.Tensor
        Packed elements.

    Returns
    -------
    torch.Tensor
        One truth value per element.
    """
    p, r = self.parts(t)
    return self._base.contains(p) & self._module.contains(r)

star

star(t: Tensor, weights_star: ElementStar) -> Tensor

<p, r>* = <p*, p* · (p* · r)>, where the star of p exists.

It solves X = 1 ⊕ <p, r> ⊗ X: the weight is p* and the statistic q must satisfy q = p · q ⊕ p* · r, which p* · (p* · r) does since p* = 1 ⊕ p p*.

PARAMETER DESCRIPTION
t

Packed elements.

TYPE: Tensor

weights_star

The star of the weights, elementwise.

TYPE: ElementStar

RETURNS DESCRIPTION
Tensor

The packed star.

Source code in src/quivers/core/carriers.py
def star(self, t: torch.Tensor, weights_star: ElementStar) -> torch.Tensor:
    """``<p, r>* = <p*, p* · (p* · r)>``, where the star of ``p`` exists.

    It solves ``X = 1 ⊕ <p, r> ⊗ X``: the weight is ``p*`` and the
    statistic ``q`` must satisfy ``q = p · q ⊕ p* · r``, which
    ``p* · (p* · r)`` does since ``p* = 1 ⊕ p p*``.

    Parameters
    ----------
    t : torch.Tensor
        Packed elements.
    weights_star : ElementStar
        The star of the weights, elementwise.

    Returns
    -------
    torch.Tensor
        The packed star.
    """
    p, r = self.parts(t)
    starred = weights_star(p)
    return self.pack(
        starred, self._module.act(starred, self._module.act(starred, r))
    )

SecondOrderExpectationSemiring

SecondOrderExpectationSemiring(base: Semiring, first: int, second: int)

Bases: _Packed

Weights with two statistics and their products (Li and Eisner 2009).

An element is <p, r, s, t> with r of length m, s of length k and t an m x k matrix, packed in that order with t row by row. The product is

<p1 p2, p1 r2 ⊕ p2 r1, p1 s2 ⊕ p2 s1,
 p1 t2 ⊕ p2 t1 ⊕ r1 s2ᵀ ⊕ r2 s1ᵀ>,

so summing over derivations gives ⊕_d p(d) r(d) s(d)ᵀ in the last part, the expectation of the product of two additive statistics.

PARAMETER DESCRIPTION
base

A commutative semiring with scalar elements.

TYPE: Semiring

first

The length m of the first statistic.

TYPE: int

second

The length k of the second statistic.

TYPE: int

RAISES DESCRIPTION
TypeError

If base is not a commutative semiring with scalar elements.

ValueError

If a length is negative.

Source code in src/quivers/core/carriers.py
def __init__(self, base: Semiring, first: int, second: int) -> None:
    if not isinstance(base, Semiring) or base.element_shape != ():
        raise TypeError(
            f"a second-order carrier is over a commutative semiring with scalar "
            f"elements, not {base.name}"
        )
    if first < 0 or second < 0:
        raise ValueError("statistic lengths are nonnegative")
    self._base = base
    self._first = int(first)
    self._second = int(second)

base property

base: Semiring

The semiring of every part.

RETURNS DESCRIPTION
Semiring

The base.

name property

name: str

SecondOrder(<base>, <m>, <k>).

RETURNS DESCRIPTION
str

The name.

evidence

evidence(law: Law) -> LawEvidence

The evidence for a law; laws about the carrier hold by a theorem.

PARAMETER DESCRIPTION
law

A law the structure claims.

TYPE: Law

RETURNS DESCRIPTION
LawEvidence

The argument when the laws of the base are established.

Source code in src/quivers/core/carriers.py
def evidence(self, law: Law) -> LawEvidence:
    """The evidence for a law; laws about the carrier hold by a theorem.

    Parameters
    ----------
    law : Law
        A law the structure claims.

    Returns
    -------
    LawEvidence
        The argument when the laws of the base are established.
    """
    if law.scope == "carrier":
        if _established(self._base):
            return Proved(
                argument=f"{_PROOFS}#proof-second-order", sources=(_LI_EISNER,)
            )
        return self.assumption(f"the laws of {self._base.name} are not established")
    return super().evidence(law)

parts

parts(t: Tensor) -> tuple[Tensor, Tensor, Tensor, Tensor]

The four parts of each element.

PARAMETER DESCRIPTION
t

Packed elements.

TYPE: Tensor

RETURNS DESCRIPTION
tuple of torch.Tensor

p, r (m), s (k) and t (m x k).

RAISES DESCRIPTION
ValueError

If t lacks the packed axis.

Source code in src/quivers/core/carriers.py
def parts(
    self, t: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    """The four parts of each element.

    Parameters
    ----------
    t : torch.Tensor
        Packed elements.

    Returns
    -------
    tuple of torch.Tensor
        ``p``, ``r`` (``m``), ``s`` (``k``) and ``t`` (``m x k``).

    Raises
    ------
    ValueError
        If ``t`` lacks the packed axis.
    """
    self._check(t)
    m, k = self._first, self._second
    products = t[..., 1 + m + k :].reshape(*t.shape[:-1], m, k)
    return t[..., 0], t[..., 1 : 1 + m], t[..., 1 + m : 1 + m + k], products

pack

pack(p: Tensor, r: Tensor, s: Tensor, t: Tensor) -> Tensor

Elements from their four parts.

PARAMETER DESCRIPTION
p

Weights.

TYPE: Tensor

r

First statistics, trailing m.

TYPE: Tensor

s

Second statistics, trailing k.

TYPE: Tensor

t

Products, trailing m x k.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The packed elements.

Source code in src/quivers/core/carriers.py
def pack(
    self, p: torch.Tensor, r: torch.Tensor, s: torch.Tensor, t: torch.Tensor
) -> torch.Tensor:
    """Elements from their four parts.

    Parameters
    ----------
    p : torch.Tensor
        Weights.
    r : torch.Tensor
        First statistics, trailing ``m``.
    s : torch.Tensor
        Second statistics, trailing ``k``.
    t : torch.Tensor
        Products, trailing ``m x k``.

    Returns
    -------
    torch.Tensor
        The packed elements.
    """
    index = torch.broadcast_shapes(
        p.shape, r.shape[:-1], s.shape[:-1], t.shape[:-2]
    )
    flat = t.reshape(*t.shape[:-2], self._first * self._second)
    return torch.cat(
        (
            p.expand(index).unsqueeze(-1),
            r.expand(*index, self._first),
            s.expand(*index, self._second),
            flat.expand(*index, self._first * self._second),
        ),
        dim=-1,
    )

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The product of two packed elements.

PARAMETER DESCRIPTION
a

Packed elements.

TYPE: Tensor

b

Packed elements, broadcastable with a.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

<p1 p2, p1 r2 ⊕ p2 r1, p1 s2 ⊕ p2 s1, p1 t2 ⊕ p2 t1 ⊕ r1 s2ᵀ ⊕ r2 s1ᵀ>.

Source code in src/quivers/core/carriers.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The product of two packed elements.

    Parameters
    ----------
    a : torch.Tensor
        Packed elements.
    b : torch.Tensor
        Packed elements, broadcastable with ``a``.

    Returns
    -------
    torch.Tensor
        ``<p1 p2, p1 r2 ⊕ p2 r1, p1 s2 ⊕ p2 s1, p1 t2 ⊕ p2 t1 ⊕ r1 s2ᵀ ⊕ r2 s1ᵀ>``.
    """
    p1, r1, s1, t1 = self.parts(a)
    p2, r2, s2, t2 = self.parts(b)
    outer = self._base.tensor_op
    return self.pack(
        self._base.tensor_op(p1, p2),
        self._plus(self._act(p1, r2, 1), self._act(p2, r1, 1)),
        self._plus(self._act(p1, s2, 1), self._act(p2, s1, 1)),
        self._plus(
            self._act(p1, t2, 2),
            self._act(p2, t1, 2),
            outer(r1.unsqueeze(-1), s2.unsqueeze(-2)),
            outer(r2.unsqueeze(-1), s1.unsqueeze(-2)),
        ),
    )

zero_like

zero_like(shape: tuple[int, ...], like: Tensor) -> Tensor

<0, 0, 0, 0> at every index.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device are used.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The zero.

Source code in src/quivers/core/carriers.py
def zero_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """``<0, 0, 0, 0>`` at every index.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device are used.

    Returns
    -------
    torch.Tensor
        The zero.
    """
    return self._base.zero_like((*shape, self._packed_size()), like)

unit_like

unit_like(shape: tuple[int, ...], like: Tensor) -> Tensor

<1, 0, 0, 0> at every index.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device are used.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The unit.

Source code in src/quivers/core/carriers.py
def unit_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """``<1, 0, 0, 0>`` at every index.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device are used.

    Returns
    -------
    torch.Tensor
        The unit.
    """
    zero = self.zero_like(shape, like)
    return torch.cat(
        (self._base.unit_like((*shape, 1), like), zero[..., 1:]), dim=-1
    )

contains

contains(t: Tensor) -> Tensor

Whether every part is in the base.

PARAMETER DESCRIPTION
t

Packed elements.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

One truth value per element.

Source code in src/quivers/core/carriers.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Whether every part is in the base.

    Parameters
    ----------
    t : torch.Tensor
        Packed elements.

    Returns
    -------
    torch.Tensor
        One truth value per element.
    """
    self._check(t)
    return self._base.contains(t).all(dim=-1)

star

star(t: Tensor, weights_star: ElementStar) -> Tensor

<p*, p*² r, p*² s, p*² t ⊕ 2 p*³ r sᵀ>, where p* exists.

It solves X = 1 ⊕ <p, r, s, t> ⊗ X using only p* = 1 ⊕ p p* and commutativity; the factor 2 is 1 ⊕ 1.

PARAMETER DESCRIPTION
t

Packed elements.

TYPE: Tensor

weights_star

The star of the weights, elementwise.

TYPE: ElementStar

RETURNS DESCRIPTION
Tensor

The packed star.

Source code in src/quivers/core/carriers.py
def star(self, t: torch.Tensor, weights_star: ElementStar) -> torch.Tensor:
    """``<p*, p*² r, p*² s, p*² t ⊕ 2 p*³ r sᵀ>``, where ``p*`` exists.

    It solves ``X = 1 ⊕ <p, r, s, t> ⊗ X`` using only
    ``p* = 1 ⊕ p p*`` and commutativity; the factor 2 is ``1 ⊕ 1``.

    Parameters
    ----------
    t : torch.Tensor
        Packed elements.
    weights_star : ElementStar
        The star of the weights, elementwise.

    Returns
    -------
    torch.Tensor
        The packed star.
    """
    p, r, s, products = self.parts(t)
    starred = weights_star(p)
    square = self._base.tensor_op(starred, starred)
    cube = self._base.tensor_op(square, starred)
    cross = self._base.tensor_op(r.unsqueeze(-1), s.unsqueeze(-2))
    twice = self._plus(cross, cross)
    return self.pack(
        starred,
        self._act(square, r, 1),
        self._act(square, s, 1),
        self._plus(self._act(square, products, 2), self._act(cube, twice, 2)),
    )

ProductSemiring

ProductSemiring(factors: Sequence[OrderPreservingSemiring])

Bases: _Packed

Several commutative semirings side by side.

An element is a tuple of elements, one per factor, packed by concatenation; every operation acts factor by factor. Factors have elements of rank at most one and share a tensor dtype.

PARAMETER DESCRIPTION
factors

The factors; each must claim a commutative product.

TYPE: Sequence of OrderPreservingSemiring

RAISES DESCRIPTION
TypeError

If there are fewer than two factors or one does not commute.

ValueError

If a factor's elements have rank above one.

Source code in src/quivers/core/carriers.py
def __init__(self, factors: Sequence[OrderPreservingSemiring]) -> None:
    if len(factors) < 2:
        raise TypeError("a product has at least two factors")
    for factor in factors:
        if TIMES_COMMUTATIVE not in factor.laws():
            raise TypeError(f"the product of {factor.name} does not commute")
    self._factors = tuple(factors)
    self._sizes = tuple(_size(factor.element_shape) for factor in factors)

factors property

factors: tuple[OrderPreservingSemiring, ...]

The factors.

RETURNS DESCRIPTION
tuple of OrderPreservingSemiring

The factors, in order.

name property

name: str

Product(<factor>, ...).

RETURNS DESCRIPTION
str

The name.

evidence

evidence(law: Law) -> LawEvidence

The evidence for a law; laws about the carrier hold by a theorem.

PARAMETER DESCRIPTION
law

A law the structure claims.

TYPE: Law

RETURNS DESCRIPTION
LawEvidence

The argument when the laws of every factor are established.

Source code in src/quivers/core/carriers.py
def evidence(self, law: Law) -> LawEvidence:
    """The evidence for a law; laws about the carrier hold by a theorem.

    Parameters
    ----------
    law : Law
        A law the structure claims.

    Returns
    -------
    LawEvidence
        The argument when the laws of every factor are established.
    """
    if law.scope == "carrier":
        if _established(*self._factors):
            return Proved(argument=f"{_PROOFS}#proof-product", sources=())
        return self.assumption("the laws of a factor are not established")
    return super().evidence(law)

parts

parts(t: Tensor) -> tuple[Tensor, ...]

The element of each factor.

PARAMETER DESCRIPTION
t

Packed elements.

TYPE: Tensor

RETURNS DESCRIPTION
tuple of torch.Tensor

One tensor per factor, with its element axes.

RAISES DESCRIPTION
ValueError

If t lacks the packed axis.

Source code in src/quivers/core/carriers.py
def parts(self, t: torch.Tensor) -> tuple[torch.Tensor, ...]:
    """The element of each factor.

    Parameters
    ----------
    t : torch.Tensor
        Packed elements.

    Returns
    -------
    tuple of torch.Tensor
        One tensor per factor, with its element axes.

    Raises
    ------
    ValueError
        If ``t`` lacks the packed axis.
    """
    self._check(t)
    found: list[torch.Tensor] = []
    start = 0
    for factor, size in zip(self._factors, self._sizes, strict=True):
        piece = t[..., start : start + size]
        found.append(piece.reshape(tuple(t.shape[:-1]) + factor.element_shape))
        start += size
    return tuple(found)

pack

pack(parts: Sequence[Tensor]) -> Tensor

Elements from one element per factor.

PARAMETER DESCRIPTION
parts

One tensor per factor, with its element axes.

TYPE: Sequence of torch.Tensor

RETURNS DESCRIPTION
Tensor

The packed elements.

Source code in src/quivers/core/carriers.py
def pack(self, parts: Sequence[torch.Tensor]) -> torch.Tensor:
    """Elements from one element per factor.

    Parameters
    ----------
    parts : Sequence of torch.Tensor
        One tensor per factor, with its element axes.

    Returns
    -------
    torch.Tensor
        The packed elements.
    """
    flat = [
        part.reshape(
            tuple(part.shape[: part.ndim - len(factor.element_shape)]) + (size,)
        )
        for part, factor, size in zip(
            parts, self._factors, self._sizes, strict=True
        )
    ]
    index = torch.broadcast_shapes(*(piece.shape[:-1] for piece in flat))
    return torch.cat(
        [piece.expand(*index, piece.shape[-1]) for piece in flat], dim=-1
    )

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

The product, factor by factor.

PARAMETER DESCRIPTION
a

Packed elements.

TYPE: Tensor

b

Packed elements, broadcastable with a.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The packed product.

Source code in src/quivers/core/carriers.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """The product, factor by factor.

    Parameters
    ----------
    a : torch.Tensor
        Packed elements.
    b : torch.Tensor
        Packed elements, broadcastable with ``a``.

    Returns
    -------
    torch.Tensor
        The packed product.
    """
    return self.pack(
        [
            factor.tensor_op(x, y)
            for factor, x, y in zip(
                self._factors, self.parts(a), self.parts(b), strict=True
            )
        ]
    )

zero_like

zero_like(shape: tuple[int, ...], like: Tensor) -> Tensor

The zero of every factor.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device are used.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The packed zero.

Source code in src/quivers/core/carriers.py
def zero_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """The zero of every factor.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device are used.

    Returns
    -------
    torch.Tensor
        The packed zero.
    """
    return self.pack([factor.zero_like(shape, like) for factor in self._factors])

unit_like

unit_like(shape: tuple[int, ...], like: Tensor) -> Tensor

The unit of every factor.

PARAMETER DESCRIPTION
shape

The index shape.

TYPE: tuple of int

like

The tensor whose dtype and device are used.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The packed unit.

Source code in src/quivers/core/carriers.py
def unit_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """The unit of every factor.

    Parameters
    ----------
    shape : tuple of int
        The index shape.
    like : torch.Tensor
        The tensor whose dtype and device are used.

    Returns
    -------
    torch.Tensor
        The packed unit.
    """
    return self.pack([factor.unit_like(shape, like) for factor in self._factors])

contains

contains(t: Tensor) -> Tensor

Whether every factor's element is in its carrier.

PARAMETER DESCRIPTION
t

Packed elements.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

One truth value per element.

Source code in src/quivers/core/carriers.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Whether every factor's element is in its carrier.

    Parameters
    ----------
    t : torch.Tensor
        Packed elements.

    Returns
    -------
    torch.Tensor
        One truth value per element.
    """
    found = [
        factor.contains(part)
        for factor, part in zip(self._factors, self.parts(t), strict=True)
    ]
    result = found[0]
    for item in found[1:]:
        result = result & item
    return result

star

star(t: Tensor, stars: Sequence[ElementStar]) -> Tensor

The star of every factor.

PARAMETER DESCRIPTION
t

Packed elements.

TYPE: Tensor

stars

The star of each factor.

TYPE: Sequence of ElementStar

RETURNS DESCRIPTION
Tensor

The packed star, which exists where every factor's does.

Source code in src/quivers/core/carriers.py
def star(self, t: torch.Tensor, stars: Sequence[ElementStar]) -> torch.Tensor:
    """The star of every factor.

    Parameters
    ----------
    t : torch.Tensor
        Packed elements.
    stars : Sequence of ElementStar
        The star of each factor.

    Returns
    -------
    torch.Tensor
        The packed star, which exists where every factor's does.
    """
    return self.pack(
        [star(part) for star, part in zip(stars, self.parts(t), strict=True)]
    )

signed_log

A packed signed logarithmic carrier for first-order weight derivatives.

SignedLogDualSemiring

Bases: _Packed

A real dual algebra with independently signed log primal and tangent.

Each element stores (sign, log_abs, tangent_sign, tangent_log_abs). Zero in either component is (0, -inf). A zero primal can have a nonzero tangent. The operations carry one supplied direction without differentiating the sign or logarithm of the primal representation.

The carrier uses float64 arithmetic. Equal represented magnitudes cancel in a multiway sum before other additions. Detectable disappearance of a nonzero summand raises a numerical error. Algebraic laws concern the decoded ideal dual algebra.

name property

name: str

The name of the signed log dual algebra.

evidence

evidence(law: Law) -> LawEvidence

Give the ideal carrier evidence for the requested law.

Source code in src/quivers/core/signed_log.py
def evidence(self, law: Law) -> LawEvidence:
    """Give the ideal carrier evidence for the requested law."""
    if law.scope == "carrier" and law in self.laws():
        return Proved(argument="api/core/carriers.md#proof-signed-log-dual")
    return super().evidence(law)

pack

pack(primal: Tensor, tangent: Tensor) -> Tensor

Combine two broadcastable canonical signed log pairs.

Source code in src/quivers/core/signed_log.py
def pack(self, primal: torch.Tensor, tangent: torch.Tensor) -> torch.Tensor:
    """Combine two broadcastable canonical signed log pairs."""
    _check_pair(primal)
    _check_pair(tangent)
    return torch.cat(torch.broadcast_tensors(primal, tangent), dim=-1)

parts

parts(value: Tensor) -> tuple[Tensor, Tensor]

Return the primal and tangent pairs without changing their encoding.

Source code in src/quivers/core/signed_log.py
def parts(self, value: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Return the primal and tangent pairs without changing their encoding."""
    self._check(value)
    primal, tangent = value[..., :2], value[..., 2:]
    _check_pair(primal)
    _check_pair(tangent)
    return primal, tangent

from_linear

from_linear(primal: Tensor, tangent: Tensor) -> Tensor

Embed two finite float64 components as a dual number.

Source code in src/quivers/core/signed_log.py
def from_linear(self, primal: torch.Tensor, tangent: torch.Tensor) -> torch.Tensor:
    """Embed two finite float64 components as a dual number."""
    return self.pack(_encode(primal), _encode(tangent))

to_linear

to_linear(value: Tensor) -> tuple[Tensor, Tensor]

Decode both components, refusing an unrepresentable nonzero value.

Source code in src/quivers/core/signed_log.py
def to_linear(self, value: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Decode both components, refusing an unrepresentable nonzero value."""
    primal, tangent = self.parts(value)
    return _decode(primal), _decode(tangent)

contains

contains(t: Tensor) -> Tensor

Return a Boolean tensor for the canonical primal and tangent pairs.

Source code in src/quivers/core/signed_log.py
def contains(self, t: torch.Tensor) -> torch.Tensor:
    """Return a Boolean tensor for the canonical primal and tangent pairs."""
    self._check(t)
    self._check_dtype(t)
    return _canonical(t[..., :2]) & _canonical(t[..., 2:])

tensor_op

tensor_op(a: Tensor, b: Tensor) -> Tensor

Multiply the primal coefficients and apply the product rule.

Source code in src/quivers/core/signed_log.py
def tensor_op(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """Multiply the primal coefficients and apply the product rule."""
    x, dx = self.parts(a)
    y, dy = self.parts(b)
    return torch.cat(
        (_multiply(x, y), _add(_multiply(x, dy), _multiply(y, dx))), dim=-1
    )

positive_quotient

positive_quotient(numerator: Tensor, denominator: Tensor) -> Tensor

Divide dual numbers by a dual with positive primal coefficient.

PARAMETER DESCRIPTION
numerator

Two canonical encoded dual numbers, with broadcastable shapes.

TYPE: Tensor

denominator

Two canonical encoded dual numbers, with broadcastable shapes.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The quotient and its directional coefficient in signed log.

RAISES DESCRIPTION
ValueError

If a denominator primal is not positive.

FloatingPointError

If the encoded arithmetic exceeds float64 precision.

Source code in src/quivers/core/signed_log.py
def positive_quotient(
    self, numerator: torch.Tensor, denominator: torch.Tensor
) -> torch.Tensor:
    """Divide dual numbers by a dual with positive primal coefficient.

    Parameters
    ----------
    numerator, denominator
        Two canonical encoded dual numbers, with broadcastable shapes.

    Returns
    -------
    torch.Tensor
        The quotient and its directional coefficient in signed log.

    Raises
    ------
    ValueError
        If a denominator primal is not positive.
    FloatingPointError
        If the encoded arithmetic exceeds float64 precision.
    """
    primal, tangent = self.parts(denominator)
    sign, log_value = primal.unbind(-1)
    if bool((sign != 1).any()):
        raise ValueError("a signed log dual quotient requires a positive primal")
    dsign, dlog = tangent.unbind(-1)
    inverse = self.pack(
        _pair(sign, -log_value),
        _pair(-dsign, dlog - log_value - log_value),
    )
    return self.tensor_op(numerator, inverse)

zero_like

zero_like(shape: tuple[int, ...], like: Tensor) -> Tensor

Broadcast the canonical primal and tangent zero to the index shape.

Source code in src/quivers/core/signed_log.py
def zero_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """Broadcast the canonical primal and tangent zero to the index shape."""
    self._check_dtype(like)
    return like.new_tensor((0, -torch.inf, 0, -torch.inf)).expand((*shape, 4))

unit_like

unit_like(shape: tuple[int, ...], like: Tensor) -> Tensor

Broadcast the canonical primal one and tangent zero.

Source code in src/quivers/core/signed_log.py
def unit_like(self, shape: tuple[int, ...], like: torch.Tensor) -> torch.Tensor:
    """Broadcast the canonical primal one and tangent zero."""
    self._check_dtype(like)
    return like.new_tensor((1, 0, 0, -torch.inf)).expand((*shape, 4))