Skip to content

7. Categorical foundations

QVR types its declarations by objects and morphisms, composes morphisms under a chosen pair of operations, and converts a morphism from one pair of operations to another with change_base. In the terms of category theory, the morphisms of a module are matrices in a category of matrices, errors such as incompatible algebras: ProductFuzzyAlgebra() and MarkovAlgebra() come from composing matrices under different operations, and a probabilistic program denotes a Markov kernel.

Morphisms as matrices

A category has objects, morphisms between them, an associative composition of morphisms, and an identity morphism on each object (Mac Lane, 1998). In QVR an object A : FinSet n is a finite set of size \(n\), and a morphism f : A -> B is a tensor of shape (|A|, |B|) whose entries lie in a set \(V\) of weights. Composition is the matrix product over two operations on \(V\), a product \(\otimes\) and a sum \(\oplus\):

\[ (f \mathbin{>\!\!>} g)[a, c] = \bigoplus_{b \in B} f[a, b] \otimes g[b, c]. \]

The codomain of f must equal the domain of g, and two FinSet objects are equal only when their names and sizes agree. A declaration object B : FinSet 3 makes a finite set named B, so in a .qvr file f : A -> B and g : C -> D do not compose when B and C are distinct objects of the same size, and the compiler reports cannot compose: codomain ... != domain ....

The choice of \((\otimes, \oplus)\) fixes what composition computes. With AND and OR it says whether a path exists, with product and sum it adds the probabilities of mutually exclusive routes, and with \(+\) and \(\min\) it finds the cheapest route. When \((V, \oplus, \otimes)\) is a semiring, the \(V\)-valued matrices form a category, often written \(\mathbf{Mat}(V)\), because distributivity makes the matrix product associative and the identity matrix is a unit (Mohri, 2002; Hofmann et al., 2014). When \(V\) is a quantale, a complete lattice with an associative product that distributes over arbitrary joins, the matrices form a quantaloid (Rosenthal, 1996). Without these laws, rebracketing a composite or inserting an identity may change the result, so check the laws of the chosen operations before simplifying a computation. The semantics states the construction in full.

A \(\mathcal V\)-enriched category in Kelly's sense has, in place of each hom-set (the set of morphisms between two objects), a hom-object in a monoidal category \(\mathcal V\) (Kelly, 1982). The category of \(V\)-matrices is not enriched over \(V\) in that sense: each of its hom-sets is a set of matrices. For a quantale \(V\), each hom-set is itself a complete lattice and composition preserves joins in each argument, which is what makes the category a quantaloid, that is, a category enriched over complete lattices.

Typed errors

Types and composition rules let the compiler reject two kinds of mistake before any tensor is evaluated. A program declared Pure whose body observes:

object Item : FinSet 3

export program p : Item -> Item [effects=[Pure]]
    observe y : Item <- Normal(loc=0.0, scale=1.0)
    return y
CompileError: line 3, col 7: program 'p' is declared as Pure but body uses effects ['Score']

A composite of morphisms with different weights:

composition product_fuzzy [level=algebra]

object A : FinSet 3
object B : FinSet 4
object C : FinSet 2

morphism f : A -> B [role=parameter]
morphism h : B -> C [role=parameter]

define g = h.change_base(softmax(C))
export define pipeline = f >> g
CompileError: line 11, col 25: incompatible algebras: ProductFuzzyAlgebra() and MarkovAlgebra()

f has entries in \([0, 1]\) composed by noisy-OR, while g is a row-stochastic matrix composed by sum and product. Without the check, f >> g would run and mix the two readings.

Composition rules and their laws

An Algebra gives \(\otimes\), \(\oplus\) (the method join), the unit of \(\otimes\), a zero, a meet, and a negation. The library checks none of the laws, so each instance below is named by the structure it is:

Name \(\otimes\) \(\oplus\) Unit Structure
Boolean AND OR true Boolean semiring. Its matrices are relations.
ProductFuzzy \(a b\) \(1 - \prod_i (1 - x_i)\) 1 Product t-norm with the probabilistic sum (noisy-OR) (Klement et al., 2000; Pearl, 1988). Not a semiring.
Lukasiewicz \(\max(0, a + b - 1)\) \(\min(1, \sum_i x_i)\) 1 Łukasiewicz t-norm with the bounded sum (Klement et al., 2000). Not a semiring.
Godel \(\min(a, b)\) \(\max_i x_i\) 1 Minimum (Gödel) t-norm with the maximum, a semiring on \([0, 1]\).
Tropical \(a + b\) \(\min_i x_i\) 0 Tropical (min-plus) semiring on \([0, \infty]\): cheapest paths (Mohri, 2002).
MaxPlus \(a + b\) \(\max_i x_i\) 0 Max-plus semiring: the best path, as in the Viterbi algorithm (Goodman, 1999).
LogProb \(a + b\) \(\mathrm{logsumexp}_i\, x_i\) 0 Log semiring: sum and product of probabilities in log space (Mohri, 2002).
Markov \(a b\) \(\sum_i x_i\) 1 Sum-product semiring, used for row-stochastic matrices.
Real \(a b\) \(\sum_i x_i\) 1 The ring \((\mathbb R, +, \times)\).
Probability \(a b\) \(\min(1, \sum_i x_i)\) 1 Product with a capped sum on \([0, 1]\). Not a semiring.
Counting \(a b\) \(\sum_i x_i\) 1 Counting semiring on \(\mathbb N\): the number of paths (Goodman, 1999).

composition product_fuzzy [level=algebra] at the top of a .qvr file sets the operations for every >> in the module. The level states which laws the rule claims, unchecked:

CompositionRule
    ├── Magmoid           (level magmoid: no associativity or identity)
    ├── Semigroupoid      (level semigroupoid: associative, no identity)
    ├── Algebra           (level algebra: identity, unit, zero, meet, and negation)
    └── Semiring          (an Algebra and a Semigroupoid: associative with identity)
            └── IdempotentSemiring  (idempotent sum)

Under a rule declared semigroupoid the morphisms form a semicategory, a category without identities (Tilson, 1987). Under magmoid composition has no laws at all (the structure is a magmoid). The eight semirings in the table are of class Semiring, so either level accepts them, and the other three are of class Algebra only. identity(A) and the operations cup(A), cap(A), f.dagger, and f.trace(A), which bend, transpose, and loop the wires of a compact closed category, need an Algebra. Under composition material_impl [level=magmoid], identity(A) fails with

CompileError: line 3, col 11: identity: requires an algebra-level composition rule (one with an identity, a unit, and a zero); the module declares the magmoid 'MaterialImplication', which has none. Declare an algebra, as in `composition product_fuzzy [level=algebra]`, or drop the identity operation.

The rule material_impl uses the Reichenbach implication \(a \to b = 1 - a + ab\) (Baczyński and Jayaram, 2008) as \(\otimes\) and the product as \(\oplus\). That \(\otimes\) is not associative, so the rule is a Magmoid, and composites under it must not be rebracketed. Chapter 7 of the Python track covers the hierarchy in detail.

Composition operators

Operator Meaning
>> Composition in the operands' shared composition rule.
<< The same composite written right to left: g << f is f >> g.

f >> g fails when the operands' rules differ. No operator changes the rule silently. To compose across rules, apply change_base to one operand first.

Change of base

f.change_base(phi) applies a map phi to the tensor of f and retags the result with the target rule. phi is one of two kinds:

  • An entrywise map (class CarrierMap) applies a function \(\varphi : V \to W\) to each entry. When \(\varphi\) is monotone and lax for \(\otimes\), \(\oplus\), and the unit, it induces change of base in Kelly's sense (Kelly, 1982). The named maps include expectation (from Markov to ProductFuzzy, reading each probability as a degree of membership), log_prob, max_plus, threshold, and boolean_embedding.
  • A MorphismTransformation rewrites the whole tensor, for instance normalizing each row. The constructors softmax(B), l1_normalize(B), and l2_normalize(B) normalize along the axis of B, and bayes_invert(prior) computes a Bayesian inversion (Cho and Jacobs, 2019). A row normalization is not a change of base.

Both kinds are values: a define can bind them, >>> composes them, and change_base applies them:

composition product_fuzzy [level=algebra]
object A : FinSet 3
object B : FinSet 4
morphism f : A -> B [role=parameter]

define s = softmax(B)
define pipeline = s >>> expectation
define g = f.change_base(pipeline)

softmax(B) maps ProductFuzzy to Markov, normalizing each row, and expectation maps Markov back to ProductFuzzy. g thus has the rule of f, with each row normalized to sum to one. Chapter 6 of the Python track gives the full interface.

Probabilistic programs as kernels

A Markov kernel from \(X\) to \(Y\) assigns to each \(x\) a probability distribution on \(Y\). Markov kernels are the morphisms of the Kleisli category of the Giry monad, which sends a space to the space of probability distributions on it (Giry, 1982). A program without observe or score denotes such a kernel. observe and score multiply the result by a density or by \(\exp(w)\), which may exceed one, so a program that uses them denotes a kernel into unnormalized measures (an s-finite kernel) (Staton, 2017). Each step acts on the running set of bindings and its log weight:

  • let v <- sample F(args) draws v from F(args).
  • observe v <- F(args) keeps the observed value of v and adds its log density to the log weight.
  • score w = expr adds expr to the log weight.
  • let v = expr binds v to a deterministic value.
  • marginalize v : A <- F(args) runs its indented body once for each element of the finite set A and combines the resulting log weights (chapter 4).
  • return v keeps v and discards the other bindings.

For the regression of chapter 1, the kernel draws sigma, beta_0, and beta_1, and its weight is the Normal density of the observed y. Stochastic variational inference (SVI) fits a guide to the normalized posterior, and the No-U-Turn Sampler (NUTS) samples it through the log joint density. Neither changes the program that defines the model. The compiler checks the effect summary (Sample, Score, Marginal, Pure) against the body, and chapter 10 introduces the finer effect rows of the core language.

Next

Chapter 8 checks convergence, compares the data with posterior predictive draws, and compares models by leave-one-out cross-validation. The semantics gives the denotation of every construct, and the examples gallery gives complete models.

Cited sources

Saunders Mac Lane. Categories for the Working Mathematician. Volume 5 of Graduate Texts in Mathematics. Springer, 2 edition, 1998. URL: https://link.springer.com/book/10.1007/978-1-4757-4721-8, doi:10.1007/978-1-4757-4721-8.

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.

Dirk Hofmann, Gavin J. Seal, and Walter Tholen, editors. Monoidal Topology: A Categorical Approach to Order, Metric, and Topology. Cambridge University Press, 2014. doi:10.1017/CBO9781107517288.

K. I. Rosenthal. The Theory of Quantaloids. Chapman \\& Hall, 1 edition, 1996. URL: https://www.routledge.com/The-Theory-of-Quantaloids/Rosenthal/p/book/9780429157028.

G. M. Kelly. Basic Concepts of Enriched Category Theory. Cambridge University Press, 1982. Reprinted in Reprints in Theory and Applications of Categories 10 (2005), 1–136. URL: https://www.tac.mta.ca/tac/reprints/articles/10/tr10abs.html.

Erich Peter Klement, Radko Mesiar, and Endre Pap. Triangular Norms. Trends in Logic. Springer, 2000. doi:10.1007/978-94-015-9540-7.

Judea Pearl. Probabilistic Reasoning in Intelligent Systems: Networks of Plausible Inference. Morgan Kaufmann, 1988. doi:10.1016/C2009-0-27609-4.

Joshua Goodman. Semiring Parsing. Computational Linguistics, 25(4):573–606, 1999. URL: https://aclanthology.org/J99-4004/.

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.

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.

Michèle Giry. A Categorical Approach to Probability Theory. In B. Banaschewski, editor, Categorical Aspects of Topology and Analysis, volume 915 of Lecture Notes in Mathematics, pages 68–85. Springer, 1982. URL: https://link.springer.com/chapter/10.1007/BFb0092872, doi:10.1007/BFb0092872.

Sam Staton. Commutative Semantics for Probabilistic Programming. In Programming Languages and Systems (ESOP 2017), Lecture Notes in Computer Science, 855–879. Springer, 2017. doi:10.1007/978-3-662-54434-1_32.