Manuscript Offprint
arXiv:2609.40046Freely Generated Categorical Structures and Automatic Differentiation, PhD Thesis (Introduction and Conclusion)
About this version
This version contains the introduction, conclusion, and Dutch and English summaries of the doctoral thesis Freely generated categorical structures and automatic differentiation. The six research papers forming Chapters 2–7 of the full thesis are not reproduced here; they are available separately at the links below. The original chapter numbering is retained: the introduction is Chapter 1 and the conclusion is Chapter 8. Throughout this version, references to chapters and descriptions of the thesis structure refer to the full thesis. The bibliography contains the works cited in this version.
Chapters 2, 3, 5 and 7 are joint work with Matthijs Vákár; Chapter 4 is joint work with Gordon Plotkin and Matthijs Vákár; and Chapter 6 is joint work with Rui Prezado and Matthijs Vákár. In the joint papers forming Chapters 2–7 of the full thesis, I took a leading role in the mathematical development and preparation of the manuscripts, with particular responsibility for the formulation and proof of the main results. The work was developed in close collaboration with the coauthors named above, through sustained discussion and refinement of the ideas, arguments and exposition.
arXiv:2210.07724v3.
- CHAD for expressive total languages [21].
arXiv:2110.00446v2.
- Unraveling the iterative CHAD [26].
arXiv:2505.15002v3.
-
Free Doubly-Infinitary Distributive Categories are Cartesian Closed [25]. Published article; arXiv:2403.10447v10.
-
Free extensivity via distributivity [27].
Published article; arXiv:2405.02185.
- Monoidal closure of Grothendieck constructions via -tractable monoidal structures and Dialectica formulas [24].
Published article; arXiv:2405.07724v4.
iii
Contents
About this version iii
1 Introduction 1
1.1 Reverse-mode Automatic Differentiation 1
1.2 Categorical Semantics of Programming Languages 2
1.3 Functionality 3
1.4 Expressiveness 6
1.5 Freely generated categorical structures 9
1.6 AD from universal properties 10
1.7 Free extensivity and distributivity 11
1.8 Grothendieck constructions 12
1.9 Extensivity and related contributions 12
1.10 Contributions and Thesis Outline 13
8 Conclusion and Future Work 17
Bibliography 21
Samenvatting 25
Summary 29
V
CHAPTER 1
Introduction
This thesis rests on the conviction that theory and practice in computer science should inform one another. As Donald Knuth emphasised in Theory and Practice [17], theoretical and practical work gain from sustained interaction. Semantic foundations can clarify what an implementation must achieve and provide methods for establishing its correctness. Conversely, the demands of implementation can reveal questions that are not apparent from an abstract formulation alone. The work presented here develops this interaction through automatic differentiation and categorical semantics.
In programming languages, this principle takes a concrete form: practical language features guide the theoretical questions, while semantic frameworks provide a basis for specifying transformations and proving them correct. The resulting constructions may, in turn, suggest improvements to the language or its implementation.
Differentiable programming [6, 12] exemplifies this interaction. It plays a substantial role in scientific computing, machine learning, and optimisation. Its central idea is to compute derivatives of the functions denoted by programs, making differentiation available as part of programming itself. At the heart of this approach lies a systematic program transformation implementing the chain rule of calculus: automatic differentiation (AD). AD has a long history, from its early development in numerical analysis [12] to its reformulation in functional settings and more recent semantic treatments [1, 10].
In this thesis, automatic differentiation provides the concrete problem through which we develop and evaluate semantic frameworks for programming languages. We seek a compile-time AD transformation for expressive languages, together with a precise semantics and a proof that the generated program computes the derivative of the original. Universal properties determine the transformation from its action on primitives; correctness additionally requires correct primitive derivatives and a semantic argument relating the transformed program to differentiation. This separation makes the construction modular and provides a foundation for subsequent work on optimisation, efficiency, and parallelism.
1.1 Reverse-mode Automatic Differentiation
Automatic differentiation raises a semantic question as well as an algorithmic one: how should a language represent derivatives, and how should differentiation interact with its constructs? Reverse mode makes these questions particularly apparent.
Reverse-mode automatic differentiation transforms a program so that, in addition to its original outputs, it computes co-derivatives, namely the action of the transpose of the derivative on cotangent vectors. For , a reverse pass computes for an output cotangent , whereas a forward pass computes for an input tangent . Recovering the full Jacobian requires such reverse passes or forward passes. Reverse
1. Introduction
mode is therefore particularly attractive when there are many inputs and few outputs, as in the scalar loss functions of machine learning; forward mode is often preferable in the opposite regime. Actual costs also depend on the implementation and its storage requirements [6, 12].
At the same time, reverse-mode AD exposes a persistent gap between practical implementations and semantic foundations. Achieving a correct and efficient source-to-source transformation for expressive higher-order languages requires threading derivative computations through programs in a way that preserves their structure and intent. Widely used frameworks such as TensorFlow [2], PyTorch [33], and JAX [7] combine graph representations, tracing, compilation, and runtime support in different ways. The question pursued here concerns the language-level foundations: how to derive a compositional source transformation and prove its correctness for the constructs of an expressive typed language.
This difficulty leads to the central question of the thesis: can both forward- and reverse-mode AD be formulated as compositional compile-time transformations with correctness proofs for expressive programming languages supporting inductive types, recursion, non-termination, and other advanced features? We argue that categorical semantics provides a suitable framework. Our approach builds on the categorical treatment of forward-mode AD via dual numbers for the simply typed λ-calculus [14], Elliott's categorical account of AD [10], and Vákár's reverse-mode transformation for the simply typed λ-calculus [40], known as Combinatory Homomorphic Automatic Differentiation (CHAD).
1.2 Categorical Semantics of Programming Languages
Category theory has long provided a rigorous mathematical foundation for the semantics of programming languages, offering a precise framework for their denotational interpretation. Seminal works such as Lambek and Scott's introduction to higher-order categorical logic [18], Crole's Categories for Types [8], and Jacobs' Categorical Logic and Type Theory [15] demonstrate how rich type theories and λ-calculi can be modelled by categorical structures including cartesian closed categories, indexed categories, and Freyd categories.
From the outset, categorical methods have profoundly influenced both the theory and practice of programming languages. The following examples highlight some of the landmark developments:
• Moggi’s use of monads in programming-language semantics provided a unifying account of computational effects [31, 32], including state, exceptions, nondeterminism, partiality, continuations, probabilistic choice, and I/O. Since then, monads have become a standard tool in semantic modelling and in functional programming, most notably through their adoption in Haskell.
• Fiore and Plotkin’s axiomatic domain theory identified categorical conditions, such as algebraic compactness, that solve recursive domain equations and thereby deliver a uniform treatment of recursive types and domains [11].
• Plotkin and Power’s theory of algebraic effects refined the monadic approach through algebraic theories; subsequent work on effect handlers further developed this modular treatment of computational effects.
• Levy’s Call-by-Push-Value (CBPV) analyses call-by-name and call-by-value within a common calculus of values and computations, with adjunctions playing a central role in its semantics [19, 20].
In this tradition, the aim of this thesis is to develop categorical methods that inform the design of program transformations and support proofs of their correctness. The resulting account of AD also raises questions of wider interest in categorical semantics, particularly concerning the structure of free constructions and indexed models.
On the one hand, categorical insights yield structure-preserving AD transformations with transparent correctness proofs. On the other hand, the demands of real implementations expose the limitations of existing frameworks and stimulate the development of richer theories that remain accountable to practice. Throughout this thesis, AD thus serves simultaneously as a stress test and a catalyst: it presses semantic frameworks to their limits while also benefiting from the conceptual clarity and guarantees they provide.
1.3 Functoriality
We now cast automatic differentiation in categorical terms. This is natural, since the chain rule ensures that differentiation respects identities and composition, which is the hallmark of functoriality. A categorical viewpoint sharpens both the specification and the implementation of AD: it enforces modularity by decomposing programs along categorical structure, clarifies semantics by presenting AD as a structure-preserving functor, and supports efficiency by enabling principled reuse and optimisation. Accordingly, if differentiation is to function as a reliable program transformation, it should arise as a functor that preserves relevant categorical structure.
From now on, we work in the setting of differentiable manifolds and maps between them, the standard framework for studying differentiation in classical mathematics. For readers unfamiliar with manifolds, it is enough to think of Euclidean spaces and their open subsets, as typically encountered in an introductory or intermediate course in calculus. Since manifolds are seldom implemented directly in practice, these simpler settings are often sufficient for reasoning about modern differentiable programming. Nevertheless, manifolds also admit useful presentations by idempotents. Every finite-dimensional smooth manifold without boundary, assumed Hausdorff and second countable, can be embedded in a Euclidean space and realised as a smooth retract of an open neighbourhood. Such a presentation consists of an open set U and a smooth idempotent . Maps between the images of two such idempotents are represented by smooth maps
We write Man for the category of finite-dimensional smooth manifolds and smooth maps, using the convention that each manifold has a fixed dimension. Accordingly, when using idempotent presentations we restrict to those whose images have a fixed dimension.
Assuming that Man models the phenomena of interest, a program transformation should be a structure-preserving functor that assigns to each differentiable map its (co-)derivative. Since AD relies on the chain rule, it ought to behave functorially. More precisely, at its most basic, the co-derivative defines a functor
1. Introduction
where 1 denotes the one-point manifold and 1 ↓ Man is the coslice category of pointed manifolds and point-preserving smooth maps; see standard references on comma categories such as [29, Ch. II.6] or [5, Sec. 2.3]. Dually, the derivative is also a functor .
In practice, Euclidean spaces are implemented without base points. This motivates reframing differentiation as a functor
The central question then becomes: what is the appropriate target category C? Two main paradigms, relying on distinct answers to this question, have been developed within the categorical semantics of AD: the dual numbers approach and CHAD; see Chapters 2 and 3, respectively.
As explained later, dual numbers offer a principled approach to forward-mode AD. They also admit reverse-mode formulations, studied in Chapter 2. CHAD makes a different choice of target structure, representing the primal value and its associated cotangent space separately; this makes the dependence of cotangents on primal values explicit.
In CHAD, the cotangent spaces over all points of a manifold are collected into a family. The functor (1.1) thereby induces
where is the free coproduct completion of (see [4]). Concretely, maps a manifold to the pair , where denotes the underlying set of (by slight abuse of language), and , with the indexing set viewed as a discrete category, assigns to each the cotangent space at . A morphism in Man is mapped to the pair , where is the underlying function and is the family of linear maps
representing the respective co-derivatives. Since models the category of containers for suitable dependently typed languages with linear types (see Chapters 3 and 4; cf. containers [3]), this viewpoint underlies the CHAD construction introduced in [40]. Chapters 3 and 4 develop this functional account, while Chapter 2 treats dual numbers.
1.3.1 Structure-preserving functionality
Program transformations that are structure-preserving admit systematic methods of reasoning. They align with the universal properties that characterise the syntactic and semantic structures of programming languages (modulo -equivalence) and support proof techniques such as logical relations. These methods organise the correctness proof around the structure of the language and the behaviour of its primitives.
Returning to the functor (1.2), it is not enough for differentiation to be merely functional. Both practical and theoretical considerations point to a stronger requirement: the functor must also be structure-preserving, acting as a morphism of the categorical structure we care about. This requirement is not incidental but reflects a general methodological principle that extends beyond differentiation to program transformations more broadly.
Differentiation is an especially suitable test case for this principle, since it is already essentially structure-preserving. The task, then, is to make this precise by establishing a functional differentiation that preserves the relevant categorical structure. Concretely, we show:
Theorem 1.3.1. The functor chaℤ : Man → Fam(Vect^{op}) preserves finite products.
Proof. The cotangent space of a product has the canonical decomposition
The direct sum is a coproduct in Vect, hence a product in Vect . Together with the product of the indexing sets, this is precisely the product of families. The cotangent maps of the manifold projections are the corresponding direct-sum injections, and the cotangent space of the one-point manifold is zero, giving the terminal family.
1.3.2 Forward CHAD and dual numbers
The relation between forward CHAD and dual-numbers AD is especially transparent at first-order types. Let Vect denote the category of real vector spaces and linear maps, let be the underlying-set functor, and consider the total-elements functor
Here takes the disjoint union of a family. Thus retains both the primal value and a tangent vector; it is not the projection . On a family morphism it acts by
The products of families have fibres , while coproducts concatenate families. Consequently, preserves finite products and coproducts, including their nullary cases: the terminal family is and its total set is a singleton.
For the simply typed total source language with products, variants, and function types, the forward CHAD interpretation gives a composite
On a ground type , forward CHAD assigns the constant tangent family . For a smooth primitive , the composite therefore gives
This is precisely the forward dual-numbers interpretation. Since both interpretations preserve finite products and coproducts and agree on the generators, they agree, up to the canonical comparison isomorphisms, on the first-order fragment generated by these operations:
1. Introduction
At real inputs and outputs, the correctness theorems also identify their results for programs that use higher-order constructs internally: both compute the same primal result and directional derivative.
The distinction arises at function types. Although Fam(Vect) is cartesian closed, Q does not preserve exponentials. A small example makes the obstruction explicit. Put . The exponential has one shape for each linear map , and a copy of over each shape. Hence the canonical comparison
identifies a pair with the affine function ; it does not include, for example, . The same obstruction occurs on the actual ground-type interpretation : the comparison for contains only functions of the form , and therefore misses . Thus the composite preserves the first-order product-and-variant structure but is not a cartesian closed interpretation into Set. Forward CHAD and dual numbers share their first-order derivative behaviour while organising higher-order values differently.
1.4 Expressiveness
Automatic differentiation raises several technical challenges, including the if-problem [16, 30]. At a deeper level, however, the central difficulties stem from questions of expressiveness. To support realistic programming languages, differentiation must extend beyond its classical setting so that it applies coherently to richer type systems and effects, remains consistent with the chain rule, and agrees with the classical notion on data types. Categorical semantics provides a natural framework in which to address these requirements.
The gap becomes apparent when classical differentiation is contrasted with the requirements of modern programming languages. Classical differentiation is formulated within concrete mathematical categories that lack cartesian closure and do not accommodate non-termination. Functional languages, by contrast, support currying (cartesian closedness), general recursion and iteration (and therefore non-termination), as well as complex types such as recursive types.
Consider, for example, the classical category of manifolds and differentiable maps, Man. This category already fails to capture basic programming constructs. It does not support variant types: if one attempts to define
for , the intended disjoint union is not an object of Man under our fixed-dimension convention. Categorically, one would like to satisfy
but such coproducts do not exist in Man: the two summands would have to be open submanifolds of K, contrary to the fixed-dimension convention. Even these simple variant types therefore require a broader setting.
A natural extension is to allow formal families of manifolds, whose components may have different dimensions, by taking the free coproduct completion
If C has small coproducts, the universal property of the free coproduct completion extends the (co-)differentiation functor (1.2) uniquely up to canonical isomorphism to a coproduct-preserving functor. If the original functor preserves finite products and finite products in C distribute over small coproducts, this extension is bicartesian:
which we continue to denote by D. In the case of CHAD, this amounts to
which is a bicartesian functor. This extension better aligns categorical semantics with programming constructs.
Nonetheless, VMan still falls short of the expressiveness required by realistic programming languages. For instance, it lacks a general account of partiality and unbounded iteration, as well as function types and general coinductive types. We briefly illustrate these shortcomings in the subsequent discussion.
Higher-order functions. In functional programming, functions are first-class values: they can be passed as arguments, returned as results, and composed into new functions. For instance,
takes a function and produces a new one. Categorically, this requires exponential objects, representing maps from to by an object of the category. Such higher-order structure is central to programming languages but absent from both Man and VMan by Lemma 1.4.1.
Lemma 1.4.1. Neither the category Man nor the category VMan is cartesian closed.
Proof. Suppose that exists in either category, interpreting as a singleton family in VMan. Let represent the zero function. For every , polynomial interpolation gives a smooth map
Its transpose is a section of the evaluation map at . Moreover, for every . In VMan, a morphism from a singleton family selects one component of its codomain, so every selects the component containing . Differentiating at zero therefore shows that is a retract of the same finite-dimensional tangent space . This space would have dimension at least for every , a contradiction.
1. Introduction
Iteration. Real programs also rely on (general) recursion or iteration. Intuitively, iteration repeatedly applies a step until termination. Formally, given
where f either produces an output in B or returns a new state in A, the iteration operator yields a partial function
defined by
where , and the result is undefined otherwise. This formalises looping until a result is returned or divergence occurs (see Chapters 2 and 4).
For example, the factorial function can be expressed via iteration. We take , with the natural number stored as a discrete counter, and let . The state records the remaining counter and the accumulated product. These are objects of VMan by representing as a countable family of copies of . We define
where are coproduct injections. Then is defined by
General recursion. General recursion can be expressed by a fixpoint operator
Intuitively, denotes an element of that is a fixed point of . Such an operator is not definable in , since function types are absent, nor in the simply typed -calculus, which requires additional structure. A standard semantics uses a domain-theoretic setting with least fixed points, thereby accounting for non-termination. A familiar example is the factorial function:
which unfolds through recursive calls until the base case is reached. The availability of fix allows such definitions to be expressed uniformly as , where maps a candidate to the function
Recursive types. Programming languages also depend on types defined recursively. The most basic examples are inductive types, such as natural numbers, lists, and trees, which arise as initial algebras of polynomial functors. For instance, lists over a set A are described by the type equation
where 1 represents the empty list and represents cons-cells. Dually, coinductive types such as streams are defined as final coalgebras, for example
capturing potentially infinite sequences.
In realistic programming, recursion in functions and recursive types often appear together, giving rise to rich structures essential for practical computation. Categorically, this requires objects K defined as solutions to recursive domain equations, so that morphisms can themselves be specified recursively. Such objects often do not exist in VMan, which therefore lacks the expressive power needed to model these fundamental constructions.
Conclusion. From a programming perspective, VMan lacks several standard constructs and thus cannot serve as a faithful model of real languages. To capture these features adequately, one must move beyond such concrete categories.
1.5 Freely generated categorical structures
One possible approach is to embed Man into a more expressive category by a completion or another free construction. Such models can be useful, but our immediate objective is a program transformation on an expressive language. Its correctness should recover classical differentiation at the types where that comparison is available, including for programs that use richer constructs internally. This calls for a treatment of syntax and its interpretations, rather than a commitment to a single concrete extension of VMan.
We therefore work at the level of programming languages modulo , viewing a language as a freely generated categorical structure on its primitive types and operations. The universal property specifies the AD macro, while suitable semantic models and logical relations establish its agreement with differentiation.
This stance keeps us focused on the real task: devising transformations from universal properties and proving correctness by structural methods (e.g. logical relations), rather than through case analyses tied to a particular category.
Example: simply typed -calculus. Given a set of primitive types and a set of primitive operations (e.g. ), we obtain a typed operation signature
in Set, where is the set of finite lists of primitive types, recording the ordered input types of an operation. More general operation signatures allow arbitrary type expressions. The free cartesian closed category on the signature presents the simply typed -calculus via the Curry–Howard–Lambek correspondence: tuples and function types arise as products and exponentials.
Grounded in two-dimensional universal algebra, the same construction extends to richer languages. Reasoning about programs modulo becomes reasoning in their freely generated structure. Two features are essential: (i) the structure reflects the language’s expressive power through familiar categorical semantics, and (ii) the universal property ensures that structure-preserving functors, the semantics of homomorphic program transformations, are uniquely determined by their action on primitives.
1. Introduction
Working hypothesis. Freely generated structures provide a principled bridge between abstract (categorical) semantics and implementation concerns. This thesis substantiates that claim: treating programming languages modulo as free categorical structures produces principled, practically relevant, and verifiable program transformations while enriching categorical semantics.
AD via freeness. In particular, modelling AD as a homomorphic transformation on the programming language modulo yields principled, modular, and correct AD. Correctness follows from universal properties and categorical logical relations, and optimisation opportunities emerge more clearly. In this way, AD serves as a sustained test of the methodology, aligning categorical semantics with real computational demands.
Finally, instead of enlarging concrete models piecemeal, we formulate differentiation within the appropriate free structures. This ensures compatibility with standard models whenever applicable, while supporting the expressiveness required by modern programming languages.
1.6 AD from universal properties
The guiding principle of this thesis is that differentiation should be structure-preserving. This perspective is consistent with classical mathematics, where tangent bundles and dual numbers exhibit functional behaviour, and extends naturally to expressive programming languages when syntax is treated as free categorical structure.
Formally, let a language be modelled by a categorical structure (e.g. a cartesian closed, indexed, or Freyd category). The programming language modulo is then the freely generated -structure on a set of primitives/signatures. Any uniform transformation that respects this structure corresponds to a structure-preserving functor/morphism, uniquely determined by its action on primitives. Instead of specifying AD via ad hoc syntactic rules, we characterise it as the unique homomorphic extension induced by suitable semantic data.
This framework encompasses both forward- and reverse-mode AD. For forward mode, we recover dual numbers by defining a structure-preserving functor from the syntactic category of a simply typed higher-order source language to that of an extended target language, sending each primitive operation to code for its value and derivative action. The functor extends homomorphically to all programs, and correctness is established via a categorical logical-relations argument that accommodates recursive types and partial primitives.
CHAD provides a second approach to both forward- and reverse-mode AD. We develop CHAD (Combinatory Homomorphic AD) for a higher-order total language with rich data types (products, sums, inductive and coinductive types). The semantics is expressed via indexed categories and their Grothendieck constructions, which accumulate derivative information through data projections. To handle sums systematically we introduce extensive indexed categories, a fibred analogue of extensive categories. The reverse transformation is then given by a homomorphic functor into a Grothendieck construction, with correctness following from universal properties and refined logical relations.
We further extend the approach to first-order languages with partial operations and general while-loops, yielding Iterative CHAD. Here, iteration-extensive indexed categories relate substitution along a loop to parameterised initial algebras of substitution along its body. Their folds supply iteration in the category of containers; iterative folders isolate the operations required by the target syntax. The transformation remains structure-preserving, and its correctness is proved compositionally.
The methodological connection. Throughout, language features determine the categorical structure to be preserved. Universal properties specify the transformations, and semantic comparisons establish their correctness.
1.7 Free extensivity and distributivity
Throughout this research we have emphasised that freely generated categorical structures are central to categorical semantics: a programming language modulo can be seen as a freely generated categorical structure. Concrete models then appear as non-free algebras, with syntax represented by the free counterpart. This perspective has long been fruitful in program semantics, and it has proven especially powerful in the development of AD.
Pursuing AD from this vantage point raised questions that extend beyond the applied setting into foundational aspects of category theory. In formulating AD as a homomorphic transformation, we encountered structural requirements on free completions under products and coproducts. Within two-dimensional universal algebra, this prompted a systematic study of the free completions under small products and small coproducts (Chapter 5), followed by analogous constructions for classes of limits (Chapter 6). A canonical pseudodistributive law between the product and coproduct completions yields a pseudomonad whose pseudoalgebras are the doubly-infinitary distributive categories.
Concretely, a category C with small products and small coproducts is doubly-infinitary distributive when the canonical functor
preserves small products, where Fam (C) denotes the free coproduct completion of C. This condition is strictly stronger than ordinary infinitary distributivity. For instance, Top is infinitary distributive but not doubly-infinitary. Moreover, although coproducts together with cartesian closedness imply infinitary distributivity, this implication fails at the doubly-infinitary level: the category of pseudotopological spaces PsTop is complete, cocomplete, and cartesian closed (indeed a quasitopos), yet the inclusion Top → PsTop preserves both coproducts and products, showing that PsTop is not doubly-infinitary distributive. Chapter 5 develops these comparisons in detail.
Our main focus, however, lies on the freely generated structures themselves. We prove that free doubly-infinitary distributive categories are cartesian closed: an unexpected result in which function types arise purely from freeness, becoming an admissible property (alongside, for instance, extensivity). Although initially motivated by the applied challenge of differentiable programming and optimisation issues in CHAD, this theorem is of independent interest: it clarifies the interplay between distributivity and two-dimensional monad theory, underpins later developments on free extensive categories (Chapter 6), and points toward new connections between freely generated structures, function spaces, and categorical accounts of defunctionalisation (left to future work).
Thus, a concrete problem in automatic differentiation gave rise to new results in pure category theory, which in turn enrich the research program on homomorphic program
1. Introduction
transformations. The broader lesson is that categorical investigations inspired by AD are not confined to differentiation alone but illuminate the semantics of programming languages and can be directly applied to a wide range of principled, structure-preserving transformations.
1.8 Grothendieck constructions
A second strand of foundational contributions concerns lifting structure through Grothendieck constructions. The guiding question is how much of the structure of a base category can be transported along a fibration to its total category. Within CHAD this issue became central when analysing the behaviour of exponentials, both cartesian and monoidal, as well as coproducts, initial algebras, terminal coalgebras, and even iteration, of the Grothendieck constructions of indexed categories. A significant portion of the theory needed for CHAD reduces to clarifying these aspects of fibred category theory, which has to do with completion aspects of the 2-category of indexed categories.
These lifting questions are equally relevant to logical relations methods. The categorical logical relations technique can be viewed as a semantics obtained by transporting the structure of a base model into a category of predicates (see, for instance, [22]). Constructing such relational models depends on principled ways of lifting limits, colimits, initial algebras, monads, and exponentials along functors that are often fibrations.
To treat the closure constructions required here in a common framework, we introduce -(co)tractable monoidal structures. Indexed cotractability, together with suitable -types and base-category hypotheses, yields a Dialectica-inspired construction of internal homs in the Grothendieck construction. This provides a uniform route to total categories supporting function spaces, built from indexed families.
The resulting framework unifies many constructions of monoidal closed and cartesian closed total categories from indexed categories. As in other parts of the thesis, concrete needs from AD and CHAD prompted the questions, and the answers feed back as independent contributions to fibred category theory. Practical concerns about reverse-mode differentiation thus led to a systematic account of when and how structure lifts through Grothendieck constructions, with value beyond the original application.
1.9 Extensivity and related contributions
A recurring theme in this work is extensivity. For many programming languages considered modulo , the associated free categorical structures are extensive, a fact that repeatedly guided our semantic designs.
To capture this behaviour in a fibred setting and to handle coproducts, we introduced extensive indexed categories in [21] (Chapter 3). This notion ensures that coproducts lift through Grothendieck constructions, which in turn allows variant types to be modelled cleanly in dependently typed semantics. The idea is developed further in [26] (Chapter 4), where we formulate an analogous principle for iteration. There we reconcile general while-loops with dependent types by requiring that substitution along an iterated computation be isomorphic to the parameterised initial-algebra carrier functor induced by substitution along its body.
In parallel, the notion of -tractable coproduct structures from Chapter 7 can be read as a generalisation of the decomposition of morphisms supplied by extensivity. It controls the behaviour of morphisms with coproduct codomains and clarifies the interaction between coproducts and exponentials inside Grothendieck constructions.
Taken together, these results present extensivity as a unifying principle that underlies coproducts, iteration, lifting, and monoidal closure in our semantics. The trajectory is characteristic of the thesis as a whole: requirements that arise from CHAD, such as modelling sums and loops in expressive typed settings, lead to general theorems about extensive and fibred categories. Applied questions in differentiable programming thus stimulate advances in categorical foundations, and those advances in turn strengthen the semantic tools available for principled program transformations.
1.10 Contributions and Thesis Outline
The development of structure-preserving differentiation yields new results in categorical semantics that stand on their own. The dissertation interleaves practical transformations with these foundational advances.
The full thesis is structured as follows:
• Chapter 2. Dual-Numbers AD for ML-family Languages. This chapter corresponds to [23]. We study forward- and reverse-mode dual-numbers AD for an ML-family language (simply typed -calculus with recursive types). It gives an account of dual-numbers AD in both modes for a language with general recursive types, together with a unified semantic correctness proof.
We present the dual-numbers transformation as a structure-preserving morphism between the freely generated categorical structures associated with the source and target languages. A streamlined logical-relations argument establishes correctness: differentiating syntax yields the same derivative as the denotational semantics of the program. This provides a template for constructing and verifying program transformations in languages with recursive types. Since Pitts' logical-relations framework for recursive types [9, 34] remains the classical reference in this area, a detailed comparison between our approach and his is left to future work.
The treatment includes iteration, term recursion, and recursive types. The transformation is specified from the syntactic structure, while the concrete semantics interprets recursion by least fixed points.
Finally, we derive correct reverse-mode dual-numbers AD from the same transformation using a suitable vector-space interpretation and input wrappers, again for languages with recursive types. The companion implementation work of Smeding and Vákár studies efficient dual-numbers reverse AD and the preservation of parallelism [37, 39]. These developments complement the semantic correctness results presented here.
• Chapter 3. CHAD for expressive total languages. This chapter corresponds to [21]. It presents the first categorical account of reverse-mode AD for languages that include not only products and higher-order functions but also coproducts, inductive types, and coinductive types. The same framework also covers forward-mode AD. The framework is fully compositional and avoids both explicit mutation and graph tracing. Its central theoretical contribution is the introduction of extensive indexed categories, which capture disjoint sums in a fibred setting. We also introduce related notions that ensure initial algebras and terminal coalgebras lift through the fibration, as well as results on the creation of terminal coalgebras by monadic functors and initial algebras by comonadic functors, for compatible endofunctors.
Within this setting, forward- and reverse-mode AD are formulated as homomorphic transformations, with correctness established via a refined categorical logical-relations proof that exploits monadicity and comonadicity techniques in analysing lifted initial algebras and terminal coalgebras.
The efficient implementation of CHAD developed by Smeding and Vákár [38] complements this semantic account. The relationship between the dependent presentation and a simply typed target is examined further in the recent work discussed in Chapter 8.
• Chapter 4. Unraveling the iterative CHAD. This chapter corresponds to [26].
Iterative CHAD extends CHAD to cover first-order programs with general iteration (while-loops), non-termination, and partial (potentially undefined) operations, while preserving its structure-preserving semantics.
We introduce iteration-extensive indexed categories to model these features in a dependently typed setting. We relate substitution along a loop to parameterised initial algebras of substitution along its body. The resulting folds induce fibred iteration on the op-Grothendieck construction. Iterative folders retain the operations needed by the target syntax, while the enriched models identify the induced iteration with least-fixed-point iteration. Through these categorical constructions and a syntactic categorical model with a universal property, we define a unique homomorphic extension of CHAD in the presence of iteration and non-termination. We then prove a correctness theorem: the differentiated program has the same domain of definition as the original program and computes its reverse-mode derivative wherever it is defined.
Beyond its theoretical contributions, this work advances the general study of dependently typed languages with iteration. It shows new techniques for reconciling iteration and dependent types, with further applications expected in program logics.
• Chapter 5. Free Doubly-Infinitary Distributive Categories. This chapter corresponds to [25].
We construct the pseudomonad Dist, arising from the canonical pseudo-distributive law between the free completion pseudomonads under small products and small coproducts. Its pseudoalgebras are the doubly-infinitary distributive categories, a class of categories in which the canonical functor preserves small products. This property is strictly stronger than ordinary infinitary distributivity and had not been systematically studied in the literature.
Our main result is that the free doubly-infinitary distributive completion of any category C is cartesian closed, and therefore supports function types. This is surprising: while free (infinitary) distributive categories generally fail to be cartesian closed, the stronger distributivity of the doubly-infinitary setting makes cartesian closure an admissible property of the free construction. We also give explicit formulas for exponentials in Dist(C), whose combinatorial flavour resonates with Dialectica-style constructions.
The work originated from attempts to understand programming languages up to -equivalence and led to unexpected foundational insights. It reveals new connections between distributivity, freeness, and the categorical representation of higher-order functions, and points toward a categorical formulation of defunctionalisation [35]. Although motivated by differentiable programming, the result stands independently as a contribution to two-dimensional monad theory and to the study of free categorical structures.
• Chapter 6. Free extensivity via distributivity. This chapter corresponds to [27], and builds directly on [25]. We show that a canonical pseudodistributive law between the free completion under coproducts and under suitable limits gives rise to a pseudomonad whose pseudoalgebras correspond to natural classes of extensive categories.
This result deepens the relationship between distributivity and extensivity by identifying extensivity as a property that emerges from universal constructions. In particular, we prove that free doubly-infinitary lextensive categories are cartesian closed, extending the perspective of Chapter 5 and revealing new structural compatibilities between sum types and function types.
As before, the motivation stems from programming-language semantics: understanding languages modulo and clarifying the role of extensivity as an admissible property led directly to new foundational results in category theory.
• Chapter 7. Grothendieck constructions. This chapter corresponds to [24]. The guiding question is: how much structure of a category can be lifted through a fibration? In particular, we study the preservation of exponentials, both in cartesian and in monoidal contexts.
This investigation originated from our work on CHAD, which required a systematic understanding of how properties such as closure and extensivity are transported through Grothendieck constructions. Building on the classical literature on fibrations, we develop conditions that apply uniformly to the constructions needed here.
We begin by analysing fibred limits, colimits, and monoidal (closed) structures of Grothendieck constructions. In doing so, we extend the notion of extensive indexed category introduced in Chapter 3, giving rise to the concept of left Kan extensivity. This new notion provides a uniform mechanism for computing colimits in Grothendieck constructions and refines the understanding of how coproducts behave under fibred colimit formation.
Building on this, we introduce -(co)tractable monoidal structures. Indexed co-tractability, together with suitable -types and base-category hypotheses, gives sufficient conditions for monoidal closure through a Dialectica-inspired formula. Un-
1. Introduction
der this framework, -tractable coproducts unify and extend cocartesian coclosed structures, biproducts, and extensive coproducts.
Once again, concrete challenges from AD and CHAD led to advances of independent value in pure category theory, expanding the theory of extensive indexed categories through the introduction of left Kan extensivity and a clearer understanding of exponentials in Grothendieck constructions.
• Chapter 8. Conclusion and future work. We reflect on how the dialogue between automatic differentiation and categorical semantics led to the results above, summarise contributions and limitations, and outline directions for program transformations beyond differentiation.
Universal properties provide a common framework for the transformations studied in this thesis, while categorical logical relations and semantic comparisons establish their correctness. The resulting development contributes both to automatic differentiation for expressive languages and to the study of free and fibred categorical structures. It also suggests a broader programme of structure-preserving program transformations, with AD as its central case study.
CHAPTER 8
Conclusion and Future Work
This thesis has examined the interaction between categorical semantics and program transformation through automatic differentiation (AD). The practical requirements of AD led us to account for linear transformations, higher-order functions, recursive types, sums, iteration, and partiality within a compositional framework. Treating programming languages modulo their equations as freely generated categorical structures allowed us to define AD by its action on primitives and to organise correctness proofs through universal properties and categorical logical relations. The same investigation raised questions about free completions and Grothendieck constructions, leading to results of independent categorical interest.
From Foundations to Homomorphic AD
On the programming-language side, the thesis developed a framework for homomorphic (i.e. structure-preserving) program transformations, with AD as its main application. Three case studies illustrate the methodology:
• Dual-numbers AD (forward and reverse, Ch. 2). Dual-numbers AD was established as a structure-preserving morphism between the syntactic models of an ML-family source language and an extended target language, both with recursive types. We established correctness by a reusable categorical logical-relations argument accommodating recursive types, partial primitives and differentiability/local properties [23].
• Forward- and reverse-mode AD: CHAD (Ch. 3). We extended Combinatory Homomorphic AD (CHAD) to expressive total languages with tuples, variant types, inductive and coinductive types, and higher-order functions. The dependent target semantics led us to introduce extensive indexed categories to model sums in the Grothendieck construction. Correctness followed from universal properties and categorical logical-relations proofs encompassing initial algebras and terminal coalgebras, using the monadicity and comonadicity results developed in the chapter [21].
• Iteration and partiality: Iterative CHAD (Ch. 4). Extending the first-order fragment of CHAD to general iteration and non-termination led to iteration-extensive indexed categories. These relate substitution along a loop to parameterised initial algebras of substitution along its body. Their folds yield fibred iteration on the op-Grothendieck construction, and iterative folders express the corresponding operations in the target language. This distinction between semantic universal properties and syntactic operations supports a homomorphic extension of CHAD with a proof of domain preservation and derivative correctness [26].
From AD to Foundations
Each extension of AD demanded new categorical machinery, leading to stand-alone foundational results:
• Extensivity and distributivity (Ch. 5 and Ch. 6). By studying a pseudodistributive law between the free completions under products and coproducts, we arrived at the notion of a doubly-infinitary distributive category. We proved that the free such categories are cartesian closed.
Building on this, by analysing pseudodistributive laws between the free completions under limits and under coproducts, we obtained notions of free lextensive completions. The free doubly-infinitary lextensive completions are cartesian closed; in the free infinitary lextensive case, objects with finitely many connected components are exponentiable.
• Grothendieck constructions (Ch. 3, Ch. 4, and Ch. 7). In Chapters 3 and 4, we introduced several notions of extensive indexed categories, providing a clear understanding of coproducts, iteration, and even parameterised initial algebras (and terminal coalgebras) within their respective Grothendieck constructions.
In Chapter 7, we studied limits, colimits, and monoidal closure. Indexed -cotractability, together with suitable -types and base-category hypotheses, gives sufficient conditions for monoidal closure of the total category. We also developed left Kan extensivity to describe the lifting of colimits to Grothendieck constructions.
These results were inspired by the challenges encountered while devising principled AD macros. They also contribute independently to the understanding of extensive categories, fibred category theory, and two-dimensional universal algebra.
Limitations
Alongside providing a solution to the problem of reverse-mode AD for the expressive programming languages studied here, this work has demonstrated that categorical semantics can be employed to design practically relevant program transformations. Our emphasis on correctness and clear semantics was not merely a matter of theoretical elegance: it showed that abstract categorical reasoning can yield concrete AD macros whose derivative correctness is established by semantic proofs. At the same time, this foundation lays the groundwork for systematic reasoning about implementation concerns, such as optimisation and efficiency, by providing a clean and principled semantic framework.
Building on existing work on efficient implementations, the natural next frontiers lie in addressing concrete implementation issues. These include remaining efficiency challenges, the role of defunctionalisation, and the question of how CHAD might further exploit parallelism. While such matters belong partly to the practical engineering of AD systems, categorical structures can provide a sharper and more principled perspective. In particular, there are opportunities to study operational aspects (e.g. rewriting systems), to analyse defunctionalisation through its categorical semantics, and to explore structured approaches to parallelism in CHAD.
Ultimately, the open question is how far this methodology can be taken. This thesis has shown that categorical semantics, when held accountable to practice, is not only explanatory but generative: it can deliver transformations that are provably correct and practically relevant. The challenge now is to push this dialogue further: to see whether the same categorical reasoning that has secured correctness can also chart a systematic roadmap to efficiency, optimisation, and implementation. In this way, theory and practice may continue to advance together, each strengthening and extending the other.
Recent Developments
Work completed since the original submission has already advanced two directions suggested by this thesis: extending CHAD to more expressive languages, and understanding more precisely the relationship between its semantic account and its implementation. The two papers discussed below are subsequent work and are not included among the contributions of this thesis.
In the first direction, our joint work with Diogo Simm and Matthijs Vákár, Backpropagation for Effectful Languages I: Finite Probability and Discrete Output Algebraic Effects [36], extends the CHAD approach to finite-support probabilistic computations with differentiable weights. Reverse propagation must account for the weights as well as the deterministic computations. The construction treats monadic operations and handlers compositionally and proves correctness for handled programs with real-valued outputs. This provides a concrete step towards richer probabilistic languages and other algebraic effects; continuous probability and more general combinations of effects still require further work.
In the second direction, joint work with Diogo Simm and Matthijs Vákár [28] gives a simply typed presentation of dependent CHAD for products, variants and higher-order functions. For variants, primal-indexed idempotents represent the dependent cotangent fibres inside ordinary types. Hoofman and Moerdijk's account of semifunctors and Cauchy completion [13] explains why the ambient transformation preserves composition but sends identities to idempotents, while its interpretation in the completion is an ordinary functor. This relates implementable program representations more directly to the semantic principles developed in this thesis, reinforcing the prospect of advancing theory and practice together.
Future Work
The contributions of this thesis point naturally towards two complementary strands of further research: (A) advancing program transformations and differentiable programming, and (B) developing a categorical toolkit for programming language semantics and program transformations more broadly.
(A) Program transformations and differentiable programming.
• Extending CHAD. Extend the CHAD account to ML-family languages, developing the treatment of recursion and recursive types in an indexed target or an appropriate simply typed presentation.
• Higher-order differentiation. Extend the homomorphic approach to higher-order reverse-mode differentiation, moving beyond first derivatives to capture higher-order derivatives in a principled way.
• Simply typed CHAD. Extend the idempotent-completion account of variants discussed above to richer language fragments, and study how its semantic comparison supports optimisations such as defunctionalisation, closure conversion, and sharing.
• AD with effects. Build on the finite-probability and discrete-output account described above, extending CHAD to richer probabilistic languages and combinations of algebraic effects and handlers while retaining compositional semantics and correctness proofs.
(B) A categorical toolkit for PL semantics and program transformations.
• Presentations via 2-dimensional universal algebra. Systematise the theory of presentations of categorical structures for programming-language semantics, with particular attention to coherence and to comparisons between alternative categorical models of the same constructs.
• Beyond AD. The thesis suggests an underlying principle for transformations whose auxiliary information depends on the program value. Ongoing work investigates how such value-indexed semantic data can give rise to uniform, structure-preserving transformations beyond differentiation. Their further applications and implementation remain a direction for future research.
Closing
This thesis has shown how categorical semantics can yield practical methods for constructing correct program transformations. We derived compositional AD transformations for expressive languages, and the CHAD account developed here formed part of the foundation for Smeding and Vákár's efficient implementation [38]. Conversely, the requirements of AD led to independent mathematical results on free completions, extensivity and Grothendieck constructions.
Subsequent work on simply typed CHAD further clarifies the relation between these semantic foundations and their implementation. These developments support a promising programme of research in which categorical models, correctness proofs and efficient implementations are developed together. The thesis thus substantiates the principle with which it began: sound semantic foundations can guide the principled construction of reliable and practically useful program transformations, with explicit correctness guarantees, while the demands of computation can lead to new mathematics.
Bibliography
[1] Martin Abadi and Gordon D. Plotkin. A Simple Differentiable Programming Language. Proceedings of the ACM on Programming Languages, 4(POPL):38:1–38:28, January 2020. doi:10.1145/3371106. URL https://doi.org/10.1145/3371106.
[2] Martin Abadi, Ashish Agarwal, Paul Barham, Eugene Brevdo, Zhifeng Chen, Craig Citro, Greg S. Corrado, Andy Davis, Jeffrey Dean, Matthieu Devin, Sanjay Ghemawat, Ian Goodfellow, Andrew Harp, Geoffrey Irving, Michael Isard, Yangqing Jia, Rafal Jozefowicz, Lukasz Kaiser, Manjunath Kudlur, Josh Levenberg, Dandelion Mané, Rajat Monga, Sherry Moore, Derek Murray, Chris Olah, Mike Schuster, Jonathon Shlens, Benoit Steiner, Ilya Sutskever, Kunal Talwar, Paul Tucker, Vincent Vanhoucke, Vijay Vasudevan, Fernanda Viégas, Oriol Vinyals, Pete Warden, Martin Wattenberg, Martin Wicke, Yuan Yu, and Xiaoqiang Zheng. TensorFlow: Large-Scale Machine Learning on Heterogeneous Systems, 2015. URL https://www.tensorflow.org/. Software.
[3] Michael Abbott, Thorsten Altenkirch, and Neil Ghani. Categories of Containers. In FoSSaCS 2003, volume 2620 of Lecture Notes in Computer Science, pages 23–38. Springer, 2003. doi:10.1007/3-540-36576-1_2. URL https://people.cs.nott.ac.uk/psztxa/publ/fossacs03.pdf.
[4] Jiří Adámek and Jiří Rosický. How nice are free completions of categories? Topology and its Applications, 273:106972, 2020. doi: 10.1016/j.topol.2019.106972. URL https://www.sciencedirect.com/science/article/pii/S0166864119303773.
[5] Jiří Adámek, Horst Herrlich, and George E. Strecker. Abstract and Concrete Categories: The Joy of Cats. Theory and Applications of Categories, 2006. URL https://www.tac.mta.ca/tac/reprints/articles/17/tr17.pdf. Reprint, available online.
[6] Atilim Gunes Baydin, Barak A. Pearlmutter, Alexey Andreyevich Radul, and Jeffrey Mark Siskind. Automatic Differentiation in Machine Learning: A Survey. Journal of Machine Learning Research, 18(153):1–43, 2018. URL http://jmlr.org/papers/v18/17-468.html.
[7] James Bradbury, Roy Frostig, Peter Hawkins, Matthew James Johnson, Yash Katariya, Chris Leary, Dougal Maclaurin, George Necula, Adam Paszke, Jake VanderPlas, Skye Wanderman-Milne, and Qiao Zhang. JAX: composable transformations of Python+NumPy programs, 2018. URL https://github.com/jax-ml/jax. Software.
[8] Roy L. Crole. Categories for Types. Cambridge Mathematical Textbooks. Cambridge University Press, 1993. doi: 10.1017/CBO9781139172707. URL http://www.cambridge.org/de/academic/subjects/computer-science/programming-languages-and-applied-logic/categories-types?format=PB.
[9] Arthur Azevedo de Amorim. On Pitts' Relational Properties of Domains. arXiv:2207.07053, 2022. URL https://arxiv.org/abs/2207.07053.
[10] Conal Elliott. The simple essence of automatic differentiation. Proc. ACM Program. Lang., 2 (ICFP):70:1–70:29, jul 2018. doi: 10.1145/3236765. URL https://doi.org/10.1145/3236765.
[11] Marcelo P. Fiore and Gordon D. Plotkin. An extension of models of Axiomatic Domain Theory to models of Synthetic Domain Theory. In Dirk van Dalen and Marc Bezem, editors, Computer Science Logic, volume 1258 of Lecture Notes in Computer Science, pages 129–149, Berlin, Heidelberg, 1997. Springer Berlin Heidelberg. doi: 10.1007/3-540-63172-0_36.
Bibliography
[12] Andreas Griewank and Andrea Walther. Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation. Society for Industrial and Applied Mathematics, second edition, 2008. doi: 10.1137/1.9780898717761. URL https://epubs.siam.org/doi/abs/10.1137/1.9780898717761.
[13] Raymond Hoofman and Ieke Moerdijk. A remark on the theory of semi-functors. Mathematical Structures in Computer Science, 5(1):1–8, 1995. doi: 10.1017/S096012950000061X.
[14] Mathieu Huot, Sam Staton, and Matthijs Vákár. Correctness of Automatic Differentiation via Diffeologies and Categorical Gluing. In Jean Goubault-Larrecq and Barbara König, editors, Foundations of Software Science and Computation Structures, pages 319–338, Cham, 2020. Springer International Publishing. doi: 10.1007/978-3-030-45231-5_17.
[15] Bart Jacobs. Categorical Logic and Type Theory, volume 141 of Studies in Logic and the Foundations of Mathematics. Elsevier, 1999.
[16] Johann Joss. Algorithmisches Differenzieren. PhD thesis, ETH Zürich, 1976. URL https://www.research-collection.ethz.ch/handle/20.500.11850/134597. Diss. Math. ETH Zürich, Nr. 5757.
[17] Donald E. Knuth. Theory and practice. Theoretical Computer Science, 90:1–15, 1991. URL https://arxiv.org/abs/cs/9301114.
[18] Joachim Lambek and Philip J. Scott. Introduction to Higher Order Categorical Logic, volume 7 of Cambridge Studies in Advanced Mathematics. Cambridge University Press, 1986.
[19] Paul Blain Levy. Call-by-Push-Value: A Subsuming Paradigm. In Typed Lambda Calculi and Applications, volume 1581 of Lecture Notes in Computer Science, pages 228–243. Springer, 1999. doi: 10.1007/3-540-48959-2_17.
[20] Paul Blain Levy. Call-by-push-value: Decomposing call-by-value and call-by-name. Higher-Order and Symbolic Computation, 19(4):377–414, 2006. doi: 10.1007/s10990-006-0480-6. URL https://doi.org/10.1007/s10990-006-0480-6.
[21] F. Lucatelli Nunes and Matthijs Vákár. CHAD for expressive total languages. Mathematical Structures in Computer Science, 33(4–5):311–426, 2023. doi: 10.1017/S096012952300018X.
[22] F. Lucatelli Nunes and Matthijs Vákár. Logical Relations for Partial Features and Automatic Differentiation Correctness. Technical Report 2023–09, Mathematisches Forschungsinstitut Oberwolfach, 2023. URL https://publications.mfo.de/bitstream/handle/mfo/4046/0W P-2023-09.pdf.
[23] F. Lucatelli Nunes and Matthijs Vákár. Automatic differentiation for ML-family languages: Correctness via logical relations. Mathematical Structures in Computer Science, 34(8):747–806, 2024. doi: 10.1017/S0960129524000215.
[24] F. Lucatelli Nunes and Matthijs Vákár. Monoidal closure of Grothendieck constructions via -tractable monoidal structures and Dialectica formulas. Theory and Applications of Categories, 44(35):1153–1217, 2025. URL https://www.tac.mta.ca/tac/volumes/44/35/44-35abs.html.
[25] F. Lucatelli Nunes and Matthijs Vákár. Free Doubly-Infinitary Distributive Categories are Cartesian Closed. Applied Categorical Structures, 34(5):53, 2026. doi: 10.1007/s10485-026-09887-7. URL https://arxiv.org/abs/2403.10447.
[26] F. Lucatelli Nunes, Gordon Plotkin, and Matthijs Vákár. Unraveling the iterative CHAD. arXiv:2505.15002, 2025. URL https://arxiv.org/abs/2505.15002v3. Version 3, revised 13 September 2026.
[27] F. Lucatelli Nunes, Rui Prezado, and Matthijs Vákár. Free extensivity via distributivity. Portugaliae Mathematica, 82(1–2):177–204, 2025. doi: 10.4171/PM/2129.
[28] F. Lucatelli Nunes, Diogo Simm, and Matthijs Vákár. Simply Typed Reverse-Mode Auto-
Bibliography
matic Differentiation with Variants: Denotational Correctness via Idempotent Completion. arXiv:2607.14453, 2026. URL https://arxiv.org/abs/2607.14453v3.
[29] Saunders Mac Lane. Categories for the Working Mathematician, volume 5 of Graduate Texts in Mathematics. Springer, 2 edition, 1998. doi: 10.1007/978-1-4757-4721-8.
[30] Damiano Mazza and Michele Pagani. Automatic differentiation in PCF. Proc. ACM Program. Lang., 5(POPL):1–27, 2021. doi: 10.1145/3434309. URL https://doi.org/10.1145/3434309.
[31] E. Moggi. Computational lambda-calculus and monads. In [1989] Proceedings. Fourth Annual Symposium on Logic in Computer Science, pages 14–23, 1989. doi: 10.1109/LICS.1989.39155. URL https://doi.org/10.1109/LICS.1989.39155.
[32] Eugenio Moggi. Notions of computation and monads. Information and Computation, 93(1): 55–92, 1991. doi: 10.1016/0890-5401(91)90052-4. URL https://www.sciencedirect.com/science/article/pii/0890540191900524. Selections from 1989 IEEE Symposium on Logic in Computer Science.
[33] Adam Paszke, Sam Gross, Francisco Massa, Adam Lerer, James Bradbury, Gregory Chanan, Trevor Killeen, Zeming Lin, Natalia Gimelshein, Luca Antiga, et al. PyTorch: An Imperative Style, High-Performance Deep Learning Library. In Advances in Neural Information Processing Systems 32 (NeurIPS 2019), 2019. URL https://papers.nips.cc/paper/9015-pytorch-a-n-imperative-style-high-performance-deep-learning-library.pdf.
[34] Andrew M. Pitts. Relational Properties of Domains. Information and Computation, 127(2): 66–90, jun 1996. doi: 10.1006/inco.1996.0052. URL https://www.cl.cam.ac.uk/~amp12/papers/relpod/relpod.pdf.
[35] John C. Reynolds. Definitional Interpreters for Higher-Order Programming Languages. In Proceedings of the ACM Annual Conference (ACM '72), Volume 2, pages 717–740, 1972. doi:10.1145/800194.805852.
[36] Diogo Simm, F. Lucatelli Nunes, and Matthijs Vákár. Backpropagation for Effectful Languages I: Finite Probability and Discrete Output Algebraic Effects. arXiv:2607.13935, 2026. URL https://arxiv.org/abs/2607.13935.
[37] Tom Smeding and Matthijs Vákár. Efficient Dual-Numbers Reverse AD via Well-Known Program Transformations. Proceedings of the ACM on Programming Languages, 7(POPL): 1573–1600, 2023. doi: 10.1145/3571247. URL https://doi.org/10.1145/3571247.
[38] Tom J. Smeding and Matthijs I. L. Vákár. Efficient CHAD. Proceedings of the ACM on Programming Languages, 8(POPL):1060–1088, 2024. doi: 10.1145/3632878. URL https://doi.org/10.1145/3632878.
[39] Tom J. Smeding and Matthijs I. L. Vákár. Parallel dual-numbers reverse AD. Journal of Functional Programming, 35:e16, 2025. doi: 10.1017/S0956796825100051. URL https://arxiv.org/abs/2207.03418.
[40] Matthijs Vákár. Reverse AD at Higher Types: Pure, Principled and Denotationally Correct. In Nobuko Yoshida, editor, Programming Languages and Systems, pages 607–634, Cham, 2021. Springer International Publishing. doi: 10.1007/978-3-030-72019-3_22. URL https://doi.org/10.1007/978-3-030-72019-3_22.
Samenvatting
De categorietheorie biedt een krachtig fundament voor de semantiek van programmeertalen en maakt het mogelijk om typesystemen, programma’s en programmeequivalenties wiskundig nauwkeurig te modelleren. Klassieke werken zoals J. Lambek en P. Scott’s Introduction to Higher-Order Categorical Logic, R. Crole’s Categories for Types, en B. Jacobs’ Categorical Logic and Type Theory tonen aan hoe categorische structuren een breed scala aan type-theorieën en programmeertalen kunnen modelleren. Voortbouwend op deze fundamenten introduceerde E. Moggi de monaden, waarmee hij een verenigend categorisch kader bood voor het representeren van computationele effecten, zoals toestand, uitzonderingen en niet-determinisme. Sindsdien is de invloed van de categorietheorie alleen maar toegenomen, zowel bij het analyseren van bestaande taalfaciliteiten als bij het inspireren van nieuwe. Zo identificerden M. Fiore en G. Plotkin in hun werk over axiomatische domeintheorie categorische voorwaarden, zoals algebraische compactheid, die voldoende zijn om recursieve domeinvergelijkingen op te lossen en zo een categorische generalisatie van domeinsemantiek te verkrijgen. Evenzo introduceerden G. Plotkin en J. Power met hun theorie van algebraische effecten een modulaire benadering om effecten te behandelen via algebraische theorieën, waarmee zij Moggi’s monadische perspectief verfinden en uitbreidden. Meer recent verenigde P. B. Levy’s Call-by-Push-Value de evaluatiestrategieën call-by-name en call-by-value binnen één calculus, ondersteund door een elegante categorische semantiek gebaseerd op een adjunctiedecompositie van Moggi’s kader. Gezamenlijk tonen deze ontwikkelingen aan dat de categorietheorie een robuust en verenigend fundament blijft bieden voor de semantiek van programmeertalen.
Dit proefschrift: Voortbouwend op deze traditie ontwikkelt dit proefschrift de semantiek van programmeertalen verder door middel van categorische structuren, telkens geleid door een concret en praktisch probleem: structuurbehoudende programmotransformaties voor het berekenen van afgeleiden, een techniek die algemeen bekendstaat als automatische differentiatie (AD). Onze theorie wordt ontwikkeld in nauwe samenhang met implementatievraagstukken, zodat onze categorische constructies realistische programmotransformaties opleveren. Deze transformaties zijn compositioneel; hun correctheid wordt bewezen met categorische logische relaties. Zij bieden tevens een basis voor verdere analyse van hun complexiteit.
Onze centrale benadering beschouwt de syntaxis van een programmeertaal, modulo haar standaard -equationele theorie, als een geschikte vrij gegenererde categorische structuur. Programmotransformaties die de structuur van programma's behouden, corresponderen dan met structuurbehoudende (of homomorfe) functoren die voortkomen uit de universele eigenschappen van deze vrije constructies. Volgens dit principe definiëren we voorwaartse automatische differentiatie in de stijl van duale getallen als een structuurbehoudende functor van de syntactische categorie van een recursieve hogere-ordebrontaal naar die van een uitgebreide doeltaal, waarbij elke primitieve operatie wordt afgebeeld op code voor haar waarde en de werking van haar afgeleide. We bewijzen de correctheid met behulp van een nieuwe techniek van logische relaties voor talen met recursieve types en partiële primitieve operaties.
Vervolgens breiden we dit homomorfe perspectief op AD uit naar de meer uitdagende en veelgebruikte achterwaartse modus van AD, door middel van CHAD (Combinatory Homomorphic AD), die totale hogere-ordeprogrammeertalen behandelt met expressieve constructies: producten, sommen, inductieve en coïductieve types, en functietypes. De semantiek van CHAD wordt ontwikkeld met behulp van de totale categorieën (Grothendieck-constructies) die horen bij geïndexeerde categorieën, en introduceert het begrip extensieve geïndexeerde categorieën om disjuncte sommen te behandelen. De correctheid volgt uit de universele eigenschap en een geschikte categorische techniek van logische relaties.
We breiden CHAD verder uit naar partiële eerste-ordetalen met algemene iteratie. De Iteratieve CHAD integreert iteratie via iteratie-extensieve geïndexeerde categorieën, waardoor we onbegrensde lussen kunnen interpreteren en aantonen dat de transformatie opnieuw uniek structuurbehoudend en correct is.
In de laatste hoofdstukken tonen we aan dat veel van het wiskundige instrumentarium dat ontwikkeld werd om CHAD te begrijpen, zich op natuurlijke wijze uitbreidt tot fundamentele resultaten in de vezelcategorietheorie, waarbij de structuur van Grothendieck-constructies van geïndexeerde categorieën wordt verduidelijkt, evenals in de theorie van distributieve en extensieve categorieën.
Het volledige proefschrift is als volgt opgebouwd:
1. Inleiding
2. Automatic Differentiation for ML-family Languages (arXiv:2210.07724)
Dit hoofdstuk komt overeen met F. Lucatelli Nunes en M. Vákár, “Automatic Differentiation for ML-family languages: correctness via logical relations,” Mathematical Structures in Computer Science 34(8), 747–806 (2024), ook beschikbaar via arXiv:2210.07724. We ontwikkelen voorwaartse en achterwaartse automatische differentiatie (AD) via duale getallen voor ML-familietalen met recursieve types en bewijzen de correctheid met behulp van logische relaties. De AD-macro wordt geformuleerd als een structuurbehoudend morfisme tussen de syntactische modellen van de bronen doeltaal, beide met recursieve types. Voor het correctheidsbewijs introduceren we een gestroomlijnd en herbruikbaar raamwerk van logische relaties voor redeneren over recursieve types en talen met effecten.
3. CHAD for Expressive Total Languages (arXiv:2110.00446)
Dit hoofdstuk komt overeen met F. Lucatelli Nunes en M. Vákár, “CHAD for expressive total languages,” Mathematical Structures in Computer Science 33(4–5), 311–426 (2023), doi:10.1017/S096012952300018X, ook beschikbaar via arXiv:2110.00446. We ontwikkelen CHAD voor totale talen met sommen, producten, inductieve, coïductieve en functietypes. Om dit te bereiken integreren we inductieve en coïductieve types in afhankelijk typesemantiek en verduidelijken hun relatie via het nieuwe begrip extensieve geïndexeerde categorieën. Daarnaast introduceren we krachtige categorische technieken van logische relaties voor redeneren over programmeertalen, gebaseerd op resultaten over monadiciteit en comonadiciteit.
4. Unraveling the Iterative CHAD
(arXiv:2505.15002)
Dit hoofdstuk komt overeen met F. Lucatelli Nunes, G. Plotkin en M. Vákár, “Unraveling the Iterative CHAD,” Preprint, arXiv:2505.15002v3 (2025), herzien op 13 september 2026. We breiden CHAD uit naar eerste-ordetalen met iteratie en niet-terminatie, waarbij we fixpunten integreren via het begrip iteratie-extensieve geïndexeerde categorieën, dat hierin wordt geïntroduceerd. Daartoe ontwikkelen we verschillende nieuwe vormen van extensieve geïndexeerde categorieën en, belangrijker nog, het concept van iteratie-extensieve geïndexeerde categorieën, die de categorische basis bieden voor bepaalde colimieten en iteratie in de overeenkomstige Grothendieck-constructies. De bijbehorende iteratieve folders beschrijven de operaties die nodig zijn om de transformatie in de doeltaal uit te drukken.
5. Free Doubly-Infinitary Distributive Categories
(arXiv:2403.10447)
Dit hoofdstuk komt overeen met F. Lucatelli Nunes en M. Vákár, “Free Doubly-Infinitary Distributive Categories are Cartesian Closed,” Applied Categorical Structures 34, artikel 53 (2026) [25], ook beschikbaar via arXiv:2403.10447. Onder andere introduceren we het concept van dubbel-oneindig distributieve categorieën, dat wil zeggen categorieën waarin willekeurige kleine producten distribueren over willekeurige kleine coproducten, in de precieze zin die in Hoofdstuk 5 wordt ontwikkeld. We bewijzen verder dat vrij dubbel-oneindig distributieve categorieën cartesiaans gesloten zijn.
6. Free Extensivity via Distributivity
(arXiv:2405.02185)
Dit hoofdstuk komt overeen met F. Lucatelli Nunes, R. Prezado, en M. Vákár, “Free Extensivity via Distributivity,” Portugaliae Mathematica 82(1–2), 177–204 (2025), ook beschikbaar via arXiv:2405.02185. We bestuderen de canonieke pseudodistributieve wet tussen de vrije coproduct-voltooiingspseudomonade en verschillende vrije limiet-voltooiingspseudomonaden. Wanneer de klasse van limieten pullbacks omvat, leidt deze interactie tot natuurlijke begrippen van extensieve categorieën. We tonen aan dat extensieve categorieën met pullbacks en oneindig lex-extensieve categorieën verschijnen als pseudoalgebra’s voor de pseudomonaden die door deze pseudodistributieve wetten worden geïnduceerd. We introduceren het begrip dubbel-oneindig lex-extensieve categorieën en bewijzen dat de vrij gegenererde zulke categorieën cartesiaans gesloten zijn. Hieruit leiden we verder af dat in vrij gegenererde oneindig lex-extensieve categorieën de objecten met een eindig aantal verbonden componenten exponentieerbaar zijn.
7. Grothendieck constructions
(arXiv:2405.07724)
Dit hoofdstuk komt overeen met F. Lucatelli Nunes en M. Vákár, “Monoidal Closure of Grothendieck Constructions via -tractable Monoidal Structures and Dialectica Formulas,” Theory and Applications of Categories 44(35), 1153–1217 (2025); zie de bibliografie [24] voor de publicatiegegevens. We bestuderen Grothendieck-constructies van geïndiceerde categorieën en introduceren het begrip left-Kan-extensiviteit, dat de bestaande kennis over extensieve geïndiceerde categorieën verfijnt en uitbreidt en zo het bredere landschap van extensiviteitsbegrippen verrijkt. Dit begrip biedt een systematisch kader voor het analyseren en berekenen van colimieten binnen Grothendieck-constructies. Om monoidale geslotenheid te onderzoeken, introduceren we bovendien het begrip -(co)tractabele monoidale structuren en tonen we aan dat dit kader voldoende voorwaarden oplevert voor het bestaan van gesloten monoidale structuren op Grothendieck-constructies.
- Conclusie en toekomstig werk
Summary
Category theory provides a powerful foundation for programming language semantics, enabling rigorous mathematical modeling of type systems, programs, and program equivalences. Classic works such as J. Lambek and P. Scott's Introduction to Higher-Order Categorical Logic, R. Crole's Categories for Types, and B. Jacobs' Categorical Logic and Type Theory demonstrate how categorical structures can model a wide range of type theories and programming languages. Building on these foundations, E. Moggi's introduction of monads offered a unifying categorical framework for representing computational effects, including state, exceptions, and nondeterminism. Since then, the influence of category theory has only deepened, both in analysing existing programming language features and in inspiring new ones. For example, M. Fiore and G. Plotkin's work on axiomatic domain theory identified categorical conditions, such as algebraic compactness, sufficient to solve recursive domain equations, thereby providing a categorical generalization of domain semantics. Similarly, G. Plotkin and J. Power's theory of algebraic effects introduced a modular approach to handling effects through algebraic theories, refining and extending Moggi's monadic perspective. More recently, P. B. Levy's Call-by-Push-Value unified call-by-name and call-by-value evaluation strategies within a single calculus, supported by an elegant categorical semantics based on an adjunction decomposition of Moggi's framework. Together, these developments demonstrate how category theory continues to provide a robust and unifying foundation for the semantics of programming languages.
This thesis: Building on this tradition, this thesis advances programming language semantics through the lens of categorical structures, guided at every step by a concrete practical problem: structure-preserving program transformations for computing derivatives, a technique commonly known as Automatic Differentiation (AD). Our theory is developed hand-in-hand with implementation challenges, ensuring our categorical constructions yield realistic program transformations. These transformations are compositional, with correctness established by categorical logical-relations proofs, and provide a basis for further analysis of their complexity.
Our central approach is to view the syntax of a programming language, modulo its standard -equational theory, as a suitable freely generated categorical structure. Program transformations that preserve program structure then correspond to structure-preserving (or homomorphic) functors induced by the universal properties of these free constructions. Using this principle, we define forward-mode AD, in the style of dual numbers, as a structure-preserving functor from the syntactic category of a recursive higher-order source language to that of an extended target language, sending each primitive operation to code for its value and derivative action. We prove correctness using a novel logical-relations technique for languages featuring recursive types and partial primitives.
We then extend this homomorphic perspective on AD to the more challenging and popular reverse-mode AD method, using CHAD (Combinatory Homomorphic AD), which handles higher-order total languages with expressive features: products, sums, inductive and coinductive types, and function types. CHAD's semantics is developed using the total categories (Grothendieck constructions) associated with indexed categories, and it introduces the notion of extensive indexed categories to handle disjoint sums. Correctness follows from the universal property and an appropriate categorical logical-relations technique.
We further broaden CHAD to partial first-order languages with general iteration. Iteration-extensive indexed categories relate loop substitution to parameterised initial algebras; iterative folders supply the operations needed by the target language. This allows us to interpret unbounded loops and prove the correctness of the extended transformation.
In the final chapters, we show that much of the mathematical machinery developed to understand CHAD extends naturally to yield foundational results in fibred category theory, clarifying the structure of Grothendieck constructions of indexed categories, as well as in the theory of distributive and extensive categories.
The full thesis is structured as follows:
1. Introduction
2. Automatic Differentiation for ML-family Languages (arXiv:2210.07724)
This chapter corresponds to F. Lucatelli Nunes and M. Vákár, “Automatic Differentiation for ML-family languages: correctness via logical relations,” Mathematical Structures in Computer Science 34(8), 747–806 (2024), also available as arXiv:2210.07724. We develop forward- and reverse-mode automatic differentiation (AD) via dual numbers for ML-family languages featuring recursive types and establish its correctness using logical relations. The AD macro is formulated as a structure-preserving morphism between the syntactic models of the source and target languages, both with recursive types. To prove correctness, we introduce a streamlined and reusable logical-relations framework for reasoning about recursive types and languages with effects.
3. CHAD for Expressive Total Languages (arXiv:2110.00446)
This chapter corresponds to F. Lucatelli Nunes and M. Vákár, “CHAD for expressive total languages,” Mathematical Structures in Computer Science 33(4–5), 311–426 (2023), doi:10.1017/S096012952300018X, also available as arXiv:2110.00446. We develop CHAD for total languages with sums, products, inductive, coinductive, and function types. To achieve this, we integrate inductive and coinductive types into dependent type semantics and clarify their intricate relationship through the novel notion of extensive indexed categories. We further introduce powerful categorical logical-relations techniques for reasoning about programming languages, drawing on results concerning monadicity and comonadicity.
4. Unraveling the Iterative CHAD
(arXiv:2505.15002)
This chapter corresponds to F. Lucatelli Nunes, G. Plotkin and M. Vákár, “Unraveling the Iterative CHAD,” Preprint, arXiv:2505.15002v3 (2025), revised 13 September 2026. We extend CHAD to first-order languages featuring iteration and non-termination, integrating fixpoints through the notion of iteration-extensive indexed categories, introduced therein. To this end, we develop several novel notions of extensive indexed categories and, more significantly, the concept of iteration-extensive indexed categories, which provide the categorical foundations for supporting certain colimits and iteration in the corresponding Grothendieck constructions. The corresponding iterative folders specify the operations needed to express the transformation in the target language.
5. Free Doubly-Infinitary Distributive Categories
(arXiv:2403.10447)
This chapter corresponds to F. Lucatelli Nunes and M. Vákár, “Free Doubly-Infinitary Distributive Categories are Cartesian Closed,” Applied Categorical Structures 34, article 53 (2026) [25], also available as arXiv:2403.10447. Among other contributions, we establish the concept of doubly-infinitary distributive categories, that is, categories in which arbitrary small products distribute over arbitrary small coproducts in the precise sense developed in Chapter 5. We further prove that free doubly-infinitary distributive categories are cartesian closed.
6. Free Extensivity via Distributivity
(arXiv:2405.02185)
This chapter corresponds to F. Lucatelli Nunes, R. Prezado, and M. Vákár, “Free Extensivity via Distributivity,” Portugaliae Mathematica 82(1–2), 177–204 (2025), also available as arXiv:2405.02185. We study the canonical pseudodistributive law between the free coproduct completion pseudomonad and various free limit completion pseudomonads. When the class of limits includes pullbacks, this interaction gives rise to natural notions of extensive categories. In particular, we show that extensive categories with pullbacks and infinitary lextensive categories arise as the pseudoalgebras for the pseudomonads induced by these pseudodistributive laws. We introduce the notion of doubly-infinitary lextensive categories and prove that the freely generated such categories are cartesian closed. From this, we further deduce that, in freely generated infinitary lextensive categories, the objects with finitely many connected components are exponentiable.
7. Grothendieck constructions
(arXiv:2405.07724)
This chapter corresponds to F. Lucatelli Nunes and M. Vákár, “Monoidal Closure of Grothendieck Constructions via -tractable Monoidal Structures and Dialectica Formulas,” published in Theory and Applications of Categories 44(35), 1153–1217 (2025) [24], arXiv:2405.07724 [math.CT]. We study Grothendieck constructions of indexed categories, introducing the notion of left-Kan extensivity, which refines and extends the existing understanding of extensive indexed categories while enriching the broader landscape of extensivity-like notions. This concept provides a systematic framework for analyzing and computing colimits within Grothendieck constructions. Furthermore, to investigate monoidal closedness, we introduce the notion of -(co)tractable monoidal structures and show that this framework yields sufficient conditions for the existence of closed monoidal structures on Grothendieck constructions.