7. Composition rules beyond algebras¶
f >> g needs two operations on weights: a product \(\otimes\) (the method tensor_op) that combines the entries along a path, and a sum \(\oplus\) (the method join) that reduces the shared axis. A CompositionRule is any such pair. The laws the pair satisfies decide which rewrites of a composite keep its value: associativity allows replacing (f >> g) >> h by f >> (g >> h), and an identity allows inserting an identity morphism. When \(\otimes\) and \(\oplus\) form a semiring, the matrix product they define is associative and the identity matrix is its unit (Mohri, 2002). Without those laws a rewrite can change the result, as chapter 1 showed for PRODUCT_FUZZY. A rule's class records which laws it claims, and EinsumWiring computes contractions of more than two tensors.
The hierarchy¶
A rule's class states which laws it claims. Each claim carries its evidence in a
law record: proved, decided, tested, or assumed. The laws of the built-in
algebras are proved, and the associativity of a rule built with semigroupoid(...) is assumed after
a test on random inputs:
| Class (QVR level) | Claims | Structure of the morphisms |
|---|---|---|
Semiring (algebra or semigroupoid) |
the semiring laws, so associativity and an identity | a category |
IdempotentSemiring (the same) |
a semiring whose \(\oplus\) is idempotent | a category whose hom-sets are lattices |
Algebra (algebra) |
an identity, with a unit, a zero, a meet, and a negation | identities, with composition that may depend on bracketing |
Semigroupoid (semigroupoid) |
associativity, no identity | a semicategory (semigroupoid) (Tilson, 1987) |
Magmoid (magmoid) |
nothing | a magmoid: composition with no laws |
CompositionRule (rule) |
nothing | the base class of the others |
classDiagram
class CompositionRule {
"tensor_op + join, no algebraic promises"
}
class Magmoid {
"no promises"
}
class Semigroupoid {
"associative tensor_op, no identity"
}
class Algebra {
"identity + unit + zero + meet + negate"
}
class Semiring {
"associative + identity"
}
class IdempotentSemiring {
"idempotent join, a lattice"
}
CompositionRule <|-- Magmoid
CompositionRule <|-- Semigroupoid
CompositionRule <|-- Algebra
Semigroupoid <|-- Semiring
Algebra <|-- Semiring
Semiring <|-- IdempotentSemiring
Code that needs identity, dagger, trace, cup, or cap requires an Algebra, code that rebrackets composites requires at least a Semigroupoid, and code that only contracts tensors accepts any CompositionRule.
from quivers.core.algebras import (
CompositionRule, Semigroupoid, Magmoid, Algebra,
PRODUCT_FUZZY, REAL,
material_implication, semigroupoid, magmoid,
)
Every built-in instance is an Algebra, and the semirings among them are also of class Semiring, and so of Semigroupoid. PRODUCT_FUZZY is an Algebra and not a Semiring: its product does not distribute over its noisy-OR, and its composition is not associative. claims lists the claims of an instance with their evidence, and establishes asks whether given laws are proved or decided.
Rules below Algebra¶
material_implication() returns a CustomMagmoid whose \(\otimes\) is the Reichenbach implication \(a \to b = 1 - a + ab\) (Baczyński and Jayaram, 2008) and whose \(\oplus\) is the product. This \(\otimes\) has the left identity 1, since \(1 \to b = b\), but no two-sided identity, which is why the rule is not an Algebra. It is also not associative: with \(a = b = c = 0.5\), \((a \to b) \to c = 0.625\) and \(a \to (b \to c) = 0.875\). It is thus a Magmoid, and composites under it must keep their bracketing.
import torch
from quivers.core.algebras import material_implication
mi = material_implication()
print(type(mi).__mro__) # (CustomMagmoid, Magmoid, CompositionRule, Lawful, ABC, object)
f = torch.tensor([[0.3, 0.5, 0.2]])
g = torch.tensor([
[0.6, 0.4],
[0.1, 0.9],
[0.7, 0.2],
])
out = mi.compose(f, g, n_contract=1)
print(out.shape) # torch.Size([1, 2])
semigroupoid(name, tensor_op, join) builds a rule from an associative \(\otimes\) and a reduction:
from quivers.core.algebras import semigroupoid
def bounded_sum(a, b):
return (a + b).clamp(max=1.0)
def max_reduce(t, dim):
if isinstance(dim, int):
dim = (dim,)
result = t
for d in sorted(dim, reverse=True):
result = result.max(dim=d).values
return result
bsm = semigroupoid("BoundedSumMax", bounded_sum, max_reduce)
At construction it tests associativity of \(\otimes\) on a fixed set of random inputs and raises if the test fails. verify_associative=False skips the test, for an operation known to be associative whose test fails only by rounding.
Building a rule without laws¶
magmoid(name, tensor_op, join) builds a rule that claims nothing. The midpoint \((a + b)/2\) is not associative:
from quivers.core.algebras import magmoid
def midpoint(a, b):
return 0.5 * (a + b) # not associative
def sum_reduce(t, dim):
if isinstance(dim, int):
dim = (dim,)
return t.sum(dim=dim)
bf = magmoid("Midpoint", midpoint, sum_reduce)
# Three-way composition order matters:
a, b, c = torch.tensor(0.3), torch.tensor(0.5), torch.tensor(0.7)
left = bf.tensor_op(bf.tensor_op(a, b), c)
right = bf.tensor_op(a, bf.tensor_op(b, c))
assert not torch.allclose(left, right)
magmoid(...) runs no test. Rules whose reduction is not the addition of a semiring, such as a top-\(k\) truncation or a sum weighted by a softmax, generally lose associativity and belong at this level.
Operations that need an identity¶
unit, identity_tensor, and the operations of a compact closed category (cup, cap, dagger, trace, which bend, transpose, and loop wires) need an identity, so a rule below Algebra lacks them and raises AttributeError:
from quivers.core.algebras import material_implication
mi = material_implication()
for attribute in ("unit", "identity_tensor"):
try:
getattr(mi, attribute)
except AttributeError:
print(attribute, "is unavailable on", type(mi).__name__)
In QVR, identity(A), cup(A), cap(A), f.dagger, and f.trace(A) fail to compile in a module whose rule is not an Algebra, such as an inline rule declared [level=semigroupoid] or [level=magmoid] (chapter 7 of the QVR track).
Contractions of several tensors¶
Binary composition is f >> g, with the shared axis taken from the morphisms' types. EinsumWiring is for a contraction of three or more tensors at once, such as
The spec is written in Einstein summation (einsum) notation, as in torch.einsum: each input lists its axis letters, the right side of the arrow lists the output letters, and a letter that appears in an input and not in the output is reduced by \(\oplus\). torch.einsum fixes \(\otimes\) and \(\oplus\) to product and sum, so torch.einsum("sp, sq, pqo -> so", a, b, c) equals einsum_wiring(REAL, "sp, sq, pqo -> so").apply(a, b, c). Operations of this kind form the operad of wiring diagrams (Spivak, 2013).
from quivers.core.wiring import EinsumWiring, einsum_wiring, contract
wiring = einsum_wiring(PRODUCT_FUZZY, "sp, sq, pqo -> so")
print(wiring.input_arity) # 3
print(wiring.composition_rule) # ProductFuzzyAlgebra()
torch.manual_seed(0)
arg1 = torch.rand(4, 3)
arg2 = torch.rand(4, 5)
kernel = torch.rand(3, 5, 2)
out = wiring.apply(arg1, arg2, kernel)
print(out.shape) # torch.Size([4, 2])
How apply evaluates the contraction depends on the laws the rule establishes, never on its name:
- When the rule establishes the commutative-semiring laws of
ELIMINATION_LAWS, a summed letter is removed by multiplying only the inputs that contain it and reducing it with \(\oplus\) (variable elimination), in an order thatplanchooses greedily. The largest intermediate tensor then has the size of the largest bag of that order, not the product of every extent. - Any other rule is evaluated in the written order: the inputs are combined with \(\otimes\) from left to right over every letter, and the contracted letters are then reduced with \(\oplus\). The order of the inputs thus matters for a rule whose \(\otimes\) is not associative.
apply_with_work
returns the output with a report of the sums, products, and elements it formed, and
complexity gives the cost
claim that applies to the rule. EinsumWiring accepts any CompositionRule, including rules below
Algebra:
mi = material_implication()
wmi = einsum_wiring(mi, "ij, jk -> ik")
out = wmi.apply(
torch.rand(2, 2),
torch.rand(2, 2),
)
Validation¶
einsum_wiring checks the spec when it is built and raises ValueError when:
- An input is empty.
- An input repeats a letter (
"ii, jk -> ik"), since a diagonal or trace contraction is not supported. - The output repeats a letter (
"ij, jk -> iik"). - An output letter appears in no input (
"ij, jk -> iz").
apply checks the number of tensors and the number of axes of each, and raises ValueError when two inputs give one letter different extents.
From QVR¶
A composition declaration selects a built-in rule by name, or defines one inline with an indented body. A module has one, so each of the following is a module of its own. An algebra gives its product, its join, and their units:
A semigroupoid needs no units:
A magmoid's product need not be associative:
A declaration without a body selects a rule from the catalog:
level is one of algebra, semigroupoid, magmoid, and rule. Without a body, the name selects a rule from the built-in catalog (product_fuzzy, material_impl, and the others), and the compiler checks that it has the declared level.
A contraction declares a named contraction of several morphisms:
object A : FinSet 4
object B : FinSet 3
object C : FinSet 5
object D : FinSet 2
morphism arg1_morph : A -> B [role=parameter]
morphism arg2_morph : A -> C [role=parameter]
morphism kernel_morph : B * C -> D [role=parameter]
contraction op_apply (
arg1 : A -> B,
arg2 : A -> C,
kernel : B * C -> D,
) : A -> D [rule=product_fuzzy, wiring="sp, sq, pqd -> sd"]
define combined = op_apply(arg1_morph, arg2_morph, kernel_morph)
export combined
op_apply can be called wherever a morphism is expected. Each call checks the number of arguments and the number of entries of each against the declared signature, then applies the EinsumWiring to the arguments' tensors. Without wiring=, the compiler infers the spec from the axis names of the signature (contractions guide).
Next¶
Chapter 8 fits regression formulas: a fit("y ~ x + (1|g)", data=df, ...) call, the QVR program it compiles to, the No-U-Turn Sampler (NUTS), PSIS-LOO model comparison, and posterior predictive checks.
Cited sources¶
Mehryar Mohri. Semiring Frameworks and Algorithms for Shortest-Distance Problems. Journal of Automata, Languages and Combinatorics, 7(3):321–350, 2002. doi:10.25596/jalc-2002-321.
Bret Tilson. Categories as Algebra: An Essential Ingredient in the Theory of Monoids. Journal of Pure and Applied Algebra, 48(1–2):83–198, 1987. doi:10.1016/0022-4049(87)90108-3.
Michał Baczyński and Balasubramaniam Jayaram. Fuzzy Implications. Studies in Fuzziness and Soft Computing. Springer, 2008. doi:10.1007/978-3-540-69082-5.
David I. Spivak. The Operad of Wiring Diagrams: Formalizing a Graphical Language for Databases, Recursion, and Plug-and-Play Circuits. 2013. arXiv:1305.0297, doi:10.48550/arXiv.1305.0297.