Algebraic Code and Large Language Models by Wuming Pan
1id1.net

Algebraic Code and Large Language Models

Wuming Pan
English edition  /  Author’s Manuscript Edition
1id1.net / ENGLISH EDITION

About this edition

Algebraic Code and Large Language Models

Author
Wuming Pan
Language and edition
English · Author’s Manuscript Edition
Source text
Translated from the Chinese author’s manuscript edition, based on the 1102 submission and the author’s separately submitted foreword and final chapter.
Scope
Eight chapters and the references follow the Chinese print edition. The contents, cross-references, and subject index refer to this English edition.
Chinese print edition
Pan, Wuming. Algebraic Code and Large Language Models [in Chinese]. Sichuan University Press. ISBN 978-7-5690-6590-9.
Chinese print edition and watermarked preview (SCUAI)
Cite this edition
Pan, Wuming. Algebraic Code and Large Language Models. English author’s manuscript edition, v1. 1id1.net, 2026.
Version PID: 1id1:core:20261128-0002@v1
https://1id1.net/id/core/20261128-0002/v1/

Foreword

The recent popularity of OpenClaw and its lobster mascot brought a change into focus for me. An agent can now act across models, tools, files, browsers, messaging channels, and the local operating system. It can generate language, invoke tools and skills, and work with both people and programmatic interfaces. Building agents therefore calls for a multilingual view of programming. Python, TypeScript, C#, Swift, Rust, F#, Kotlin, and Scala each bring their own ecosystems and strengths.

A program needs more than a prompt to connect it to an LLM API. Prompts express intent well, but a system contract must also be maintainable over time. We need intermediate representations that give goals, actions, evidence, state, errors, tool calls, and reasoning traces a structure we can parse, verify, and replay. This is how a model’s command of natural language becomes a reusable software component, with a life beyond a single text response.

I use the term “algebraic code” for this way of seeing structure. Algebraic data types (ADTs) organize the possibilities into explicit sums and products. Algebraic pattern matching (APM) expresses rules as branches that can be checked for exhaustiveness. Functor, Applicative, Monad, and Kleisli composition distinguish transforming a value, aggregating independent tasks, and sequencing dependent computations. Together they support precise, auditable reasoning. Data has a shape, rules have a scope, composition obeys laws, and execution leaves a trace.

I therefore approach programming languages along two axes. Object-oriented programming is well suited to entities, encapsulation, lifecycles, interface boundaries, and open extension. Algebraic code handles closed sets of possibilities, structured data, exhaustive dispatch, laws of composition, and verifiable reasoning. The two complement each other in a modern software system. An understanding of OOP helps us reason about objects, state, and collaboration. An understanding of algebraic code helps us reason about types, variants, patterns, and composition. For developers working across languages in the age of agents, both deserve equal standing as foundations for understanding languages and software systems.

That is the starting point for this book. We use algebraic code to understand programming languages, the token paradigm to connect programs to large language models, and verifiable intermediate representations to build agents.

Category Theory Meets Programming: A Roundtable

Imagine a game in which leading ideas from category theory and programming take seats at a round table. Their names and personalities are teaching devices. The chapters that follow give precise definitions, laws, and engineering interpretations.1

Eilenberg and Mac Lane, the founders of category theory, chair the roundtable. Ten guests take their seats. Each brings a motto, a few people or papers to read, an incarnation in code, and some familiar allies.

1. Functor: “Give me a function. I’ll preserve the structure.”

2. Applicative: “Combine independent work. Call Monad when one step needs another.”

3. Monad: “I’ll take care of sequencing and keep the effects inside.”

4. Natural Transformation: “Even a change of containers has rules.”

5. Traversable: “Turn a structure of effects into an effect containing a structure.”

6. Alternative / Choice: “If the left branch fails, try the right.”

7. Monoidal: “Abstract algebra in one hand, Applicative in the other.”

8. Kleisli: “I compose effectful arrows as readily as functions.”

9. Long-Chain Functions: Composition and Trailing Closures. “Write the control flow into the types.”

10. ADT–APM: Algebraic Data Types and Algebraic Pattern Matching. “Give data a shape and rules a table.”

The Whole Table: A Programmer’s Mnemonic

Bring the ten guests together. Start with structure-preserving maps and natural transformations between containers. Combine independent work that can run in parallel using composition with a unit and associativity. For dependencies, use an effectful sequence and allow a fallback choice where needed. For batches, turn a structure of effects into an effect containing a structure. Connect the main workflow with a pipeline of curried, pure functions, and dispatch decisions through algebraic pattern matching. Record the outputs as Token / Proof / Citations / Trace so they can be read, computed over, verified, and managed. This is how we write control flow into types, carry semantics in containers, and attach evidence to artifacts.


  1. This playful account is meant to build intuition. For historical detail, formal definitions, and arguments, consult the chapters and references.↩︎

Preface

This book begins with the token and follows four lines of work that are often treated separately: algebraic code, structured representation through algebraic data types (ADTs) and their variants, LLM reasoning and agent collaboration, and neural network inference and automatic differentiation. Large models gave us language as an interface. Since the introduction of the Transformer, attention-based networks have become a general computational architecture, and training them at scale has brought extraordinary expressive power and transfer capabilities. One difficulty persists: a beautifully worded answer can be hard to verify. Where did it come from? Does the reasoning hold? Can we reproduce and audit it? The difficulty lies in the gap between the form of the answer and what engineering requires. Natural language serves human communication well; our systems need objects they can compose, trace, and execute. Meanwhile, neural networks themselves are acquiring a more programmatic representation. ONNX (ONNX Project, 2025) uses graphs and operators as an intermediate representation (IR), versions operator semantics, and leaves execution to a runtime. On the training side, automatic differentiation expresses learning through the chain rule on a graph. We can organize the forward and backward passes as composable programs. In this sense, both inference and learning are algebraic. Our task is to give them suitable interfaces and contracts.

Language may be an interface, but software needs structure it can compose, verify, and replay. Algebraic code offers a direct approach. Long-chain (curried) functions and combinators connect computations. Sum types and ADT variants describe the legal shapes of data. Algebraic pattern matching (APM) dispatches on those shapes and checks coverage. These facilities are now common in mainstream languages. Extensible objects and enumerable data shapes have begun to meet, and algebraic code supplies abstractions stable enough to work across both. The same engineering patterns can travel among Swift, F#, Scala, Kotlin, Rust, C#, and other languages. The chapters that follow show how.

1. Our Approach: Algebraic Code and the Token Paradigm

We bring ADT variants and ideas from category theory to LLM and agent engineering. Types and pattern matching organize knowledge, reasoning, tasks, and effects so that AI code, like a design pattern, can be reused, verified, and evolved. By the token paradigm we mean the following process. An LLM first produces structured tokens through a constrained schema or function call. We represent those tokens with a strictly typed ADT and pass them to an execution or inference engine whose behavior can be checked. Structured output and function or tool calling can bind generation directly to JSON Schema and program interfaces, reducing cleanup and making replay easier.

Our subject extends beyond functional programming. Programmers can work with functions, methods, and function pointers without appealing to the lambda calculus, although the lambda calculus remains a minimal model for functional semantics. Category theory gives us an abstract mathematical language for structures and their composition that travels well between domains. It distinguishes and names different structures for combining functions, including functors, natural transformations, and monads. Our concern is the ability to model algebraically with ADTs, pattern matching, immutable data, combinators, and effect abstractions. These facilities do not depend on the purity of a lambda calculus. They let us organize code so that we can compose it and prove properties about it. The ubiquitous long-chain function is a programming counterpart of a categorical idea. In ADT programming we analyze how meanings compose, then organize and name what a token sequence carries as abstract syntax (an AST) and algebraic sums and products. These are central to the token paradigm.

2. Algebraic Code Across Languages: Composition Alongside OOP

The minimal grammar of algebraic code is ADTs (sums and products) plus pattern matching. This combination is now common infrastructure in mainstream languages:

The common idea: a closed hierarchy with pattern matching enumerates the legal states, lets a compiler check for missing cases, and expresses domain invariants up front. Algebraic code gives object-oriented programs a powerful data-oriented technique for composition.

3. Category Theory in Mainstream Languages

Categorical abstractions are another important part of algebraic code: category theory views algebra from a particularly high level of abstraction. In modern languages, long-chain functions (currying) turn a multiargument function

f:(A×B)→Cf:(A \times B) \rightarrow C

into an equivalent chain that accepts A first and B next:

A→(B→C)A \rightarrow (B \rightarrow C),

This naturally supports partial application and composition in pipelines. The trailing closures of languages such as Swift, including its support for multiple trailing closures, make it easier to fix one argument and continue building the chain. An API becomes easier to compose and can express more in a few lines. The categorical counterpart is the exponential-object isomorphism, also called the exponential law or currying isomorphism:

Hom(X×Y,Z)≅Hom(X,ZY)Hom(X \times Y,Z) \cong Hom(X,Z^{Y}),

Giving an arrow out of a product is equivalent to giving an arrow into the function space ZYZ^{Y}. Currying and composition express this law at the level of types.

The categorical abstractions Functor, Applicative, and Monad are already present in everyday APIs:

This approach draws on Moggi and Wadler. Categorical semantics describes computations and effects, and a monad organizes effects such as I/O, exceptions, and state under the identity and associativity laws. See Chapter 2.

4. Algebraic Code in Neural Network Inference and Learning

In deep learning, a network is an algebraic composition of operators. ONNX turns this idea into a standard. Its IR represents models with graphs and operators. An operator can be primitive, or a function can be defined by expanding it into a subgraph. The IR and operators are independently versioned, and ONNX Runtime executes compatible operator sets. A computation graph is thus a rewritable, composable algebraic object. On the training side, PyTorch autograd (PyTorch Core Team, 2025) dynamically records a directed acyclic graph during the forward pass. The chain rule connects leaf tensors to the root, and the backward pass follows the graph to compute gradients. Learning becomes algebraic differentiation on a graph. In .NET, TorchSharp (.NET Foundation & Microsoft, 2025a, 2025b) binds directly to LibTorch. Its tensor, module, and gradient APIs follow PyTorch semantics, making the same combination of algebraic graphs and automatic differentiation available in F#. Chapters 4–6 model networks and operator graphs with ADTs and describe learning using ReverseGraph and AD (JVP/VJP). Chapter 5 connects the representation to Transformer nodes and operators. Together these chapters show how algebraic code spans inference (the forward pass) and learning (the backward pass).

5. Connecting Agents to Large Language Models

We treat an agent as a collection of algebraic interfaces governed by contracts. Retrieval turns external material into structured records with provenance, inference checks conclusions against rules, and the LLM translates between natural language and these structures.

Chapter 1 illustrates the distinct responsibilities of retrieval and inference with the AR-Agent and UR-Agent. The later chapters concentrate on the more stable foundations: representation, composition, lowering, automatic differentiation, and executable semantics.

6. A Guide to the Chapters

We begin by using algebraic code and the token paradigm to connect language and programs. We introduce the basic vocabulary and contracts: long-chain (curried) functions and combinators; sum types, ADT variants, and APM; structured output and function or tool calls; and the division of responsibilities between the AR-Agent and UR-Agent.

Types and categories give a common account of modern composition: map, zip, and flatMap correspond to Functor, Applicative, and Monad. The exponential-object isomorphism underpins currying and partial application. We generalize the passage from transforming values to transforming values in context into programming laws that support reasoning.

Sums, products, unit, and the empty type give us a syntax and equational laws for constructing ADTs. We show how APM checks exhaustiveness and dispatches on shape, then compare ADTs and OOP and show how to bridge them.

We treat a network as an algebraic composition of operator graphs. ADTs describe tensors, operators, and subgraphs. Relating a cross-framework IR such as ONNX to its runtime makes our working assumption explicit: a graph is a composable program.

GPT-2 and attention make the abstraction concrete. We relate nodes, operators, and parameters to ADT structures, map the operator level to the module level, and show how an algebraic graph supports inference in practice.

We describe learning as differentiation on a graph, using JVPs, VJPs, reverse mode, and ReverseGraph. We show how ADTs organize the training loop from the forward pass through backpropagation to an optimizer update, and what the implementation needs to get right.

From compositional semantics we develop an executable approximation. Syntax, semantics, and constraints become exchangeable ADT fragments and rules. We translate stretches of text into structured tokens and follow the path from language through representation to executable checks.

The model proposes candidates, algebraic structure bounds the legal shapes, programs execute them, and evidence and rules verify the results. Three principles sum up the relationship: representation before generation, composition before scale, and verification before acceptance.

The core edition keeps the durable concepts, methods, and full arguments in the text. Assignments, starter code, and acceptance criteria change more quickly and live together in the open-source repository, where they can be run, tested, and maintained.

7. Readers and Classroom Use

Open-source repository for examples and starter code:

https://github.com/PanWuming/AlgebraicCode

For an informal introduction, start with Category Theory Meets Programming: A Roundtable at the front of the book. It offers a quick way to build a mental map of the abstractions.

8. How to Read This Book

Start with Chapter 1 for the big picture, then follow Chapter 3, Chapter 4, Chapter 5, Chapter 6, Chapter 7, and Chapter 8. Engineers may prefer to start with Chapters 1, 4, 5, and 6. Readers interested in programming languages and logic may start with Chapters 2, 3, and 7. Both routes come together in Chapter 8.

9. Closing Remarks and Acknowledgments

This book grew out of technical work and can also serve as a textbook for a course on algebraic code and AI frameworks. Our aim is to give students, researchers, and practitioners a theoretical foundation, a practical guide, and ideas to carry into their own work.

We believe that algebraic code and large language models together will help shape the next wave of technological change. We hope this book encourages readers to think further, develop the field, and put its advances to work for the benefit of others.

10. Funding

Publication was supported in part by a 2023 Sichuan University Higher Education Teaching Reform Project (tenth round, project SCU10337). The book also benefited from teaching reform and seed-funding projects at the university’s College of Computer Science and College of Software Engineering in recent years.

Contact the author at panwuming@scu.edu.cn.

1id1.net / ENGLISH EDITION

Contents

CHAPTER 1

An Overview of Algebraic Code and the Token Paradigm

This book starts from a simple idea: write code algebraically, then connect that composable code to an LLM. Over the past thirty years, ideas from category theory have entered programming through Haskell, giving us three powerful tools for composition: Functor, Applicative, and Monad (FAM). Moggi (Moggi, 1991) used monads to give a unified account of the semantics of computation. Wadler (Wadler, 1992b, 1995) turned that account into a practical way to organize exceptions, state, I/O, and nondeterminism. McBride and Paterson (McBride & Paterson, 2008) subsequently identified Applicative as the abstraction for combining independent steps. This gave us three levels of composition: transform a value (Functor), combine independent computations, possibly in parallel (Applicative), and sequence dependent computations (Monad). We still draw on that tradition when building reliable systems. Meanwhile, mainstream languages have made algebraic data types (ADTs) first-class citizens. Algebraic Code is an everyday tool for modeling and composition.

In the age of LLMs, composability must extend to interactions with models. RAG (Y. Huang et al., 2024; Lewis et al., 2020) allows a generative model to draw on external knowledge on demand, reducing hallucinations and making sources traceable. Approaches such as ReAct (Yao et al., 2023) interleave reasoning and action so that the model can look things up as it reasons and leave a record that can be interpreted and corrected. Algebraic Code gives us a structure we can refactor, the token paradigm gives us a language for communication, and LLMs and protocols connect the two. Beginning with long-chain functions and combinators, we will assemble these capabilities into intelligent systems that can be verified, maintained, and extended.

This chapter maps out the terrain:

1.1 Engineering Motivations and Context

Software engineering teams are feeling the strain of object-oriented programming (OOP). Class hierarchies grow ever taller, implicit state spreads, and framework “magic” hides dependencies. For many teams, a small change can ripple through the whole system. Meanwhile, AI is making it faster to write a piece of code that runs. The scarce resources are now verifiable abstractions and composable structures.

We therefore raise the level of abstraction above our existing OOP assets, using algebraic design patterns to assemble systems. Consider two representative tools.

ADTs and LCFs extend well beyond traditional functional programming. These building blocks work across paradigms and already occur in everyday Swift, Kotlin, Rust, Scala, F#, TypeScript, and C#. We advocate building on OOP by making context explicit, expressing constraints in types, and giving workflows an algebraic structure. Complexity becomes visible, composition becomes the default, and verification moves toward compile time. In an era of AI-assisted development, code that runs can also be reasoned about, evolved, and reused.

Both ADTs and long-chain functions (LCFs, or curried functions) have algebraic roots. The latter arise from the currying isomorphism in category theory, itself an algebraic language and method. This is why we call the approach “Algebraic Code.”

Large language models (LLMs) have also changed how we generate and execute software logic. Given natural language, an LLM can generate structured output, such as code fragments or data in a specified format. We call this “the token paradigm” (Tokenism). It centers on the token, the basic unit of LLM output, as a carrier of structured information. The token paradigm inherits the symbolist use of symbols to express explicit rules while drawing on the powerful language-generation capabilities of connectionism, or deep learning (Xiong et al., 2024). The move from hand-coded rules in symbolic AI to LLM-generated structured results marks a shift from symbolism toward the token paradigm.

Two trends thus shape software development. Engineers are turning to algebraic programming with long-chain functions and ADTs to improve quality and maintainability. They are also using LLMs to produce structured information through a Token KIF interface, reducing repetitive coding. The following sections develop this picture.

1.2 A Map of Algebraic Capabilities and the Role of Category Theory

These developments call for an engineering approach that safely integrates LLM capabilities into conventional software. This is the motivation for Algebraic Code: we draw on formal methods from algebra and category theory to build an algebraic capability stack for intelligent applications that are composable, amenable to reasoning, and easy to audit.

The stack has two foundations. One consists of type-system and program-structure features exemplified by algebraic data types (ADTs), which precisely characterize data and state spaces. The other consists of abstract models grounded in category theory, which describe computational processes, especially computations with side effects, at a higher level.

Category theory and abstract models of computation. Category theory supplies abstractions that unify different concepts of computation. In software these include general interfaces such as Functor, Applicative, and Monad. They give us structured ways to handle side effects. A functor supports mapping in a context: we apply a function to a value held within that context. An applicative functor lies between Functor and Monad. It allows computations in independent contexts to be sequenced and their effects combined without knowing previous results. A monad lets us chain computations, feeding each result into the next step and connecting effectful operations in the form of pure functions. As Wadler (Wadler, 1995) observed, monads offer a convenient framework for modeling global state, exception handling, output, and nondeterminism in a pure functional language. Functor, Applicative, and Monad let us encapsulate side effects in a structure governed by types and composition laws. Effects that would otherwise spread throughout a program can thus be managed within algebraic structures.

Together these foundations give the algebraic capability stack a repertoire spanning type systems and abstractions for computation. It includes parametric polymorphism (Reynolds, 1983b), introduced by Reynolds so that a function can exhibit uniform behavior at any type, as well as higher-order functions (which take or return functions), immutability, pure functions, lazy evaluation, and function composition. The table below introduces abbreviations for these capabilities. Together they give LLM-driven applications a firm engineering foundation: data have an explicit algebraic structure, and computations obey provable laws of composition, making systems easier to reason about and verify.

What capabilities does algebraic programming depend on, and how well do mainstream languages support them? They span type systems, functional programming, and categorical abstractions. We assign each an abbreviation and compare support across 13 common languages. The following twelve capabilities cover the principal elements of algebraic programming, from polymorphism to function composition.

The following table compares these algebraic capabilities across 13 modern programming languages.

Table 1-1. Algebraic capabilities of 13 modern programming languages. A check mark (✓) indicates strong or native support, a tilde (~) indicates support through libraries, conventions, or other non-native means, and a dash (–) indicates an absent or uncommon feature. The JS/TS entry primarily reflects TypeScript. C++ denotes C++11 and later, although ADTs require C++17 std::variant or a library. Java uses Java 8+ as a baseline; later versions improve support for sealed hierarchies and pattern matching.

Language PP ADT AE PM PF IM
Haskell ✓ ✓ ~ ✓ ✓ ✓
Python ~ ~ – ~ ~ ~

JavaScript /

TypeScript

✓ ✓ – ~ ~ ~
C++11+ ✓ ~ – – ~ ~
C# ✓ ~ – ~ ~ ~
Scala ✓ ✓ ~ ✓ ~ ✓
F# ✓ ✓ ~ ✓ ~ ✓
Go ✓ – – – ~ –
Rust ✓ ✓ – ✓ ~ ✓
Kotlin ✓ ✓ – ✓ ~ ✓
Swift ✓ ✓ – ✓ ~ ✓
Java 8+ ✓ ~ – ~ ~ ~

Table 1-1 (continued). Algebraic capabilities of modern programming languages

Language HOF LE FAM FC C LCF
Haskell ✓ ✓ ✓ ✓ ✓ ✓
Python ✓ ~ ~ ~ ✓ ~

JavaScript /

TypeScript

✓ ~ ~ ~ ✓ ~
C++11+ ✓ ~ ~ ~ ✓ ~
C# ✓ ~ ~ ~ ✓ ✓
Scala ✓ ~ ✓ ✓ ✓ ✓
F# ✓ ~ ✓ ✓ ✓ ✓
Go ✓ – ~ ~ ✓ ~
Rust ✓ ~ ~ ~ ✓ ~
Kotlin ✓ ~ ~ ~ ✓ ~
Swift ✓ ~ ~ ~ ✓ ✓
Java 8+ ✓ ~ ~ ~ ✓ ~

Functional languages such as Haskell and F# perform well on almost every dimension. Java and Python, by comparison, have notable gaps in areas such as ADTs, immutability, and lazy evaluation. Mainstream multiparadigm languages such as Swift, Rust, Kotlin, and C# increasingly incorporate algebraic features and occupy the middle of the map. Swift supports ADTs and pattern matching with enum and switch. Rust has ADTs (enum) and immutable bindings by default. Both still use imperative, eager execution by default. Overall, modern languages are moving toward algebraic programming. The map makes their respective strengths and limitations visible when choosing an implementation language or migrating code.

These capabilities work together as a toolkit for Algebraic Code. Algebraic data types and pattern matching express complex logic concisely and let the compiler check exhaustiveness. Pure functions with immutable data produce predictable, testable units of logic. Higher-order functions and currying make it possible to write reusable general-purpose combinators. A monad provides an interface governed by laws such as associativity and identity for chaining operations in error handling and asynchronous computation. Later examples show how these capabilities work together in software architectures for the LLM era.

1.3 The Token Paradigm: Structured Representations and LLM Output

Traditional symbolic AI relies on structured representations such as knowledge graphs and logical rules to enable machines to “understand” a problem. A large language model typically emits unstructured text as a sequence of tokens. The token paradigm brings the two together by introducing structure into the generated sequence, retaining the model’s linguistic flexibility and the explicitness of symbolic representations.

The problem. Traditional symbolic AI emphasizes structured representations such as knowledge graphs, logics, type systems, and semantic categories to ensure composability, verifiability, and reuse. LLMs naturally generate unstructured token sequences. They excel at language generation and heuristic reasoning, but their output can be difficult to verify and may contain hallucinations. Aligning the two has become a central research question. Here the token paradigm means embedding structure (schemas, grammars, constraints, or evidence) in the sequence generated by an LLM, then materializing it as computable abstract data types and verifiable semantic objects. The result preserves the model’s generative capabilities while giving its output a precise, auditable symbolic interpretation.

1.3.1 Theoretical Background of Structured Representations

Implication. If an LLM is to serve as a powerful language interface whose products can be used in software, we must return to structure and to composable representations.

1.3.2 Strengths and Limitations of LLM Output

Implication. High-assurance applications can use the language capabilities of LLMs only when the output is structured and backed by evidence.

1.3.3 Three Paths from Token Output to Structured Tokens

  1. Structured or constrained decoding

    • Mechanisms such as JSON or schema-constrained output and function calling can constrain the model during generation, placing information in a parseable schema with specified fields, types, and value domains. Mainstream APIs offer integrated support for structured output, JSON mode, and function calling, connecting prompting to constraint enforcement and parsing (Google DeepMind, 2025b, 2025a; Microsoft Azure AI, 2025; OpenAI, 2025b, 2025a).

    • The theoretical significance is that generation is bound in advance to a decidable domain of formats, types, and syntax. This reduces downstream cleanup and improves reproducibility and composability.

  2. Delegating reasoning to a verifiable executor

    • In program-aided and program-of-thought approaches, the LLM translates natural language into a program or DSL as an intermediate representation and delegates solving to an interpreter or solver, substantially reducing errors in arithmetic and symbolic reasoning. PAL illustrates the general advantage of generating and interpreting a program over reasoning entirely in natural language (Chen et al., 2022; Gao et al., 2022; Wei, Wang, Schuurmans, & others, 2022).

    • The theoretical significance is that an unverifiable answer produced in one linguistic step becomes a sequence from language to structure to execution. Responsibility for correctness passes to an execution system with explicit semantics.

  3. Integrating external knowledge in structured form

    • RAG connects nonparametric memory (a document index) to generation, substantially improving factual accuracy. Both theory and experiment show how retrieval and generation complement each other (Y. Huang et al., 2024; Lewis et al., 2020).

    • GraphRAG goes further by extracting a knowledge graph from documents. It aligns relations across documents and passages and supports multihop reasoning while accommodating scale and traceable provenance (Janssen, 2008).

Summary. These approaches constrain form through decoding, delegate semantic execution to programs or reasoning engines, and introduce verifiable external knowledge through RAG or knowledge graphs. Together they turn unconstrained tokens into structured tokens.

1.3.4 Relation to Neuro-Symbolic Integration

A recent survey of neuro-symbolic approaches argues that a principled integration of trainable neural networks with interpretable symbolic systems capable of reasoning requires composable interfaces and consistent semantics at the levels of representation, learning, and inference. This agrees with the token paradigm’s use of schemas at generation time and enforcement of semantic alignment at execution time (d’Avila Garcez & Lamb, 2023).

1.3.5 Conclusion

The token paradigm goes beyond reducing LLM errors. Its central idea is to translate generated output into structure, connect structure to semantics, and submit those semantics to verifiable execution. Its three pillars are structured output, programmatic or logical intermediate representations, and retrieval or knowledge-graph integration. The approach builds on formal semantics and semantic parsing while harnessing the generative and planning capabilities of LLMs. It provides a methodological and engineering path toward unifying language, knowledge, and reasoning.

1.4 Interactions Between LLMs and Algebraic Agents: AR-Agent and UR-Agent

In this book’s algebraic client architecture, the LLM plans and generates in natural language, and two kinds of algebraic agent turn the results into executable, verifiable structures.

The two agents share a contract: TokenKIF as the interchange format and TokenADT as the in-program data type. The three-way interaction among the LLM, agents, and program can then be implemented and replayed.

1.4.1 Dividing Responsibilities: When to Call AR or UR

1.4.2 A Minimal Interaction Contract

The LLM emits a command token in the ar.* or ur.* namespace instead of unconstrained text. The agent returns a structured result and a verifiable trace.

Example requests

// Ask AR for source material
{"cmd":"ar.retrieve",
 "query":"Why do residual connections in a Transformer help gradients propagate?",
 "top_k":6, "schema":"KIF.v1"}

// Ask UR to perform inference
{"cmd":"ur.prove",
 "goal":"∀x (Parent(x,Ann) → Ancestor(x,Ann))",
 "kb":[ "...KIF rules and facts..." ],
 "logic":"FOL", "strategy":"resolution"}

Example responses

// AR response: structured knowledge and citations
{"kif":[ ... ], "citations":[{"docId":"paper.pdf","page":12,"span":[341,528]}],
 "trace":[{"step":"hybrid-retrieval"},{"step":"rerank"}]}

// UR response: a verifiable inference result
{"result":"proved",
 "proof":{"format":"LFSC","size":1240},
 "trace":[{"step":"resolve","in":[17,42],"mgu":{"x":"a"}},{"step":"empty-clause"}]}

Constraints

All responses must parse into TokenADT. AR must supply citations, and UR must be able to export a proof.

1.4.3 AR-Agent: Interface and Implementation, from Source Material to KIF

Engineering note. Keep the KIF extraction format narrow, with a few stable fields. Define mandatory fields and required evidence before adding detail.

1.4.4 UR-Agent: Interface and Implementation, from Knowledge to Proof or Solution

Engineering note. Persist the ProofToken (input clauses, unifier/MGU, and output clause) so that a small external kernel can check the proof independently.

1.4.5 On the LLM Side: Routing, Planning, and Explanation

  1. Router. Choose the order and budget for calls to ar.*, ur.*, and tools.* according to the task’s intent and constraints.

  2. Plan. Break a complex goal into the subgoal sequence retrieve → extract → prove/solve → render.

  3. Render. Render kif/proof as text, tables, or code that the reader can understand, preserving the conclusion and evidence.

A practical pattern is ReAct prompting: Thought determines the route, Action issues an ar.* or ur.* command, and Observation receives KIF or a proof so planning can continue.

1.4.6 A Developer’s Checklist

1.4.7 A Simple Example

Question. “Prove P(f(f(a))) from the axioms P(a) and ∀x(P(x)→P(f(x))), and cite the source.”

1.4.8 Summary

The three cooperate under a common TokenKIF/TokenADT contract. It preserves the LLM’s strengths in expression and planning while bringing retrieval and reasoning into an executable, verifiable algebraic framework.

1.5 A Quick Example: Turning a Table of Differentiation Rules into a Runnable Program in 30 Lines of Algebraic Code

Aim. Before turning to the theory, we use a runnable example in which the structure expresses the rules to move from “code = control flow” to “code = ADT variants + pattern matching + recursion schemes.” You will see how to

1.5.1 Goal and Expression

The expression comes from Baydin et al. (2018):

y=ln(x1)+x1⋅x0−sin(x0),y = ln\left( x_{1} \right) + x_{1} \cdot x_{0} - sin\left( x_{0} \right),\quad

∂y∂x1=1x1+x0.\frac{\partial y}{\partial x_{1}} = \frac{1}{x_{1}} + x_{0}.

1.5.2 The ADT and Its Branches: Structure as Grammar, Branches as Rules

The following F# code runs as written (.NET 9 / F# 9). Expr combines sums, products, and the unit type. The function d translates each rule into a branch, and eval performs numerical evaluation.

// ===== Expression ADT =====
type Expr =
  | Zero | One
  | Const of double
  | V of int
  | E   of Expr | Ln  of Expr
  | Sin of Expr | Cos of Expr
  | Tanh of Expr | Sech of Expr
  | Neg of Expr
  | Plus of Expr * Expr
  | Sub  of Expr * Expr
  | Mul  of Expr * Expr
  | Div  of Expr * Expr

// ===== Differentiation: one branch per rule =====
let rec d (e: Expr) (i:int) : Expr =
  match e with
  | Zero | One | Const _ -> Zero
  | V a                  -> if a = i then One else Zero
  | E p                  -> Mul(E p, d p i)                           // (e^p)' = e^p · p'
  | Ln p                 -> Div(d p i, p)                             // (ln p)' = p' / p
  | Sin p                -> Mul(Cos p, d p i)
  | Cos p                -> Mul(Neg(Sin p), d p i)
  | Tanh p               -> Mul(Mul(Sech p, Sech p), d p i)
  | Sech p               -> Mul(Neg(Mul(Sech p, Tanh p)), d p i)
  | Neg p                -> Neg(d p i)
  | Plus(p,q)            -> Plus(d p i, d q i)
  | Sub(p,q)             -> Sub (d p i, d q i)
  | Mul(p,q)             -> Plus(Mul(d p i, q), Mul(p, d q i))        // Product rule
  | Div(p,q)             -> Div(Sub(Mul(d p i, q), Mul(p, d q i)), Mul(q,q)) // Quotient rule

// ===== Evaluator =====
let rec eval (e:Expr) (x:double list) : double =
  match e with
  | Zero -> 0.0 | One -> 1.0
  | Const a -> a
  | V i -> x.[i]
  | E p -> System.Math.Exp (eval p x)
  | Ln p -> System.Math.Log (eval p x)
  | Sin p -> System.Math.Sin (eval p x)
  | Cos p -> System.Math.Cos (eval p x)
  | Tanh p -> System.Math.Tanh (eval p x)
  | Sech p -> 1.0 / System.Math.Cosh (eval p x)
  | Neg p -> -(eval p x)
  | Plus(p,q) -> eval p x + eval q x
  | Sub(p,q)  -> eval p x - eval q x
  | Mul(p,q)  -> eval p x * eval q x
  | Div(p,q)  -> eval p x / eval q x

Run the demonstration:

let y = Sub(Plus(Ln (V 1), Mul(V 1, V 0)), Sin (V 0))
// y = ln x1 + x1·x0 − sin x0
let z = d y 1
// ∂y/∂x1
printfn "z(raw) = %A" z

let v = eval y [5.0; 2.0]
// x0=5, x1=2
printfn "eval(y,[5;2]) = %.15f" v
// Result: 11.652071455223084

Each mathematical rule corresponds to one branch. Exhaustiveness checking ensures that every form is covered, and the type makes ill-formed expressions unrepresentable.

1.5.3 Corresponding Swift Code (Excerpt)

indirect enum Expr {
  case zero, one
  case const(Double), v(Int)
  case e(Expr), ln(Expr), sin(Expr), cos(Expr), tanh(Expr), sech(Expr)
  case neg(Expr), plus(Expr,Expr), sub(Expr,Expr), mul(Expr,Expr), div(Expr,Expr)
}

func d(_ e: Expr, _ i: Int) -> Expr {
  switch e {
  case .zero, .one, .const: return .zero
  case .v(let a): return a == i ? .one : .zero
  case .e(let p):  return .mul(.e(p), d(p,i))
  case .ln(let p): return .div(d(p,i), p)
  case .sin(let p): return .mul(.cos(p), d(p,i))
  case .cos(let p): return .mul(.neg(.sin(p)), d(p,i))
  case .tanh(let p): return .mul(.mul(.sech(p), .sech(p)), d(p,i))
  case .sech(let p): return .mul(.neg(.mul(.sech(p), .tanh(p))), d(p,i))
  case .neg(let p):  return .neg(d(p,i))
  case .plus(let p, let q): return .plus(d(p,i), d(q,i))
  case .sub (let p, let q): return .sub (d(p,i), d(q,i))
  case .mul (let p, let q): return .plus(.mul(d(p,i), q), .mul(p, d(q,i)))
  case .div (let p, let q): return .div(.sub(.mul(d(p,i), q), .mul(p, d(q,i))), .mul(q,q))
  }
}

1.6 Suggested Reading Paths

Structure comes first throughout this book. Algebraic Code, algebraic data types, neural-network computation graphs, large language models, automatic differentiation, and executable representations of natural language all fit into this picture. This core edition offers four paths that converge, so you need not read it from cover to cover. Each path builds a shared vocabulary in Chapter 1 and brings the methods together in Chapter 8.

1.6.1 A Quick Route Through the Main Argument

Start with Chapter 1 for the token paradigm, ADTs and APM, and the division of labor between LLMs and structured interfaces. Read Chapter 3 and Chapter 4 to see how closed variants and pattern matching turn computation graphs into composable algebraic objects. Chapter 5 and Chapter 6 apply this representation to Transformers and automatic differentiation. Finish with Chapter 7 and Chapter 8, which extend the method to logical approximations of natural language and to verifiable intelligence.

Follow a single thread: language or model output is converted into structure, structures compose into programs, programs produce traceable results, and those results are checked against types, shapes, rules, and evidence. No background in category theory is required. Keep asking three questions: What shapes can the data legitimately take? Through what interface do the parts compose? What mechanism verifies the result?

1.6.2 An Engineering-First Route

Developers and architects can read Chapter 1, Chapter 4, Chapter 5, Chapter 6, Chapter 7, and Chapter 8 in that order. Chapter 4 provides a minimal cross-framework abstraction for neural networks. Chapter 5 relates it to Transformers and ONNX. Chapter 6 shows how to organize reverse computation over the same graph structure. Chapter 7 extends structured output to natural language. Read each chapter as a problem in interface design rather than a manual for a particular framework.

The engineering focus is on boundaries. The LLM must generate within a structured contract. Nodes must explicitly declare inputs, outputs, attributes, types, and shapes. Lowering must map high-level structures deterministically to a backend. Backpropagation must reuse the composability of the forward graph. Natural language must pass through a parseable intermediate representation before it enters the program. The assignments in the companion repository test whether these boundaries work in practice.

1.6.3 A Deeper Theoretical Route

Readers interested in programming languages, logic, or semantics can follow Chapter 2, Chapter 3, Chapter 6, Chapter 7, and Chapter 8. Chapter 2 uses Functor, Applicative, and Monad to describe minimal contracts for composition and effects. Chapter 3 uses sums, products, unit, and empty types to explain the syntax for constructing ADTs. Chapter 6 treats differentiation as a composable program transformation. Chapter 7 considers how finite, strongly typed structures can approximate core logical relations in natural language.

On this route, category theory is a language for checking whether compositions are valid. Look beyond terminology: Does a mapping preserve structure? Is sequencing explicit? Are side effects confined to the interface? Can a transformation be reproduced and checked?

1.6.4 LLMs and Natural Language

Readers studying models and their applications can start with Sections 1.3 and 1.4 of Chapter 1, then read Chapter 5, Chapter 7, and Chapter 8. Chapter 5 shows how the model’s own computations can be viewed as an algebraic graph. Chapter 7 shows how model output can move beyond free text to strongly typed tokens and rule structures. Chapter 8 defines the system boundary: models propose candidates, and programs and evidence determine which candidates can be accepted.

On this route, avoid equating structured output with a different JSON format. Its value lies in connecting type checking, pattern matching, function calls, execution traces, and external evidence. Once governed by these constraints, the LLM’s generative power becomes a reusable software capability.

1.6.5 Companion Repository

The exercises from the print edition are now collected at https://github.com/PanWuming/AlgebraicCode. The repository provides runnable starter code, tests and acceptance criteria, and instructions that can be updated as the toolchain changes. The book explains why the material is organized as it is and how to organize it. The repository shows how to run and verify it.

Whatever path you choose, complete at least one end-to-end assignment: convert natural language or model output to an ADT, apply a repeatable transformation, and use tests, evidence, or rules to explain why the result holds. Completing this cycle puts the book’s central method into practice.

CHAPTER 2

Long-Chain Functions, Functors, and Monads: The Syntax and Semantics of Composition

The Haskell community helped bring category theory systematically into programming languages. Moggi (Moggi, 1991) used monads to establish a categorical semantics of computation. Wadler (Wadler, 1992b, 1995) turned monads into a practical way of organizing exceptions, state, output, and nondeterminism. This influence extends well beyond mathematical curiosity. A particularly accessible example is the long-chain function: instead of supplying several arguments at once, we supply one argument at a time to a chain of functions, each returning the next. This opens a path from function composition to combinators and, ultimately, to Algebraic Code.

In the 2000s and beyond, the abstractions became more precise. Applicative (McBride & Paterson, 2008) separated the aggregation of independent steps from Monad, and arrows (Hughes, 2000) further generalized the forms composable computation could take. In the toolchain, GHC1 (GHC Development Team, 2025; Marlow & others, 2016) can automatically lower do notation to Applicative composition with ApplicativeDo, connecting the abstraction directly to syntactic sugar and optimization. Categorical abstractions such as Functor, Applicative, and Monad now appear in mainstream languages as ways to construct and compose blocks of code that handle contexts, exceptions, parallelism and concurrency, resources, and state. They complement object-oriented abstractions such as types, encapsulation, and polymorphism.

Why learn these ideas? An engineer’s perspective

  1. Distinct semantic levels. Functor handles transformations of values, Applicative aggregates independent steps, and Monad expresses dependent sequencing or short-circuiting. Each has a small, clear role.

  2. Refactoring. Identity, associativity, and unit laws tell us when we can fuse two maps or split a flatMap without changing behavior, giving us greater freedom to refactor.

  3. Parallelism. Applicative naturally supports parallel aggregation of independent steps, which maps directly to Swift’s async let, Kotlin’s parZip, or Rust’s join!.

  4. Testability. Option, Result, Task, and related contexts make effects, errors, and missing values explicit. Unit tests can use property-based testing to focus on pure transformations.

  5. Cooperation with OO. Object-oriented design models and encapsulates data. Categorical composition assembles behavior from small units. Together they offer maintainable data structures and transparent control flow.

What this chapter covers

2.1 Long-Chain Functions and Code Composition

A long-chain function, or curried function, is a basic form of composition in Algebraic Code. It decomposes a function of several arguments into a chain of single-argument functions, each returning the next. In category theory this corresponds to the familiar isomorphism for exponential objects:

A→(B→C)≅(A×B)→CA \rightarrow (B \rightarrow C) \cong (A \times B) \rightarrow C

In type terms,

A→B→C(right-associative, equivalent to A→(B→C))A \rightarrow B \rightarrow C\quad\text{(right-associative, equivalent to }A \rightarrow (B \rightarrow C)\text{)}

has the same expressive power as a function that takes a Cartesian product of arguments at once, (A×B)→C(A \times B) \rightarrow C. The forms and the ways they compose differ. We can extend the same rule to longer chains:

A→B→C→D≅A→(B→(C→D))≅(A×B×C)→DA \rightarrow B \rightarrow C \rightarrow D \cong A \rightarrow (B \rightarrow (C \rightarrow D)) \cong (A \times B \times C) \rightarrow D

Currying converts a function of several arguments into functions that each accept one argument in turn. Partial application supplies some initial arguments to obtain a function of fewer arguments. Together they facilitate composition and pipeline notation.

Basic laws

Notation 1: Function composition

Write the steps as a chain of composed pure functions:

// F#
let h = f >> g >> k      // Equivalent to fun x -> k (g (f x))

Notation 2: A value pipeline

Let the value flow through the functions, following the direction of data flow:

// F#
let y = x |> f |> g |> k

Notation 3 (Swift): Trailing closures and chained higher-order functions

Swift uses trailing closures to make chained calls easier to read while retaining the semantics of pure composition:

let result = xs
  .map { transform($0) }
  .filter { predicate($0) }
  .flatMap { expand($0) }

In this book, a curried pipeline specifically refers to the three forms of pure function chain above: currying with composition or piping, with trailing closures available for readability.

2.1.1 F#: Native Currying and Combinators

F# functions are curried by default, and arrows associate to the right:

let multiply x y = x * y          // Type: int -> int -> int

let double = multiply 2           // Partial application: fix the first argument
let ten = double 5                // Evaluates to 10
assert (ten = 10)

Pipes and combinators let us write the data flow as a declarative chain:

let input = [ -2; -1; 0; 1; 2; 3 ]

let result =
    input
    |> List.map ((*) 2)           // Partially apply (*) to multiply by 2
    |> List.filter ((<) 0)        // ((<) 0) is equivalent to fun x -> 0 < x
    |> List.sum                   // Sum the elements
// result = 12

// Equivalent but more efficient: sumBy fuses map and sum, avoiding an intermediate list
let result2 =
    input
    |> List.filter ((<) 0)
    |> List.sumBy (fun x -> x * 2)

// Combinator example: multiply by 2, then add 3
let transform = ((*) 2) >> ((+) 3)
let demo = input |> List.map transform   // [-1; 1; 3; 5; 7; 9]

// Type signature of List.map (right-associative):
(*
val map : ('T -> 'U) -> 'T list -> 'U list
*)

Points to note

2.1.2 Swift: Currying with Returned Functions and Trailing Closures

Swift functions are not curried by default, but returning a function gives us the same effect. Trailing closures make the resulting chains concise and readable:

// Implement currying by returning a function: multiply : Int -> (Int -> Int)
func multiply(_ x: Int) -> (Int) -> Int { { y in x * y } }

let double = multiply(2)       // Partial application: fix the first argument
let ten = double(5)            // 10
assert(ten == 10)

// Declarative data pipeline: map / filter / reduce
let input = [-2, -1, 0, 1, 2, 3]
let sumPositiveTimesTwo = input
    .map { $0 * 2 }            // Trailing closure: write the transformation after the call
    .filter { $0 > 0 }
    .reduce(0, +)              // Add, starting from 0
// sumPositiveTimesTwo == 12

// A small higher-order apply function for use with a trailing closure
@inline(__always)
func apply<T, U>(_ value: T, using f: (T) -> U) -> U { f(value) }

let r1 = apply(5) { $0 * 2 }   // 10 (trailing closure syntax)

Points to note

The function above accepts an integer and a transformation closure. Trailing closure syntax lets us write the transformation { $0 * 2 } after the function call, improving readability. Many Swift standard-library combinators accept trailing closures, including array map, filter, and reduce. The resulting chains read almost like natural language.

Swift also provides compositional support for error handling. The throws keyword indicates that a function may throw an error. The rethrows keyword is used for functions that compose potentially throwing closures. A function declared rethrows can propagate an error from a closure argument without independently introducing an error. For example, the signature of Collection.map in the Swift standard library is

func map<T, E>(_ transform: (Self.Element) throws(E) -> T) throws(E) -> [T] where E : Error

If transform can throw, the map call needs try and may propagate an error. If the closure cannot throw, map will not throw either. For a higher-order function marked rethrows, the caller writes try only when the supplied closure may throw. Otherwise the chain remains an ordinary functional call with no try. This carries error semantics through a composition with little syntax: mark the potentially throwing link with try without explicitly catching errors at every step.

Swift also provides try? and try! to embed throwing behavior in different contexts:

In the following example:

enum CalcError: Error { case odd(Int) }

// A potentially throwing transformation: throw for odd x, return x*10 for even x
func risky(_ x: Int) throws -> Int {
    guard x % 2 == 0 else { throw CalcError.odd(x) }
    return x * 10
}

// A custom higher-order function similar to map; its key annotation is rethrows:
// The caller needs try only when the supplied closure can throw.
func applyAll<T, U>(_ xs: [T], _ f: (T) throws -> U) rethrows -> [U] {
    var out: [U] = []
    out.reserveCapacity(xs.count)
    for x in xs { out.append(try f(x)) }
    return out
}

let xs = [1, 2, 3, 4]

// 1) Nonthrowing closure: no try required
let squares = applyAll(xs) { $0 * $0 }               // [1, 4, 9, 16]

// 2) Throwing closure: use try; try? lifts failure into Optional
let firstDoubleEven: Int? = (try? applyAll(xs, risky))?.first
// risky(1) throws, so try? turns the whole call into nil, and first is still nil

// 3) Per-element soft failure: try? each element; compactMap drops failures
let firstSuccessful: Int? = xs.compactMap { try? risky($0) }.first
// => 20 (from 2*10): 1 is discarded and 2 succeeds

print("squares:", squares)
print("firstDoubleEven:", firstDoubleEven as Any)
print("firstSuccessful:", firstSuccessful as Any)

// 4) The same rethrows higher-order function also accepts nonthrowing functions
func bump(_ x: Int) -> Int { x + 1 }
let bumped = applyAll(xs, bump)                      // No try required
print("bumped:", bumped)

// 5) Another rethrows example: a value-level passthrough function
func passthrough<T, U>(_ value: T, using f: (T) throws -> U) rethrows -> U {
    try f(value)
}

// Use try! when failure can be ruled out (a thrown error would crash the program)
let forced: Int = try! passthrough(8, using: risky)  // 8 is even, so the call cannot throw
let safeForced: Int? = try? passthrough(8, using: risky)
print("forced:", forced, "safeForced:", safeForced as Any)

The output appears in the following order:

squares: [1, 4, 9, 16]

Calling applyAll with the nonthrowing squaring closure requires no try. Errors propagate through rethrows only when needed.

firstDoubleEven: nil

try? applyAll(xs, risky) throws on the first element, 1. The try? folds the whole call into nil, so .first is still nil. Failure is handled softly at the level of the entire chain.

firstSuccessful: Optional(20)

Here the handling is per element: xs.compactMap { try? risky($0) }. Each element gets its own try?. Failures are dropped and successes retained, so the first successful value is 2 * 10 = 20. This is per-element soft failure.

bumped: [2, 3, 4, 5]

Passing the nonthrowing bump (x+1) to applyAll again requires no try, illustrating the composability of rethrows.

forced: 80 safeForced: Optional(80)

We use try! on a path we can prove safe: 8 is even, so risky will not throw. The corresponding try? version yields Optional(80). The two illustrate the difference between asserting success and making the result optional.

This code treats error handling as a composable context. throws and rethrows determine where try is needed. try? lifts error handling into Optional so that it works with map and compactMap, while try! reduces boilerplate where safety can be proved. Long-chain functions thus extend naturally to error semantics: an error can propagate along the chain as needed, or be converted into data (Optional) and handled declaratively within the chain.

2.1.3 Summary

From a categorical perspective,

Hom(A×B,C)≅Hom(A,CB)Hom(A \times B,C) \cong Hom(A,C^{B})

underpins the type equivalence for long-chain functions. In F#, currying and partial application come by default. Combined with |> and >>, they produce readable, composable pipelines. In Swift, returned functions and trailing closures yield the same power of composition, with map / filter / reduce supplying a data pipeline. Long-chain functions (currying) give composition its basic syntax, allowing functions to fit together in sequence. Swift and F# use devices such as trailing closures and pipe operators to support chains. Alongside mechanisms such as throws/rethrows, they offer flexible composition in both syntax and semantics. With the type system’s guarantees, we can combine separate operations into complex functionality while keeping code modular and readable.

2.2 Functor: Lifting a Value Transformation into a Context

Intuitively, a functor is a context type that supports map. It preserves the shape of the container (its structure, ordering, emptiness, and so on), mapping each element from aa to bb. Abstractly, given an ordinary function u:a→bu:a \rightarrow b, a functor F lifts it to:

F(u):F[a]→F[b]F(u):F\lbrack a\rbrack \rightarrow F\lbrack b\rbrack

Familiar programming examples include Optional<T>, Array<T>, Result<Success, Failure>, List<'T>, and Option<'T>.

The two functor laws

  1. Identity. map id == id. Applying the identity function leaves a container’s contents and structure unchanged.

  2. Composition. map g >> map f == map (f ∘ g). Mapping twice in succession is equivalent to mapping the composite once.

These laws give map its pure functional reading: it introduces no side effect of its own and performs the equivalent transformation on the values.

2.2.1 Swift: Modern Idioms for Optional, Array, and Result

Optional as a minimal functor

let maybeNum: Int? = 2

let str: String? = maybeNum.map { "\($0 * 3)" }   // "6"
let noneMapped: String? = (nil as Int?).map { "\($0 * 3)" } // Still nil

// Quick composition-law test (assert directly in a playground or Swift package)
func compose<A,B,C>(_ g: @escaping (B) -> C, _ f: @escaping (A) -> B) -> (A) -> C { { g(f($0)) } }

let f: (Int) -> Int = { $0 + 1 }
let g: (Int) -> Int = { $0 * 2 }

let lhs = maybeNum.map(g).map(f)           // Map g, then map f
let rhs = maybeNum.map(compose(f, g))      // Map the composite once
assert(lhs == rhs)

Tip. Swift’s map accepts a KeyPath transformation, which can improve readability:

let words = ["Swift", "FSharp", "Functor"]
let counts = words.map(\.count)        // [5, 6, 7]

Array.map: preserve the shape, transform the values

let nums = [1, 2, 3]
let squares = nums.map { $0 * $0 }     // [1, 4, 9]

// Identity
assert(nums.map({ $0 }) == nums)

// Composition law
let h: (Int) -> Int = { $0 - 1 }
let k: (Int) -> Int = { $0 * 10 }
assert(nums.map(h).map(k) == nums.map(compose(k, h)))

Result: map successful values and use mapError for failures

enum MyError: Error { case boom }

let ok: Result<Int, MyError> = .success(3)
let asString = ok.map { "\($0)" }                      // .success("3")

let bad: Result<Int, MyError> = .failure(.boom)
let stillBad = bad.map { $0 * 10 }                     // Failure is preserved: .failure(.boom)

// An alternative: provide bimap to transform both successes and errors
extension Result {
    func bimap<U, E2>(
        success: (Success) -> U,
        failure: (Failure) -> E2
    ) -> Result<U, E2> {
        self.map(success).mapError(failure)
    }
}

let prettyError: Result<String, String> =
    bad.bimap(success: { "\($0)" }, failure: { _ in "!!!" })  // .failure("!!!")

Conceptually, Result is a bifunctor: its success and failure channels can be mapped independently. The Swift standard library provides map for success and mapError for failure. We combine them in bimap, bringing the interface closer to the categorical formulation.

2.2.2 F#: Idiomatic Composition with Option, List, and Result

F# provides its family of map functions in modules such as Option, List, and Result. Together with the |> pipe and >> combinator, they produce distinctly algebraic pipelines.

let input = [ -2; -1; 0; 1; 2; 3 ]

// List: map + filter + sum
let sumPosTimes2 =
    input
    |> List.map ((*) 2)
    |> List.filter ((<) 0)
    |> List.sum
// == 12

// More efficient fusion: avoid an intermediate list
let sumPosTimes2' =
    input
    |> List.filter ((<) 0)
    |> List.sumBy (fun x -> x * 2)

// Option: map Some and retain None
let optX = Some 10
let mapped = optX |> Option.map (fun x -> x + 5)   // Some 15
let nothing: int option = None
let stillNone = nothing |> Option.map ((*) 2)      // None

// Result: map successes and use mapError for failures
let ok : Result<int, string> = Ok 3
let ok' = ok |> Result.map string                  // Ok "3"

let bad : Result<int, string> = Error "E"
let bad' = bad |> Result.map ((*) 10)              // Still Error "E"
let badPretty = bad |> Result.mapError (fun e -> $"ERR:{e}") // Error "ERR:E"

// Composition law (using List as an example)
let f x = x + 1
let g x = x * 2
let left  = input |> List.map g |> List.map f
let right = input |> List.map (f << g)
assert (left = right)

// Combinator: compose “multiply by 2” and “add 3” into one transformation
let transform = ((*) 2) >> ((+) 3)
let demo = input |> List.map transform

2.2.3 The C# Analogy: Select as a Functor Map

C# seldom uses the term “functor,” but Select on IEnumerable<T> and the Select provided for Nullable<T> by some libraries both exemplify map: preserve the structure and map only the values within it.

var nums = new[] { 1, 2, 3 };
var squares = nums.Select(x => x * x);      // IEnumerable<int>: shape preserved

int? n = 2;
var s = n.Select(x => x * 3);               // Available in some extension packages; none stays none

2.2.4 Summary: Embedding Transformations in a Context

These practices consistently lift “value → value” to “value in context → value in context,” providing a foundation for declarative chaining.

2.3 Applicative: Parallelism and Aggregation for Independent Effects

Functor transforms values, and Monad handles dependent sequencing. An applicative functor lies between them. When steps are independent and their results only need to be combined, possibly in parallel, Applicative is the natural choice.

2.3.1 The Minimal Contract and Mental Model

Minimal contract (types)

pure:a→Fa⟨*⟩:F(a→b)→Fa→Fbpure:a \rightarrow F\, a\quad\quad\langle*\rangle:\ F(a \rightarrow b)\ \rightarrow \ F\, a\ \rightarrow \ F\, b

Common equivalent forms:

liftA2:(a→b→c)→Fa→Fb→FcliftA2:\ (a \rightarrow b \rightarrow c)\ \rightarrow \ F\, a\ \rightarrow \ F\, b\ \rightarrow \ F\, c

The derivation relationships are:

fmapf≡puref⟨*⟩,mapN generalizes liftA2, liftA3, and so on.fmap\ f \equiv pure\ f\ \langle*\rangle,\quad\quad\text{mapN generalizes liftA2, liftA3, and so on.}

Relationship to Monad. An Applicative can be derived from a Monad:

u⟨*⟩v=u≫=(λf.v≫=(λx.return(f,x)))u\langle*\rangle v\mspace{6mu} = \mspace{6mu} u \gg = \ (\lambda f.\ v \gg = \ (\lambda x.\ return\,(f,x)))

The converse does not hold: Applicative is weaker than Monad. It cannot express branching control that depends on a previous result. In return, it offers compositions that can be parallelized or reordered.

2.3.2 The Four Applicative Laws, with Assertion Templates

  1. Identity

    pureid⟨*⟩v≡vpure\ id\langle*\rangle v \equiv v

  2. Composition

    pure(.)⟨*⟩u⟨*⟩v⟨*⟩w≡u⟨*⟩(v⟨*⟩w)pure\ (.)\langle*\rangle u\langle*\rangle v\langle*\rangle w \equiv u\langle*\rangle(v\langle*\rangle w)

  3. Homomorphism

    puref⟨*⟩purex≡pure(f,x)pure\ f\langle*\rangle pure\ x \equiv pure\ (f,x)

  4. Interchange

    u⟨*⟩purey≡pure($y)⟨*⟩uu\langle*\rangle pure\ y \equiv pure\ (\$\, y)\langle*\rangle u

Example assertions in Swift (Optional)

// An implementation of apply for Optional
infix operator <*> : AdditionPrecedence
func <*><A,B>(f: ((A)->B)?, x: A?) -> B? { f.flatMap { g in x.map(g) } }
func pure<A>(_ x: A) -> A? { .some(x) }

let v: Int? = 3
let u: ((Int)->Int)? = { $0 + 1 }

// Identity
assert((pure({ $0 }) <*> v) == v)
// Homomorphism
assert((pure({ $0 + 1 }) <*> pure(3)) == pure(4))

Example assertions in F# (Option)

let inline (<*>) (ff: ('a->'b) option) (fa: 'a option) =
    Option.bind (fun f -> fa |> Option.map f) ff
let pure x = Some x

let v = Some 3
let u = Some ((+) 1)

// Identity
assert (pure id <*> v = v)
// Homomorphism
assert (pure ((+) 1) <*> pure 3 = pure 4)

2.3.3 When to Prefer Applicative: Engineering Trade-offs

2.3.4 Cross-Language Reference: Combining Independent Steps

Swift(zip / map2)

enum E: Error { case bad }

func map2<A,B,C>(_ ra: Result<A,E>, _ rb: Result<B,E>, _ f: (A,B)->C) -> Result<C,E> {
  ra.flatMap { a in rb.map { b in f(a,b) } }
}
func zip<A,B>(_ ra: Result<A,E>, _ rb: Result<B,E>) -> Result<(A,B),E> {
  map2(ra, rb, { ($0,$1) })
}

let a = Result<Int,E>.success(2)
let b = Result<Int,E>.success(3)
let s = zip(a,b).map(+)// .success(5): aggregate two independent steps

F# (custom map2 for Option/Result)

let map2 f oa ob = Option.bind (fun a -> Option.map (fun b -> f a b) ob) oa
let r = map2 (+) (Some 2) (Some 3)  // Some 5
Scala (Cats)
import cats.implicits._
val r = (Option(2), Option(3)).mapN(_ + _)         // Some(5)

// Error accumulation: Validated (Applicative semantics)
import cats.data.ValidatedNel
def checkName(n: String): ValidatedNel[String, String] = if (n.nonEmpty) n.validNel else "name".invalidNel
def checkAge(a: Int): ValidatedNel[String, Int] = if (a > 0) a.validNel else "age".invalidNel
case class User(n:String, a:Int)
val u = (checkName(""), checkAge(-1)).mapN(User.apply) // Invalid(NonEmptyList(name, age))

Kotlin(Arrow)

import arrow.core.*
data class User(val n:String, val a:Int)
val nameV: ValidatedNel<String,String> = "".invalidNel()
val ageV : ValidatedNel<String,Int>   = (-1).invalidNel()
val user : ValidatedNel<String,User>  = Validated.mapN(nameV, ageV) { n, a -> User(n,a) }
Rust
let a: Option<i32> = Some(2);
let b: Option<i32> = Some(3);
let r = a.zip(b).map(|(x,y)| x + y); // Some(5)

let ax: Result<i32,&'static str> = Ok(2);
let bx: Result<i32,&'static str> = Ok(3);
let rz = ax.zip(bx).map(|(x,y)| x + y); // Ok(5): aggregate independent results

traverse/sequence: exchanging the order of container and effect

An Applicative naturally gathers many small effects into a single organized result.

Swift (Result version)

enum Perr: Error { case bad }
func parseInt(_ s: String) -> Result<Int, Perr> {
  Int(s).map(Result.success) ?? .failure(.bad)
}

func traverse<A,B>(_ xs: [A], _ f: (A)->Result<B,Perr>) -> Result<[B],Perr> {
  xs.reduce(.success([])) { acc, x in
    acc.flatMap { bs in f(x).map { b in bs + [b] } }
  }
}

let ok  = traverse([“1”,”2”,”3”], parseInt)   // .success([1,2,3])
let bad = traverse([“1”,”x”,”3”], parseInt)   // .failure(.bad)

sequence is the special case traverse(id), turning T<G<A>> into G<T<A>>.

2.3.5 Parallelizable Applicatives: Engineering Notes

The rule of thumb: prefer Applicative when no step depends on an earlier one. The resulting composition can be parallelized, reordered, and tested easily.

2.3.6 Summary and Comparison

2.4 The Minimal Contract for a Monad

A functor tells us how to map in a context. A monad tells us how to sequence computations in a context. Possibilities such as failure or absence and requirements such as carrying state are handled behind the composition, allowing us to lay out the calculations in a single sequence.

Minimal contract (types only)

unit:A→M⟨A⟩,\text{unit}:A \rightarrow M\left\langle A \right\rangle,\quad\quad

bind:M⟨A⟩→(A→M⟨B⟩)→M⟨B⟩\text{bind}:M\langle A\rangle \rightarrow (A \rightarrow M\langle B\rangle) \rightarrow M\langle B\rangle

In familiar types, this becomes:

2.4.1 Optional as a Monad in Swift: A Concise Semantic Match

// Try to convert the string to Int; return nil on failure
func parseInt(_ s: String) -> Int? { Int(s) }

let a: String? = “42”
let b: String? = nil

let r1: Int? = a.flatMap(parseInt)   // .some(42)
let r2: Int? = b.flatMap(parseInt)   // nil: short-circuits without calling parseInt

// Test the laws: left identity, right identity, and associativity (direct assertions)
func pure<T>(_ x: T) -> T? { .some(x) }
func bind<T,U>(_ m: T?, _ f: (T) -> U?) -> U? { m.flatMap(f) }

let f: (Int) -> Int? = { .some($0 + 1) }
let g: (Int) -> Int? = { .some($0 * 2) }

let x = 5
assert(bind(pure(x), f) == f(x))                     // Left identity
assert(bind(.some(x), pure) == .some(x))             // Right identity
assert(bind(bind(.some(x), f), g)                    // Associativity
     == bind(.some(x), { y in bind(f(y), g) })

Continue when a value exists, stop when it does not. Roughly, flatMap takes the A in A?, passes it to A -> B?, and produces B?.

2.4.2 Result as a Monad in Swift: Errors as a Channel

enum E: Error { case boom, oob }

func step1(_ x: Int) -> Result<String, E> {
    x > 0 ? .success(“n=\(x)”) : .failure(.oob)
}

func step2(_ s: String) -> Result<Double, E> {
    Double(s.dropFirst(2)).map(Result.success) ?? .failure(.boom)
}

let ok = Result<Int, E>.success(5)
let got: Result<Double, E> = ok
    .flatMap(step1)          // Success value "n=5"
    .flatMap(step2)          // -> .success(5.0)

// Short-circuit on failure: after any .failure, later steps do not run
let bad = Result<Int, E>.success(0).flatMap(step1).flatMap(step2)

// Modern idiom: bimap transforms successes and errors (bifunctor-like semantics)
extension Result {
    func bimap<U, E2>(success: (Success) -> U, failure: (Failure) -> E2) -> Result<U, E2> {
        self.map(success).mapError(failure)
    }
}

Compare throws/try: Result makes errors explicit data, which is convenient for functional chaining. In this analogy, throws acts as language-level do notation, with bind expressed through try and unit through implicit return.

2.4.3 F#: Sequential Composition of Option, Result, and List

// Option: continue if a value exists; stop at None
let parseInt (s:string) : int option =
    match System.Int32.TryParse s with
    | true, v -> Some v
    | _       -> None

let ratio sa sb : int option =
    parseInt sa
    |> Option.bind (fun a ->
       parseInt sb
       |> Option.bind (fun b ->
           if b = 0 then None else Some (a / b)))

// List: collect is flatMap
let input = [1;2;3]
let products =
    input
    |> List.collect (fun x -> [x; x*10])   // Compose and flatten
// [1;10;2;20;3;30]

// Result: Result.bind chains the success channel
let step1 x = if x>0 then Ok $"n={x}" else Error "oob"
let step2 (s:string) =
    match System.Double.TryParse (s.Substring 2) with
    | true, v -> Ok v
    | _ -> Error "boom"

let flow =
    Ok 5 |> Result.bind step1 |> Result.bind step2   // Ok 5.0

// A modern DSL-style version (illustrative computation expression)
type ResultBuilder() =
  member _.Bind(m,f) = Result.bind f m
  member _.Return x  = Ok x
let result = ResultBuilder()

let flowCE =
  result {
    let! s = step1 5
    let! d = step2 s
    return d
  }

F# programs often use task { let! ... } for asynchronous work. Here let! is syntactic sugar for bind.

2.4.4 Kotlin (Arrow) and Scala (for-Comprehensions)

Kotlin with Arrow (the readable, modern either DSL)

import arrow.core.raise.either
import arrow.core.raise.ensure

fun parseInt(s: String) = s.toIntOrNull()?.right() ?: "boom".left()

val result = either {
  val a = parseInt("42").bind()
  ensure(a > 0) { "oob" }
  a * 2
}
// Right(84)

Scala (a for-comprehension is equivalent to nested flatMap)

val res: Option[Int] = for {
  a <- Option(10)
  b <- Option(2)
  r <- if (b == 0) None else Some(a / b)
} yield r

2.4.5 Why These Equations Matter: The Monad Laws

The laws let us refactor chains freely. We can merge several flatMap operations or split one apart without changing the result. This is the mathematical basis for hiding control flow behind composition.

In Haskell notation (>>=)

A monad is simply a stable, refactorable protocol for connecting contexts. With unit, bind, and the three laws, we can write computations involving errors, absent values, asynchronous work, environments, or state in a uniform, composable style.

2.5 Natural Transformations in Programming Languages

2.5.1 What Is a Natural Transformation in Category Theory?

A natural transformation between two functors F,G:𝒞→𝒟F,G:\mathcal{C \rightarrow D} is specified object by object. For every object XX it supplies a morphism ηX:FX→GX\eta_{X}:FX \rightarrow GX, subject to naturality: for every f:X→Yf:X \rightarrow Y,

Gf∘ηX=ηY∘Ff.Gf \circ \eta_{X}\; = \;\eta_{Y} \circ Ff.

Intuitively, whether we first apply ff inside FF and then move across, or first move to GG and then apply ff, the result is the same. The transformation is compatible with the structure.

2.5.2 In Programming: Functors on Parameterized Types

In languages with parametric polymorphism (F#, Swift, Kotlin, Scala, and Haskell), a natural transformation corresponds to a polymorphic function defined for every type AA:

∀A.F<A>→G<A>\forall A.\;F < A > \rightarrow G < A >

It is compatible with map:

nt (F.map f x) = G.map f (nt x).

The function performs only a structural transfer, without inspecting values of AA. In programming terms, it moves the contents of a container naturally from FF to GG.

2.5.3 An Engineering Definition

2.5.4 Why It Matters

2.5.5 Miniature Example 1: From Option to List

let optionToList (oa: option<'a>) : list<'a> =
  match oa with Some x -> [x] | None -> []

The function works for any 'a and satisfies naturality:

optionToList (Option.map f oa) == List.map f (optionToList oa)

2.5.6 Miniature Example 2: From Swift Result to Optional, Discarding Error Information

func resultToOptional<A, E>(_ r: Result<A,E>) -> A? {
    switch r { case .success(let a): return a; case .failure: return nil }
}

Again, the signature holds for all A. Swift generics and the definition of map give the naturality property.

2.5.7 Natural Transformations and Functors

2.6 Kleisli Categories in Programming Languages

2.6.1 The Kleisli Category

Given a monad MM on a category CC:

The Kleisli and Eilenberg–Moore categories complement one another. For every monad, they give the two extremal solutions among the adjunctions inducing it: Kleisli on the free-algebra side and Eilenberg–Moore on the algebra or model side, where the objects are TT-algebras (Eilenberg & Moore, 1965; Mac Lane, 1998).

2.6.2 How This Appears in Languages and APIs

The central idea is to take functions that return values in an effectful context, A→M BA \rightarrow M\text{ }B, treat them as first-class objects, and connect them by Kleisli composition. Here is how that looks in different languages:

Haskell

Scala

JavaScript

C# / LINQ

Rust

Swift

In short, Kleisli composition treats monad-returning functions as composable arrows. We use it almost daily under names such as flatMap, bind, and_then, SelectMany, and then. For application developers, Kleisli composition explains why these different APIs fit one pattern.

2.7 Composition Laws: Pure Functions and Effects

Pure functions

In functional semantics, a function f:A→Bf:A \rightarrow B is pure exactly when the following hold:

  1. Its result depends only on its arguments, and it has no observable side effects. It neither reads nor writes external state nor depends on time, I/O, or randomness. This idea goes back to Backus’s algebra of programs and framework for equational reasoning (Backus, 1978).

  2. Denotational semantics. There is a deterministic semantic mapping ⟦f⟧:A→B⟦f⟧:A \rightarrow B, and for every xx the result of evaluation satisfies eval(f x)=⟦f⟧(x)\text{eval}(f\text{ }x) = ⟦f⟧(x).

  3. Referential transparency (the substitution principle). If e1=e2e_{1} = e_{2}, then C[e1]≡C[e2]C\lbrack e_{1}\rbrack \equiv C\lbrack e_{2}\rbrack in every context C[⋅]C\lbrack \cdot \rbrack. This is the standard account in texts on types and semantics (Marlow, 2010b; Pierce, 2002).

  4. In a Cartesian closed category (CCC), we can characterize this through exponential objects and the evaluation morphism ev:BA×A→Bev:B^{A} \times A \rightarrow B, satisfying the β and η equations (Hutton, 2016).

The intuition is that purity permits equational reasoning (Hughes, 1989).

2.7.1 Composition Laws for Pure Functions

With these laws, what we can read, we can rewrite and optimize.

2.7.2 What Can Impurity Break?

When a library or a piece of code hides side effects (printing, randomness, exceptions, or mutable state), the following problems arise:

Once referential transparency is lost, equational rewrites lose their justification.

2.7.3 Semantic Anomalies Introduced by Floating Point

From a functional perspective, IEEE 754 floating-point arithmetic uses finite precision and rounding. Many identities from pure mathematics no longer support unrestricted equational rewrites, including those involving associativity, commutativity, and distributivity. Floating-point operations may also involve hidden state such as the rounding mode or exception flags. It is more precise to say that floating point introduces a numeric or algebraic effect that should be modeled distinctly from I/O effects.

2.7.4 A Remedy: Put Effects in Types and Compose Under the Appropriate Laws

Make effects such as failure, asynchrony, state, or logging explicit in a container M:

Kleisli (monadic) chains

Applicative aggregation

Functor / Traversable / Alternative:

The conclusion is that the equations survive: we move from equations for pure functions to equations for effect containers. With the appropriate container and combinators, rewrites and optimizations can still be performed safely.

2.7.5 A Minimal Comparison in F#

Pure (fusion applies)

let f x = x + 1
let g x = x * 2
List.map f (List.map g xs) = List.map (f << g) xs

Impure (the equation breaks)

let mutable cnt = 0
let f x = cnt <- cnt + 1; x + cnt  // Two maps and one fused map distribute effects differently

Explicit effects (lawful composition)

let parseInt (s:string) : Result<int,string> = ...
let recip (n:int) : Result<float,string> = ...
let (>=>) f g x = Result.bind g (f x)     // Kleisli composition
let h : string -> Result<float,string> = parseInt >=> recip  // Obeys the three monad laws

In short, pure functions provide referential transparency and equational reasoning. Real-world side effects should be lifted into typed effects so that they can still compose safely under the laws of Applicative, Monad, Kleisli, and Traversable, as well as Alternative.

2.8 JAX: An Industrial-Scale Pure Functional Paradigm

JAX (JAX Team, 2025) is a Python library for accelerator-oriented array computation and program transformation. It provides a NumPy-style API and makes just-in-time compilation (JIT), automatic differentiation, vectorization, and parallelization composable function transformations. Its compiler, XLA, targets CPUs, GPUs, and TPUs.

Important aspects of programming style

JAX shows how pure functional programming can work at industrial scale. Build on immutable arrays and explicit state, express training and inference as composable functions, and apply grad / jit / vmap / pmap for automatic differentiation, compilation, and parallel optimization while preserving semantics. Keep side effects at controlled boundaries.

2.9 Chapter Recap: From Mapping to Sequencing, from Laws to Practice

2.9.1 Three Key Takeaways

  1. Coherence from categories to types to code. Functor unifies value transformations, Applicative the parallel execution or aggregation of independent effects, and Monad the sequencing of dependent effects. The same structure connects the mathematics to the types and then to readable code.

  2. Laws safeguard refactoring. map obeys identity and composition, and pure/ap and flatMap have corresponding unit and associativity laws. We can merge operations or split one into several without changing the chain’s semantics.

  3. A practical selection guide

    • To transform values without flattening, use map.

    • To combine independent steps, use ap / liftA2 / mapN / zipWith (Applicative).

    • For dependent steps or short-circuiting, use flatMap / bind (Monad).

Table 2-1. Common combinator signatures (abridged)

Concept Core type (Haskell style) Meaning at a glance
identity id :: a -> a Leave the value unchanged
composition (.) :: (b->c) -> (a->b) -> a->c Compose functions
map / fmap fmap :: (a->b) -> F a -> F b Transform values, preserve shape
bimap bimap :: (a->b) -> (c->d) -> F a c -> F b d Transform both channels
pure / return pure :: a -> F a Place a value in a context
ap <*> :: F (a->b) -> F a -> F b Applicative application (combine independent effects)
liftA2 / map2 liftA2 :: (a->b->c) -> F a -> F b -> F c Combine multiple independent arguments
flatMap / bind (>>=) :: F a -> (a->F b) -> F b Dependent sequencing or short-circuiting
join join :: F (F a) -> F a Flatten one layer of context
traverse traverse :: (a->G b) -> T a -> G (T b) Exchange container and effect, with a mapping
sequence sequence :: T (G a) -> G (T a) Collect a batch of effects
fold / reduce foldl :: (b->a->b) -> b -> T a -> b Reduce a structure
unfold unfoldr :: (b->Maybe (a,b)) -> b -> [a] Generate a structure by unfolding a seed
guard / filterM guard :: Bool -> F () / filterM :: (a->F Bool) -> [a] -> F [a] Conditional entry or effectful filtering

2.9.2 Combinators by Language

Swift

F#

Scala (Cats ecosystem)

Kotlin(Arrow)

Haskell

C# (analogous operations)

Rust


  1. GHC (the Glasgow Haskell Compiler) is the most widely used Haskell implementation. It includes a batch compiler and an interactive REPL (GHCi), with full support for Haskell 2010 and numerous built-in extensions. Its runtime system (RTS) provides lightweight threads, concurrency, parallelism, and software transactional memory (STM). The compiler desugars the source program into a typed Core language based on System FC. It then passes through STG/C-- to generate executable code using a native or LLVM backend. The ApplicativeDo extension automatically lowers independent steps in a do block to Applicative compositions, exposing opportunities for parallelism and optimization. For practical details, see the chapters on GHCi and language extensions in the GHC User’s Guide.↩︎

CHAPTER 3

ADT Variants: The Sum-of-Products Paradigm

This chapter comes down to three ideas: variants (ADTs), matching, and composition. First, we encode all mutually exclusive forms and coexisting fields of a domain precisely in its types, using sums, products, unit, and the empty type in a sum-of-products representation. Next we use algebraic pattern matching (APM) to handle the branches exhaustively. Finally, combinators such as Functor, Applicative, and Monad connect steps into verifiable pipelines. Mainstream languages support this directly. Swift enums support associated values, and a switch must cover every possible input. Kotlin’s sealed hierarchies enable compile-time exhaustiveness checks for when. F# makes selection and destructuring routine through discriminated unions (DUs) and pattern matching. Rust places variants and matching at the heart of the language with enum, match, and a rich pattern syntax.

Why emphasize the word “algebraic”? We are concerned with matching that works hand in hand with ADTs. The type system and the universal property of a sum (coproduct) connect two questions: Which branch of the sum contains the value? And how do we decompose the product in that branch? This lets the compiler check coverage and bindings and flag changes as the type evolves. The operation goes deeper than matching surface features of a string or syntax tree. Hence our specific term algebraic pattern matching.

Recursion is a natural setting for APM. With recursive expressions, syntax trees, state machines, and related structures, APM suggests a simple idiom: each rule is a branch and traversal is a fold. Write the local rule in its branch and leave walking and combining the tree to a general traversal. Section 3.3 gives a minimal example of recursion in APM and refactors handwritten recursion into composable fold/traverse operations.

ADTs and OOP complement one another. We use an architecture with a protocol-first or interface-driven outer layer and an ADT-based core. The outer layer handles mutable side effects through protocols and interfaces. The core expresses provably exhaustive domain logic with ADTs and algebraic pattern matching. Computations compose through Functor, Applicative, and Monad. This approach follows the engineering principle of favoring composition over inheritance: expose behavior through interfaces and composition, and use ADTs to encapsulate the set of possibilities. An open boundary can coexist with stronger type guarantees and testability. Swift’s protocol-oriented style and exhaustive enum matching naturally support this design.

What this chapter covers

Reading guide

If your background is in OOP, first look at the design benefits of making invalid states unrepresentable and matching exhaustively: fewer scattered if/else branches, nulls, and type checks. If functional abstractions are familiar, focus on how recursion in APM and the encapsulation of side effects behind OOP ports work together in an implementation.

3.1 Algebraic Structures: Sums, Products, Unit, and Empty, with Categorical Diagrams and Minimal Code

3.1.1 Main Ideas

A sum type with two variants: a product with two fields and the unit value.

Figure 3-1. Construction tree of an ADT. The Sum Type node has two variant branches. Variant1 contains a Product subtree with two fields, FieldA and FieldB. Variant2 carries no data beyond the unit value ().

The diagram illustrates the sum–product–unit structure of an ADT:

  1. The root is the sum type of the ADT

    • A value of this type is either Variant1 or Variant2.

    • The branches are mutually exclusive. In set-theoretic terms, they form a disjoint union.

  2. The left branch, Variant1, contains a product-type subtree

    • A value of Variant1 carries both fields, FieldA: TypeA and FieldB: TypeB.

    • This is an and relationship, as in a struct or record. The cardinalities satisfy

      |Variant1|=|TypeA|×|TypeB|.|Variant1| = |TypeA| \times |TypeB|.

  3. The right branch, Variant2, is the unit type (Unit, ())

    • This branch carries no data (a nullary constructor), with cardinality

      |Variant2|=1.|Variant2| = 1.

  4. The overall sum-of-products cardinality

    |ADT|=|Variant1|+|Variant2|=|TypeA|×|TypeB|+1.|ADT| = |Variant1| + |Variant2| = |TypeA| \times |TypeB| + 1.

    This is the classic form ADT = sum of products.

  5. Corresponding code examples

    Swift

    enum T {
      case variant1(fieldA: TypeA, fieldB: TypeB) // Product
      case variant2                               // Unit
    }

    F#

    type T =
      | Variant1 of TypeA * TypeB   // Product
      | Variant2                    // Unit

    Rust

    enum T {
      Variant1 { field_a: TypeA, field_b: TypeB },
      Variant2,
    }

Engineering implications of the diagram

The diagram shows how a sum supplies the outer shell, a product supplies the inner fields, and unit supplies a nullary branch. This sum–product–unit construction encodes alternatives (sums) and coexistence (products) more directly than a base class and subclasses, and naturally supports exhaustive matching and verification.

An intuition for cardinality

|ADT|=|Variant1|+|Variant2|=|TypeA|×|TypeB|+1,|Unit|=1,;|Empty|=0.|ADT| = |Variant1| + |Variant2| = |TypeA| \times |TypeB| + 1,\quad|Unit| = 1,;|Empty| = 0.

Engineering significance. Invalid states cannot be constructed, for example by supplying FieldA without FieldB. Adding a variant gives a compile-time reminder at every affected switch or match.

3.1.2 Categorical Diagrams: Products, Sums, Limits, and Colimits

What are these diagrams good for? They make precise the idea that a data construction is characterized by a universal property. We can use an interface diagram to synthesize types or constraints automatically.

Universal property of the product, with projections and the unique pairing map.

Figure 3-2. Universal property (limit) of the product A×BA \times B

Any pair of arrows f,gf,g into A,BA,B factors uniquely through ⟨f,g⟩:X→A×B\langle f,g\rangle:X \rightarrow A \times B. Thus A×BA \times B is characterized by the projections π1,π2\pi_{1},\pi_{2} and unique factorization. For a programmer, this is the universal property of a record or tuple.

Universal property of the coproduct, with injections and the unique copairing map.

Figure 3-3. The sum A+BA + B as a colimit (coproduct)

Given f:A→Y,g:B→Yf:A \rightarrow Y,g:B \rightarrow Y, there is a unique [f,g]:A+B→Y\lbrack f,g\rbrack:A + B \rightarrow Y that makes the triangles commute. This is the universal property of variants or enums: pattern matching supplies one branch for each injection.

Pullback square of a pair of maps with common codomain C. Pushout square of a pair of maps with common domain A.

Figure 3-4. An advanced glimpse: pullbacks and pushouts

When to use them. A pullback or pushout can express the domain more closely than an ordinary product or sum when the data must satisfy an alignment constraint or be merged by identification.

Table 3-1. ADT constructions and their categorical counterparts

Construction Programming intuition Typical syntax Universal property
Product A×BA \times B Record/tuple struct {a:A; b:B} Limit with projections π1,π2\pi_{1},\pi_{2}
Sum A+BA + B Variant/enum enum { inl A | inr B } Colimit with injections ι1,ι2\iota_{1},\iota_{2}
Unit 11 ( ) Unit/unit Terminal object
Empty 00 Uninhabited Never/Void Initial object
Pullback Constrained product Join condition (equality) Limit (fiber product)
Pushout Gluing or merging Identification construction Colimit (amalgamation)

Sums, products, unit, and empty in practice: eliminating invalid states

Swift example. Represent a loading state with an enum instead of keeping an optional, a Boolean, and a string as parallel flags.

enum Load<T> {
  case idle
  case loading
  case ok(T)              // Product: carry the result on success
  case failed(String)     // Product: carry the error on failure
}

// Use an exhaustive match: the compiler requires every state to be covered
func render(_ s: Load<Data>) {
  switch s {
  case .idle:        print("idle")
  case .loading:     print("loading")
  case let .ok(x):   print("size:", x.count)
  case let .failed(msg): print("error:", msg)
  }
}

Summary

3.2 Algebraic Pattern Matching

Why the specific term algebraic pattern matching? We mean matching against an ADT (sum/product/unit/empty), governed by the type system and exhaustiveness checking. Regular-expression matching, syntax-tree traversal, and reflective type inspection are different operations. Algebraic matching turns alternatives (Sum) and coexisting fields (Product) into branch coverage and destructuring that can be checked at compile time.

  1. Core questions at a glance

    • Which branch contains the value? (Sum → algebraic pattern selection)

    • How do we decompose the fields in that branch? (Product → algebraic pattern destructuring)

    • Can the compiler prove that I have covered every branch? (Exhaustiveness)

      • A Swift switch must be exhaustive. For a nonfrozen enum supplied by a library, @unknown default allows for future cases.

      • Kotlin checks exhaustiveness for a when over a sealed hierarchy without an else branch.

      • The match constructs of F#, Scala, and Rust naturally support exhaustiveness and destructuring for DUs, case classes, and enums, respectively.

      • C# also has property and type patterns. Without ADTs or closed hierarchies, exhaustive coverage depends on the design and is not always guaranteed by the compiler.

  2. A categorical view of algebraic pattern matching

    Pattern matching supplies a handling arrow for each injection of a sum (see the sum/coproduct diagram in Section 3.1). Given f:A→Y,g:B→Yf:A \rightarrow Y,g:B \rightarrow Y, there is a unique [f,g]:A+B→Y\lbrack f,g\rbrack:A + B \rightarrow Y.

    • In code, for enum { Inl(A) | Inr(B) }, give match the branches Inl(a) -> ... and Inr(b) -> .... The compiler thereby constructs a unique total function. This is the programming counterpart of the universal property, a colimit, behind algebraic pattern matching.

  3. A minimal cross-language overview

3.2.1 Swift (enum, Exhaustive Matching, and @unknown default)

enum Load<T> { case idle, loading, ok(T), failed(String) }

func render(_ s: Load<Data>) {
  switch s {
  case .idle: print("idle")
  case .loading: print("loading")
  case let .ok(x): print(x.count)
  case let .failed(msg): print(msg)
  @unknown default: print("future case") // Safer for system enums or nonfrozen enums
  }
}

Swift requires an exhaustive switch. With @unknown default, the compiler gives a warning when a new case is added later, helping you catch omissions. Both the official language guide and community practice emphasize this.

3.2.2 F# (DUs, match, and Optional Active Patterns)

type Load<’T> = | Idle | Loading | Ok of ‘T | Failed of string
let render = function
  | Idle -> printfn “idle”
  | Loading -> printfn “loading”
  | Ok x -> printfn “%d” x.Length
  | Failed msg -> printfn “%s” msg

For more flexible partitioning or destructuring, active patterns let us define custom views that can be matched.

3.2.3 Kotlin (sealed and when Without else)

sealed interface Load<out T>
data class Ok<T>(val v: T) : Load<T>
data class Failed(val msg: String) : Load<Nothing>
object Idle : Load<Nothing>; object Loading : Load<Nothing>

fun render(s: Load<ByteArray>) = when (s) {
  is Idle -> println("idle")
  is Loading -> println("loading")
  is Ok -> println(s.v.size)
  is Failed -> println(s.msg)
  // No else: the sealed hierarchy enables exhaustiveness checking
}

A sealed hierarchy makes all subclasses known at compile time, enabling exhaustiveness checks for when.

3.2.4 Rust(enum + match + or-pattern)

enum Load<T> { Idle, Loading, Ok(T), Failed(String) }

fn render(s: Load<Vec<u8>>) {
  match s {
    Load::Idle | Load::Loading => println!("pending"),   // or-pattern (1.53+)
    Load::Ok(x) => println!("{}", x.len()),
    Load::Failed(msg) => println!("{}", msg),
  }
}

Rust checks match exhaustiveness on enums. Or-patterns, stable since Rust 1.53, can make the code more concise.

3.2.5 Scala(case class + match/Extractor)

sealed trait Load[+T]
final case class Ok[T](v: T) extends Load[T]
final case class Failed(msg: String) extends Load[Nothing]
case object Idle extends Load[Nothing]; case object Loading extends Load[Nothing]

def render(s: Load[Array[Byte]]): Unit = s match {
  case Idle | Loading => println("pending")
  case Ok(v)          => println(v.length)
  case Failed(msg)    => println(msg)
}

Scala’s pattern matching works especially well with case classes and extractors (unapply).

3.2.6 C# (Property and Type Patterns Outside an ADT Setting)

static string Render(object s) => s switch
{
    { } when s is Idle or Loading      => “pending”,
    Ok(var v)                          => v.Length.ToString(),
    Failed(var msg)                    => msg,
    _                                  => “unknown”
};

C# provides property, type, and relational patterns. Without closed ADTs and strong exhaustiveness checking, implementations rely more on API conventions and tests.

3.2.7 Best Practices

  1. Prefer exhaustive matching on ADTs. Avoid masking an omitted case with a catch-all default or _.

  2. Swift: use @unknown default for nonfrozen system or third-party enums. Prefer explicit exhaustive matching for your own enums.

  3. Kotlin: use when without else for sealed hierarchies.

  4. Minimize partial functions. If branches should be enumerated, do not hide them in if or guard. Let the compiler audit coverage.

  5. Use combined patterns. Or-patterns (Rust 1.53+) group equivalent branches. Scala supports alternative cases, and Swift can combine cases with case .a, .b:.

  6. Destructure products explicitly. Express meaning through field and binding names and avoid magic indices. F# named-field patterns can improve readability.

  7. Extend the available views. F# active patterns and Scala extractors allow algebraic matching even on external types whose structure cannot be changed.

  8. Design for change. Public APIs may add enum cases. Common strategies include Swift’s @unknown default and Kotlin sealed hierarchies with module boundaries.

3.2.8 Reference: Elements of Algebraic Patterns

Table 3-2. Elements of algebraic patterns

Concept Purpose Language examples
Branch selection (sum) Identify the variant containing a value switch/when/match
Field destructuring (product) Bind the fields carried by a branch case .ok(let x) / Ok(x)
Guard or guard clause Add a predicate to a branch case .ok(let x) where x.count>0 / when (x>0)
Or-pattern Combine equivalent branches Idle | Loading(Scala/Rust)
Fallback strategy Accommodate future enum changes Swift @unknown default

In summary, algebraic pattern matching translates the sums and products of an ADT directly into selection and destructuring. The compiler checks coverage and the correctness of bindings. This supplies operational semantics in code for the sums, products, and unit of Section 3.1. It also underlies Section 3.4 on combining ADTs and OOP and subsequent discussions of errors, commands, and state machines.

3.3 Recursion in Algebraic Pattern Matching (APM)

Structural recursion amounts to algebraic pattern matching on an ADT. Abstract recursive calls into a homomorphism over data constructors (a fold): supply a handling arrow for each alternative of a sum, destructure products, and use unit and empty for boundary cases. The compiler can check exhaustiveness, and the structure gives a basis for termination. This is the programming counterpart of the catamorphism (fold) of recursive or initial-algebra semantics (HaskellWiki Contributors, 2025).

3.3.1 Combining Structural Recursion with APM

3.3.2 A Categorical View: Recursion as a Fold (Catamorphism)

The initial-algebra diagram. If (μF,𝗂𝗇)(\mu F,\mathsf{in}) is the initial algebra of the endofunctor FF, then for every FF-algebra (A,α)(A,\alpha) there is a unique homomorphism 𝖼𝖺𝗍𝖺α:μF→A\mathsf{cata}_{\alpha}:\mu F \rightarrow A making the diagram commute:

Commutative diagram for a catamorphism from an initial algebra.

Figure 3-5. Categorical diagram of an initial algebra

Programming intuition. Supply a handler for each constructor, α\alpha, and the system derives a single traversal (a fold). This gives handwritten recursion an algebraic formulation.

3.3.3 Minimal Implementations: Structural Recursion in Swift and F#

Swift: recursion over an enum and an optional rewrite as a fold

// Expression ADT
indirect enum Expr { case num(Int), add(Expr,Expr), mul(Expr,Expr) }
// Structural recursion: select a sum branch and destructure its product
func eval(_ e: Expr) -> Int {
  switch e {
  case let .num(n):          return n
  case let .add(a,b):        return eval(a) + eval(b)
  case let .mul(a,b):        return eval(a) * eval(b)
  }
}

// Optional: define an algebra and a fold to factor out explicit recursion
extension Expr {
  func cata<T>(
    _ alg: (Expr) -> ((Int)->T, (T,T)->T, (T,T)->T) -> T
  ) -> T {
    switch self {
    case let .num(n):   return alg(.num(n))({ n in n }, {_,_ in fatalError()},{_,_ in fatalError()})
    case let .add(a,b): return alg(.add(a,b))({ _ in fatalError() }, { x,y in x+y }, {_,_ in fatalError()})
    case let .mul(a,b): return alg(.mul(a,b))({ _ in fatalError() }, {_,_ in fatalError()}, { x,y in x*y })
    }
  }
}
// In production, prefer a generic functor-based fold. This example simply gathers the recursive calls in one place.

F#:DU + match + rec

type Expr = Num of int | Add of Expr*Expr | Mul of Expr*Expr

let rec eval = function
  | Num n      -> n
  | Add(a,b)   -> eval a + eval b
  | Mul(a,b)   -> eval a * eval b

F# marks recursion explicitly with rec and uses match for algebraic destructuring. The official documentation describes pattern matching in terms of rules that align input data with logical structures and decompose the data.

When to use recursion schemes

An engineering checklist for recursion in APM

  1. Prefer structural recursion. Recurse into the self-similar parts of the ADT. Avoid nonstructural recursion through arbitrary indexing or reflection.

  2. Represent boundaries by unit or empty cases. Clear base cases ([]/() / None) make termination conditions explicit.

  3. Pair recursion with exhaustive matching. Adding a variant gives a compile-time reminder at recursive sites that need updating, such as a Swift switch or Kotlin when.

  4. When recursion becomes complex, consider rewriting it as a catamorphism or hylomorphism. Fusion laws remove intermediate structures, supporting optimization and equational reasoning.

  5. Document the laws. Record your algebra α\alpha and laws such as derivation and fusion as a basis for regression tests and code audits.

Summary. Recursion in APM uses algebraic matching to constrain self-calls to a unique traversal over constructors (a fold). When scale, performance, or proof demands more, move to recursion schemes and express recursive control flow as composable algebraic homomorphisms.

3.4 ADT Variants and OOP: Combining Them into a Powerful Construction

Two uses of OOP are central here:

Defining the types used to construct complex objects (the domain core)

Protocol-first boundaries: interfaces for the outside world

Put I/O, side effects, and third-party dependencies behind protocols or interfaces (Swift protocol, Kotlin/Java interface, Rust trait). The core can then depend only on abstractions and switch implementations.

In the C#/.NET driver, BsonValue is an abstract base class whose subclasses, including BsonInt32 and BsonString, encapsulate their own data. This is the class hierarchy and virtual dispatch approach. Swift-BSON instead lists every form in enum BSON { … }, using associated values for data. Consumers use an exhaustive switch. This is the ADT variant approach. The contrast gives us a concrete setting for combining ADTs and OOP.

Why favor composition over inheritance?

3.4.1 The Problem: One Concept, Many Forms of Value, Illustrated with BSON

MongoDB has production-grade BSON implementations in major ecosystems including .NET, Swift, Java, Node.js, Python, and Go. A BSON value can have any one of several types. Engineers commonly model this in one of two ways:

Both designs can express the intended semantics, but using and maintaining them feels different. An ADT fixes the set of possibilities in the type definition. A consumer covers all branches in one switch or match, and the compiler checks exhaustiveness. A class hierarchy usually relies on virtual methods or a Visitor. An omitted subclass often becomes apparent only at runtime or in tests.

3.4.2 A Minimal Comparison of the Two Models

Swift (ADT, defined in one place)

public enum BSON {
    case int32(Int32)
    case int64(Int64)
    case string(String)
    indirect case array([BSON])
    case document([String: BSON])
    case bool(Bool)
    case double(Double)
    case null
    // … list the other BSON forms here
}

C# (OOP, class hierarchy)

public abstract class BsonValue { /* Common interface, virtual methods, etc. */ }

public sealed class BsonInt32 : BsonValue {
    public int Value { get; }
    public BsonInt32(int value) => Value = value;
}

public sealed class BsonString : BsonValue {
    public string Value { get; }
    public BsonString(string value) => Value = value;
}

// … define one subclass for each form

Swift lists every form in one type. In C#, the enumeration is distributed across multiple type definitions and registration points. The locality of the definition directly affects the cost of reading and changing it.

3.4.3 For Consumers: Pattern Matching, Virtual Dispatch, or Visitor

Swift: use switch for pattern matching, with exhaustiveness checked by the compiler

func bsonToString(_ v: BSON) -> String {
    switch v {
    case .string(let s): return s
    case .int32(let n):  return String(n)
    case .int64(let n):  return String(n)
    case .double(let d): return String(d)
    case .bool(let b):   return String(b)
    case .null:          return "null"
    case .array(let xs): return "[" + xs.map(bsonToString).joined(separator: ",") + "]"
    case .document(let m):
        let kvs = m.map { k, v in "\"\(k)\": \(bsonToString(v))" }
        return "{" + kvs.joined(separator: ", ") + "}"
    }
    // A case added later will produce a compile-time nonexhaustive-match diagnostic here
}

C# approach 1: Virtual methods and polymorphism

public abstract class BsonValue { public abstract string Format(); }

public sealed class BsonInt32 : BsonValue {
    public int Value { get; }
    public override string Format() => Value.ToString();
}
// Each remaining subclass implements Format()

string s = someBsonValue.Format(); // A missing Format override in a new subclass can surface at runtime

C# approach 2: Visitor (statically detectable omissions, more boilerplate)

public interface IBsonVisitor<T> {
    T Visit(BsonInt32 x);
    T Visit(BsonString x);
    // … one entry per subclass
}

public abstract class BsonValue { public abstract T Accept<T>(IBsonVisitor<T> v); }

public sealed class BsonInt32 : BsonValue {
    public int Value { get; }
    public override T Accept<T>(IBsonVisitor<T> v) => v.Visit(this);
}
// Consumer: implement a Visitor; the compiler can report an unimplemented Visit(NewSubclass)

The difference. A Visitor approaches the exhaustiveness of pattern matching, but it requires more boilerplate and costs more to extend. A switch over an ADT is direct, local, and concise.

3.4.4 Why Prefer an ADT in This Setting?

3.4.5 When Class Inheritance Is Still Needed and How to Bridge the Two

A conceptual bridge between C# and Swift

For a more functional approach within .NET, define Bson directly as an F# DU. C# consumers can interoperate through pattern matching or property access. Alternatively, approximate an ADT in C# with a sealed hierarchy and switch pattern matching.

3.5 Further Reading: Origins and Evolution of ADT Variants

3.5.1 Clarifying the Terms: Abstract and Algebraic Data Types

In many modern languages, especially in the ML/Haskell family, ADT usually means algebraic. In this book, “ADT variants” refers to the branches or extensions of algebraic data types, including GADTs.

3.5.2 Theoretical Origins (1970s–1990s)

A related line predates these languages: ALGOL 68 and Pascal already had unions or variant records (tagged unions). They lacked the constraints of typed constructors and exhaustive matching found in modern ADTs and can be viewed as their early predecessors.

3.5.3 Extensions and Refinements: GADTs and Beyond (2000s Onward)

3.5.4 Language Families and Their Variants: From Theory to Syntax

The ML/Haskell family (the home of classical ADTs)

ADT variants in contemporary mainstream languages: different syntax, common semantic roots

These variants differ in syntax but share sums and products as modeling primitives, together with exhaustive matching and type inference. This is the ML/Haskell tradition at work in mainstream languages.

Algebraic data types have roots in universal algebra and initial-algebra semantics and also have a natural practical connection with BNF (Backus–Naur Form). We now trace these two lines of development.

3.5.5 The Connection to Universal Algebra: Foundations of Semantics and Specification

Algebraic data types have roots in universal algebra and initial-algebra semantics and a natural practical connection with BNF (Backus–Naur Form). We now trace these two lines of development.

In short, an ADT is an initial algebra for an algebraic signature, or equivalently the corresponding term algebra or free algebra. Universal algebra supplies the general vocabulary of signatures, homomorphisms, quotients, products, and equational reasoning.

3.5.6 The Connection to BNF: From Grammar to Abstract Syntax and Data

BNF is a syntax for describing syntax, or metasyntax (Wikipedia contributors, 2025). It expresses a language’s context-free grammar (CFG) as a table of production rules that determine exactly which symbol sequences are sentences of the language. Many language specifications and textbooks use BNF or a variant to present a formal grammar.

Common variants

Compiler texts and functional programming textbooks teach a standard correspondence: map each production of the grammar to an ADT constructor. A nonterminal corresponds to an algebraic data type, alternatives (|) to a sum type, concatenation to a product or tuple, and recursive productions to recursive types. The path from BNF to an abstract syntax tree (AST) and then to an ADT definition is almost mechanical.

Tools support this mapping directly. The BNF Converter (BNFC), for example, automatically generates abstract-syntax type definitions and parsers from annotated BNF/LBNF for several target languages. In essence, it turns productions into constructors.

In summary, BNF gives the formal grammar, and an ADT gives the abstract data. Reading BNF productions as constructor signatures yields “AST = term algebra,” bringing us back to initial-algebra semantics.

From BNF to an F# ADT: a small mechanical mapping

BNF

Expr ::= Num
       |  Expr "+" Expr
       |  Expr "*" Expr

F# ADT

type Expr =
  | Num of int
  | Plus  of Expr * Expr
  | Times of Expr * Expr

3.5.7 Extending F# ADTs: Option/Result, Active Patterns, and Struct DUs

Example: Result working with an active pattern

// Active pattern: try to parse a string as an int or a bool
let (|AsInt|AsBool|Other|) (s:string) =
  match System.Int32.TryParse s, System.Boolean.TryParse s with
  | (true, n), _    -> AsInt n
  | _, (true, b)    -> AsBool b
  | _               -> Other

let parse (s:string) : Result<obj,string> =
  match s with
  | AsInt n  -> Ok (box n)
  | AsBool b -> Ok (box b)
  | Other    -> Error $"unrecognized: {s}"

The documentation presents active patterns as a mechanism for matching named partitions. The official documentation for Result identifies it as a struct DU and describes its companion combinator module.

3.6 Chapter Recap: Combining ADT Variants, OOP, and Combinators

Encode the set of possibilities in an ADT, put mutable side effects behind OOP ports, and compose the workflow from verifiable building blocks with map, ap, and flatMap. ADTs provide exhaustive matching and type safety, OOP provides replaceable and mockable engineering interfaces, and Functor, Applicative, and Monad make computations composable, testable, and replayable. Swift, Kotlin, F#, Rust, and Scala all have mature language and ecosystem support for this combination.

Function chains, object-oriented design, algebraic composition, and the combinator pipeline.

Figure 3-6. Four layers working together: long-chain functions → OOP (domain core and protocol-first boundary) → algebraic composition (ADTs and algebraic pattern matching) → combinator pipelines (Functor, Applicative, and Monad)

Why four layers?

  1. Long-chain functions (top layer: interfaces and assembly syntax)

    Use currying, partial application, and trailing closures to write chainable APIs. This facilitates protocol-first injection (Reader-style injection in the initial argument positions), and gives the subsequent OOP and ADT entry points the form of arrow chains. Swift’s trailing closures and closure rules directly support this style.

  2. OOP (upper middle layer: objects and boundaries)

    • Domain core. Use classes and value types to encapsulate invariants and complex objects, including entities and value objects.

    • Protocol-first boundary. Put external facilities such as repositories, HTTP, LLMs, and UIs behind a protocol, interface, or trait for substitution and testing. Swift’s protocol-oriented programming (POP) and conventional interface-based OOP share this practice.

  3. Algebraic composition (lower middle layer: structure and correctness).
    Use an ADT to encode all possible forms together in a type definition (a sum of products). Consumers handle them exhaustively with algebraic pattern matching:

    • F# discriminated unions and pattern matching.

    • Kotlin sealed hierarchies and compile-time exhaustiveness checks for when.
      This layer makes an uncovered case visible at compile time whenever a variant is added.

  4. Combinator pipelines (bottom layer: assembling steps into a verifiable workflow)

    • Functor. Map a pure transformation over a single context (map).

    • Applicative. Aggregate independent effects in parallel (ap/product).

    • Monad. Sequence dependent steps (flatMap/bind) under laws that support reasoning. The Cats documentation gives practical definitions and APIs.

3.6.1 A Minimal Example of the Layers Working Together (Swift and Kotlin)

Swift: a command ADT, ports, and flatMap-style orchestration

// Domain ADT (sum/product)
enum Command {
  case createUser(name: String, email: String)
  case deleteUser(id: Int)
  case resetPassword(id: Int)
}

// Port (OOP interface)
protocol UserRepo {
  func exists(_ id: Int) throws -> Bool
  func insert(name: String, email: String) throws
  func remove(_ id: Int) throws
}

// Application service: exhaustively match an ADT inside OOP code
final class UserService {
  let repo: UserRepo
  init(repo: UserRepo) { self.repo = repo }

  func handle(_ c: Command) throws {
    switch c {
    case let .createUser(name, email):
      try repo.insert(name: name, email: email)         // Replaceable adapter
    case let .deleteUser(id):
      if try repo.exists(id) { try repo.remove(id) }
    case let .resetPassword(id):
      // … call the LLM/email port (omitted)
    }
  }
}

Kotlin (Arrow): Either combinators treat errors as data

import arrow.core.Either
import arrow.core.flatMap

fun parseInt(s: String): Either<NumberFormatException, Int> =
  if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt())
  else Either.Left(NumberFormatException("$s is not a valid integer."))

fun reciprocal(n: Int): Either<IllegalArgumentException, Double> =
  if (n != 0) Either.Right(1.0 / n) else Either.Left(IllegalArgumentException("zero"))

val res: Either<Throwable, Double> =
  parseInt("42")
    .flatMap { n -> reciprocal(n) }     // Monad: sequence dependent steps
    .map { x -> x * 100 }               // Functor: pure mapping

The Arrow documentation demonstrates composition with Either.map and flatMap as a typed alternative to try-catch exception handling. Cats uses the same approach in Scala.

3.6.2 A Design Checklist for Combining the Four Layers

  1. Use an ADT in the core. Collect the possibilities in an enum, sealed hierarchy, or DU. Do not allow data encoded as “TypeCode + Any” to cross the boundary unchecked.

  2. Assemble workflows with combinators. Use Applicative to aggregate independent effects and Monad to sequence dependent ones. Describe data flow with pure functions and types where possible.

  3. Favor composition and use inheritance sparingly. Compose behavior through interfaces and delegation. Avoid deep inheritance trees.

  4. Design for evolution. If a public API may add cases, use @unknown default in Swift and control the boundaries of the sealed hierarchy in Kotlin.

  5. Make the workflow replayable and auditable. Log the complete path from external input through the ADT and combinator pipeline to the output, enabling replay and audit.

3.6.3 Summary

An ADT defines a closed set of possibilities, OOP supplies open boundaries and substitution points, and combinators assemble data and control flow according to algebraic laws. The three are complementary:


  1. The railway metaphor in Railway-Oriented Programming (ROP) treats Result<'T,'E> as two tracks: a success track (Ok) and a failure track (Error).↩︎

CHAPTER 4

Defining Neural Networks Across AI Frameworks with the Sweetest Layer

This chapter bridges the gap between a neural network as a mathematical object and an executable implementation with a minimal, verifiable abstraction called the sweetest layer. The high-level description specifies only structure and semantics. At the lower level, lowering mechanically translates that description into calls to a concrete operator library, here MathNet. Separating the definition of a network from its execution lets us discuss models in a common language, independently of the details of PyTorch, TensorFlow, or ONNX.

The sweetest layer has just two kinds of building block:

  1. Primitive operators such as MatMul, Add, Sigmoid, Tanh, and Softmax perform numerical computations.

  2. Structural combinators such as Chain, Parallel, Bundle, BigBundle, In, Select, and Sole organize data flow.

Add output semantics (Single | Multiple n | Dynamic), port contracts (shape and type constraints on inputs, outputs, and state), and minimal control-flow constructs and phase placeholders such as Iterate, Fix, and Phase(tag, Coda). We can then automatically lower a network graph through static validation → shape inference → normalization → backend selection.1

One observation runs through this chapter:

Chapter outline

Chapter 6 develops the technical details of backpropagation and automatic differentiation. Here we focus on forward semantics and the lowering mechanism itself.

4.1 A Mathematical Definition of a Deep Neural Network

4.1.1 Data and Parameters

4.1.2 The Model as a Directed Acyclic Graph or a Composition of Functions

View the network as a computation graph 𝒢\mathcal{G} built from a set of primitive operators 𝒪\mathcal{O}. Each node computes

zj=oj(za(j),zb(j),…;θS(j))z_{j} = o_{j}(z_{a(j)},z_{b(j)},\ldots;\theta_{S(j)}).

Equivalently, in functional notation:

fθ=ϕL∘ϕL−1∘⋯∘ϕ1,ϕ𝓁:ℝn𝓁−1→ℝn𝓁,f_{\theta}\; = \;\phi_{L} \circ \phi_{L - 1} \circ \cdots \circ \phi_{1},\phi_{\mathcal{l}}:\mathbb{R}^{n_{\mathcal{l} - 1}} \rightarrow \mathbb{R}^{n_{\mathcal{l}}},

Each ϕ𝓁\phi_{\mathcal{l}} may contain a set of parameters θ𝓁\theta_{\mathcal{l}}.

4.1.3 Loss and Empirical Risk

This book keeps the mathematical and implementation layers strictly separate. The rest of the chapter describes mechanical lowering from the abstract representation (the sweetest layer) to an executable backend (MathNet).

4.2 Representing High-Level Forward Computation with Variants

Layer by layer, or node by node. Given input xx and parameters θ\theta, compute the intermediate values z1,z2,…,zMz_{1},z_{2},\ldots,z_{M} in topological order to obtain fθ(x)f_{\theta}(x).

Typical primitives

We construct networks at two levels, using primitive operators and structural combinators.

4.2.1 Primitive Operators Implemented by the Backend

The primitive operators include ShapeIx(PrimShape), Algebra(PrimAlgebra), Module(PrimModule), and Emb(PrimEmbedding).

// Enumeration used only in the Abstract layer
type Activation = Identity | ReLU | Sigmoid | Tanh | GELU

// ── Shape and indexing ──────────────────────────────────────
type PrimShape =
    | Shape                               // Get the shape of x (lowers to NodeADT.Shape)
    | Reshape     //of sid:Sid              // Sid identifies the shape specification (lowers to a constant shape tensor + Reshape)
    | Transpose   of perm:int list
    | Concat      of axis:int
    | Split       of axis:int * splits:int list option
    | Unsqueeze   of axes:int list
    | Squeeze     of axes:int list
    | Slice       of starts:int64 list * ends:int64 list * axes:int list * steps:int list
    | Gather      of axis:int
    | Range       of start:int64 * limit:int64 * delta:int64
    | ConstantOfShape of value:float
    | Cast        of toType: DType         // For ONNX alignment, Cast can go here with shape/indexing operations, or in the algebra group.
    | Where

// ── Tensor algebra (numerical kernels) ──────────────────────
type PrimAlgebra =
  | Add | Sub | Mul | Div
  | MatMul
  | Gemm of alpha:float * beta:float * transA:bool * transB:bool
  | ReduceMean of axes:int list * keepDims:bool
  | Pow | Sqrt
  | Softmax of axis:int
  | Act of Activation                   // ReLU/Sigmoid/Tanh/GELU, etc.; these can also be treated as module-level operations.

// ── Modules: common patterns built from primitive operators ─
type LinearSpec  = { W:Pid; B:Pid option; transW:bool }  // y = x @ W^T + b (transW=true is a common layout)
type AffineSpec  = { Scale:Pid; Bias:Pid option }        // y = scale ⊙ x + b (with broadcasting)
type NormSpec    =
  | LayerNorm of gamma:Pid * beta:Pid option * eps:float * axis:int
  | RMSNorm   of gamma:Pid * eps:float * axis:int

type PrimModule =
  | Linear of LinearSpec
  | Affine of AffineSpec
  | Norm   of NormSpec
  // Add Dropout (a pass-through at inference), CausalMask (see the optional syntactic sugar below), and so on as needed.

// ── Embeddings: explicit semantics, usually implemented with Gather ──
type EmbeddingSpec = { Table:Pid; Axis:int }  // Axis=0 for GPT-2's wte/wpe
type PrimEmbedding =
  | Lookup of EmbeddingSpec                   // General embedding lookup
  | TokenEmbedding of table:Pid               // Explicit token semantics; still implemented with Gather(Axis=0)
  | PosEmbedding   of table:Pid               // Explicit position semantics; still implemented with Gather(Axis=0)

4.2.2 Structural Combinators for Data Flow Without Numerical Computation

type Node =
    // Data sources
    | Tensor of Tid
    | Param of Pid
    | ShapeParam of Sid

    // Primitive operators
    | ShapeIx  of PrimShape
    | Algebra  of PrimAlgebra
    | Module   of PrimModule
    | Emb      of PrimEmbedding

    // ─── Structural composition ──────────────────────────────────
    /// Create a tuple of inputs for an operator with multiple arguments.
    /// Output semantics: Single — one packed tuple.
    /// Example: Bundle [data; shape] |> ShapeIx Reshape
    | Bundle of Node list

    /// Create a collection of selectable outputs.
    /// Output semantics: Multiple(n) — n individually selectable outputs.
    /// Example: BigBundle [node1; node2; node3] can be followed by Select 0/1/2.
    | BigBundle of Node list

    /// Select item i from the closest enclosing BigBundle.
    /// Precondition: the enclosing construct must be a BigBundle.
    /// Output semantics: Single — the selected item.
    | Select of int

    /// Select item i from the enclosing computation stack.
    /// - Inside Parallel: select the output of branch i.
    /// - Inside BigBundle: equivalent to Select i.
    /// - Inside Chain: only In 0 is valid (select the last node's output).
    /// Output semantics: Single — the selected item's output.
    | In of int

    /// Take the sole item from the enclosing output.
    /// Precondition: the enclosing output semantics must be Single.
    /// Output semantics: Single — pass through the enclosing construct's only output.
    | Sole

    // ─── Control flow ────────────────────────────────────────────

    /// Execute a list of nodes in sequence.
    /// Output semantics: Single — the output of the last node.
    /// Data flow: node1 -> node2 -> ... -> nodeN; each node receives the previous node's output.
    | Chain of Node list

    /// Execute a list of nodes in parallel.
    /// Output semantics: Multiple(n) — implicitly bundles the outputs of n branches.
    /// Data flow: the input is copied to all branches; each branch computes independently.
    /// Access: use In i to select the output of branch i.
    | Parallel of Node list

    // State management
    | Bypass of int * Tid
    | Feed of Tid

    // Advanced control flow
    | Iterate of IterateSpec
    | Fix     of FixSpec

    // Subgraph with parameter, tensor, and shape mappings
    | SubGraph of DefContext * ParamMap list * TensorMap list * ShapeMap list * Node

    // Phase(tag, item) represents an item within a particular phase (tag).
    // Convention: item = Coda denotes a placeholder that has yet to be refined into a concrete subgraph.
    | Phase of string * GenericNode

    // Termination
    | End

    // Subgraph with parameter, tensor, and shape mappings
    | SubGraph of DefContext * ParamMap list * TensorMap list * ShapeMap list * Node

    // Termination
    | End

4.2.3 Context and Port Contracts

A network is represented as a NodeGraph:

Binding ports inside the graph connects external I/O to the internal representation and reduces the glue code needed for lowering.

Graph definition

/// A Node graph with its symbol table, I/O contract, and body Node
type NodeGraph = {
  ctx  : DefContext
  io   : {| inputs: PortContract list; outputs: PortContract list; states: PortContract list |}
  body : Node
}

This small amount of code suffices to define useful neural networks such as LSTMs. Interpreting the variant-based definition lets us run inference and generate text.

4.3 From Abstraction to Execution: Automatic Lowering and MathNet Binding

Goal. Automatically transform a NodeGraph into an executable program implemented with MathNet.Numerics. The process has the following stages.

4.3.1 Semantic Validation

4.3.2 Shape and Type Inference

4.3.3 Normalization

4.3.4 Expanding Control Flow

4.3.5 Expanding Phases

For Phase(tag, Coda), substitute the corresponding subgraph if the profile supplies an implementation for tag. Otherwise the placeholder remains and cannot be lowered.

4.3.6 Selecting and Implementing Operators

For an LSTM, all six stages can be completed without additional information. For an LLM, the profile must specify phases, layouts, and caching policies at stage 5. Otherwise there is no unique lowering (see §4.5).

4.4 An LSTM from Equations to the Sweetest Layer to Executable Code

Long short-term memory (LSTM) networks were introduced in 1997 to address the difficulty of learning long-range dependencies in the presence of vanishing or exploding gradients. Memory cells and gates allow error signals to propagate stably through time, making sequence models easier to train and use (Bengio et al., 1994; Hochreiter & Schmidhuber, 1997).

Later improvements made LSTMs practical. The forget gate improved stability on long input streams (Gers et al., 2000). Bidirectional RNNs and training and labeling methods such as CTC helped bidirectional LSTMs achieve state-of-the-art results in speech and handwriting recognition (Graves et al., 2006, 2013; Schuster & Paliwal, 1997). In machine translation, the LSTM-based sequence-to-sequence encoder–decoder and its practical implementations (Sutskever et al., 2014; Y. Wu et al., 2016) enabled large-scale deployment of end-to-end neural translation.

The evolution of attention illustrates the connection to the Transformer. Attention was first proposed as an alignment mechanism for LSTM/GRU encoder–decoders (Bahdanau et al., 2015). The Transformer subsequently eliminated recurrence altogether, using self-attention to model dependencies across the sequence. This increased parallelism, accelerated training, and improved results on multiple tasks (Vaswani et al., 2017). Transformers gradually displaced LSTM-centered architectures as the prevailing approach in NLP.

In a systematic investigation of LSTM equations and variants, Greff et al. compared many LSTM variants at scale. They highlighted the importance of the forget gate and the output activation. Their study provides background for the variant-based definition and derivations that follow (Greff et al., 2017).

4.4.1 The LSTM Equations

Consider the standard equations for an LSTM cell. Given the input vector xt∈ℝdx_{t} \in \mathbb{R}^{d} at the current time step, the previous hidden state Ht−1∈ℝhH_{t - 1} \in \mathbb{R}^{h}, and the previous cell state ct−1∈ℝhc_{t - 1} \in \mathbb{R}^{h}, the forward computation for one LSTM layer is

ft=σ(Wfxt+UfHt−1+bf)(forget gate)it=σ(Wixt+UiHt−1+bi)(input gate)ot=σ(Woxt+UoHt−1+bo)(output gate)gt=tanh(Wgxt+UgHt−1+bg)(candidate cell content)ct=ft⊙ct−1+it⊙gt(cell state update)ht=ot⊙tanh(ct)(hidden state output)\begin{matrix} f_{t} & = \sigma\left( W_{f}x_{t} + U_{f}H_{t - 1} + b_{f} \right)\quad & \text{(}\text{forget gate}\text{)} \\ i_{t} & = \sigma\left( W_{i}x_{t} + U_{i}H_{t - 1} + b_{i} \right)\quad & \text{(}\text{input gate}\text{)} \\ o_{t} & = \sigma\left( W_{o}x_{t} + U_{o}H_{t - 1} + b_{o} \right)\quad & \text{(}\text{output gate}\text{)} \\ g_{t} & = tanh\left( W_{g}x_{t} + U_{g}H_{t - 1} + b_{g} \right)\quad & \text{(}\text{candidate cell content}\text{)} \\ c_{t} & = f_{t} \odot c_{t - 1}\mspace{6mu} + \mspace{6mu} i_{t} \odot g_{t}\quad & \text{(}\text{cell state update}\text{)} \\ h_{t} & = o_{t} \odot tanh(c_{t})\quad & \text{(}\text{hidden state output}\text{)} \end{matrix}

Table 4-1. LSTM notation

Symbol Dimensions Meaning
xtx_{t} dd Current input vector
Ht−1H_{t - 1} hh Previous hidden state
ct−1c_{t - 1} hh Previous cell state
W*W_{*} h×dh \times d Input-to-gate weight matrix
U*U_{*} h×hh \times h Hidden-to-gate weight matrix
b*b_{*} hh Bias vector for each gate
σ(⋅)\sigma( \cdot ) — Sigmoid activation function
tanh(⋅)tanh( \cdot ) — Hyperbolic tangent activation
⊙\odot — Elementwise multiplication (Hadamard product)

4.4.2 Implementing an LSTM in the Sweetest Layer with Fully Automatic Lowering

The following code expresses the LSTM's data flow using only structural combinators and primitive operators. It uses no framework-specific APIs. After lowering, it maps directly to MathNet.

A common construction for the gates

open ACNN.Abstract

/// u·x + w·h + b → Act
let createGate (act: PrimModule) (wf, uf, bf: Pid*Pid*Pid) : Node =
  Chain [
    // Three parallel branches: Wx, Uh, b
    Parallel [
      Chain [ Bundle [ Param wf; Tensor (Tid "x") ]; Module PrimModule.MatMul ]   // W * x
      Chain [ Bundle [ Param uf; Feed   (Tid "h") ]; Module PrimModule.MatMul ]   // U * h_{t-1}
      Param bf                                                                    // b
    ]
    // Sum the three terms
    Bundle [ In 0; In 1 ];  Algebra PrimAlgebra.Add
    Bundle [ Sole; In 2 ];  Algebra PrimAlgebra.Add
    // Apply the activation
    Module (PrimModule.Act act)   // act ∈ Sigmoid | Tanh
  ]

The body of one LSTM layer

// Organize inputs, outputs, and state by port contract; only key fields are shown.
let lstmGraph (ctx: DefContext) (ps: {| wf:Pid; uf:Pid; bf:Pid;
                                         wi:Pid; ui:Pid; bi:Pid;
                                         wo:Pid; uo:Pid; bo:Pid;
                                         wg:Pid; ug:Pid; bg:Pid;
                                         whq:Pid; bq:Pid |}) : NodeGraph =

  // Four gates computed in parallel, yielding Multiple 4
  let gates =
    Parallel [
      createGate PrimModule.Sigmoid (ps.wf, ps.uf, ps.bf)   // f_t
      createGate PrimModule.Sigmoid (ps.wi, ps.ui, ps.bi)   // i_t
      createGate PrimModule.Sigmoid (ps.wo, ps.uo, ps.bo)   // o_t
      createGate PrimModule.Tanh    (ps.wg, ps.ug, ps.bg)   // g_t
    ]

  // Body: update c_t and h_t from gates, then produce output y_t.
  let body =
    Chain [
      gates
      // Snapshot the four gate outputs as a selectable collection for subsequent Select i operations.
      BigBundle [ In 0; In 1; In 2; In 3 ]

      // c_t = f_t ⊙ c_{t-1} + i_t ⊙ g_t
      Parallel [
        Chain [ Bundle [ Select 0; Feed (Tid "c") ]; Algebra PrimAlgebra.Hadamard ] // f_t ⊙ c_{t-1}
        Chain [ Bundle [ Select 1; Select 3 ];       Algebra PrimAlgebra.Hadamard ] // i_t ⊙ g_t
      ]
      Bundle [ In 0; In 1 ]; Algebra PrimAlgebra.Add
      Bypass (0, Tid "c")     // Write back the latest c_t

      // h_t = o_t ⊙ tanh(c_t)
      Parallel [
        Chain [ Feed (Tid "c"); Module (PrimModule.Act PrimModule.Tanh) ]           // tanh(c_t)
        Chain [ Select 2 ]                                                          // o_t
      ]
      Bundle [ In 0; In 1 ]; Algebra PrimAlgebra.Hadamard
      Bypass (0, Tid "h")     // Write back the latest h_t

      // y_t = softmax(W_hq * h_t + b_q)
      Parallel [
        Chain [ Bundle [ Param ps.whq; Feed (Tid "h") ]; Module PrimModule.MatMul ]
        Chain [ Param ps.bq ]
      ]
      Bundle [ In 0; In 1 ]; Algebra PrimAlgebra.Add
      Module (PrimModule.Act PrimModule.Softmax)
    ]

  {
    ctx  = ctx
    io   =
      {| inputs  = [ { name="x"; kind=Input;  dtype=Float32; shape=Shape.ofSym "d"; bind=Tensor (Tid "x") } ]
         outputs = [ { name="y"; kind=Output; dtype=Float32; shape=Shape.ofSym "q"; bind=Sole } ]
         states  =
           [ { name="h"; kind=State;  dtype=Float32; shape=Shape.ofSym "h"; bind=Feed (Tid "h") }
             { name="c"; kind=State;  dtype=Float32; shape=Shape.ofSym "h"; bind=Feed (Tid "c") } ] |}
    body = body
  }

Automatic lowering to MathNet

Apart from the required dimensions and types, supplied by PortContract.shape/dtype and DefContext.Sids, no profile is needed.

This code illustrates a surprising aspect of organizing a program around variants. Load trained model data, use the network defined above, and enter “Sichuan University.” Here is one sample output, rendered in English:

“Sichuan University India that beauty most the beauty of immortals your perfectionism too thorough leaves me struggling even to write of hate I truly draw”

It reads like generated text, but much of it reproduces text the model has memorized. Changing controls such as temperature produces different text.

4.5 Lowering Complex LLMs: Why a Profile Is Necessary

Lowering interprets Node as the more concrete NodeForward type. The structure of NodeForward corresponds to that of Node. The next chapter defines NodeADT.

// NodeForward (execution IR): computation nodes and planning nodes in one representation
type NodeForward =
  // Import external data, parameters, and constants.
  | FInputTensor of outT: TensorRef * from: TensorRef      // Bind an external tensor handle
  | FInputParam  of outT: TensorRef * from: ParamRef       // Read a parameter
  | FInputShape  of outT: TensorRef * from: ShapeRef       // A shape tensor, represented uniformly as a 1D int64 tensor

  // Computation: one NodeADT and its inputs -> outputs, optionally with placement and synchronization information
  | FCompute of op: NodeADT * ins: TensorRef list * outs: TensorRef list
               * place: Placement option * sync: SyncSpec option

  // Data movement/alignment and synchronization (optional; extend as needed)
  | FCopy   of dst: TensorRef * src: TensorRef * place: Placement option * sync: SyncSpec option
  | FBarrier of sync: SyncSpec                              // Synchronization only, no data
  | FFree   of TensorRef                                    // End of lifetime (memory-reuse hint)

  // Structural and control-flow sugar for planning; can ultimately be flattened into a topological order
  | FSeq    of NodeForward list                             // Sequential execution
  | FPar    of NodeForward list                             // Parallel branches; data dependencies ensure safety
  | FReturn of TensorRef list                               // Plan exit
  | FCall   of body: NodeForward * bindIns: (TensorRef*TensorRef) list * bindOuts: TensorRef list
  | FIter   of spec: IterateFSpec                           // Retain the existing iteration semantics

Compared with an LSTM, an LLM or Transformer introduces phase transitions, dynamic lengths, and cache layouts. The abstraction alone rarely determines a unique backend implementation. Typical difficulties include the following.

Phase differences

Shapes and layouts

Specify dmodel,nlayer,nhead,head_dimd_{model},n_{layer},n_{head},head\_\dim, the kv_layout (such as [B, L, H, D] or [L, B, H, D]), mask semantics and broadcasting rules, and positional encoding settings such as RoPE or ALiBi.

Caching and loop-carried state

The profile must specify the CarryKeys of Iterate and the KV-cache mapping from present to past. Otherwise lowering cannot generate Feed/Bypass operations in the correct order.

Operator selection

Should the implementation use FlashAttention, fused GEMM, or quantized kernels? The abstract syntax cannot decide. These choices are driven by the implementation policy in the profile.

How it works

In short:

4.6 Summary


  1. In compiler theory, deep learning frameworks, and algebraic programming, “lowering” has much the same meaning. It is the process of progressively translating a high-level abstraction into a lower-level executable representation.↩︎

CHAPTER 5

Transformers and LLMs in Practice

Since Attention Is All You Need introduced an attention-only architecture, the Transformer has become the common backbone of modern sequence models and LLMs. GPT-2 subsequently demonstrated zero-shot and few-shot generalization through large-scale autoregressive pretraining, establishing the practical pattern of a pretraining corpus and a common backbone. Implementations such as Hugging Face's modeling_gpt2 express a block as ln_1 → attn(c_attn/c_proj) → Add → ln_2 → mlp(c_fc/gelu/c_proj) → Add. This pre-normalization structure, with two residual connections, corresponds directly to the names and topology of the exported ONNX graph.

We take three steps from the abstraction in a research paper to an executable backend.

We also consider widely used approaches to positions and context. RoPE (rotary position embedding) introduces phase structure into the representation space. ALiBi (attention with linear biases) introduces distance structure into attention scores. At the operator and ADT level, we identify the shape and profile information needed to implement them.

Think of this chapter as an operator-level blueprint for an LLM. Each entry explains a part of the ONNX specification and constrains the design of the corresponding ADT code. A common sequence—specification, equations, use, ADT—takes the Transformer as described in the literature to a computation graph that can be validated, lowered, and executed.

5.1 The Role of LLMs and Transformers

Since Attention Is All You Need (Vaswani et al., 2017) introduced the Transformer in 2017, sequence modeling has undergone a fundamental change. Attention displaced recurrence and convolution at the center of most language tasks. This enabled large-scale pretraining of large language models (LLMs) that generalize across tasks, giving rise to the general-purpose platforms and foundation-model ecosystem of contemporary AI.

Empirically, LLM performance follows fairly stable scaling laws. Loss decreases approximately as a power law with model size, training data, and training compute. The later Chinchilla results showed that, for a fixed compute budget, training is more compute-efficient when model size and training-token count grow in roughly equal proportion. These findings explain the preference for larger models, longer training runs, and better data, and give practitioners concrete guidance on design and resource allocation (Hoffmann et al., 2022; Kaplan et al., 2020).

In cross-modal generalization and practical deployment, Transformers have moved beyond text. In vision, ViT (Dosovitskiy et al., 2021) replaced convolution with attention and achieved competitive or better performance. Transferable segmentation models with prompt-based interfaces, such as SAM and SAM2, reinforced the common-backbone, task-specific-head pattern. In semantic search and question answering, RAG combines retrieval from external memory with a generative model, improving factual accuracy on knowledge-intensive tasks and making knowledge easier to update. Together these advances established LLMs and Transformers as part of AI infrastructure.

From a systems and engineering perspective, kernel and system optimizations such as FlashAttention and its successors recast the bandwidth bottleneck in attention as an I/O problem that can be optimized. They substantially accelerate training and inference and support longer contexts and larger batches. Meanwhile, rapid community development around open-source and open-weight models such as LLaMA and Mistral (A. Q. Jiang et al., 2023; Touvron, Lavril, et al., 2023; Touvron, Martin, et al., 2023) has driven advances in inference engines, scheduling, and quantization, further entrenching the ecosystem.

The quadratic complexity of attention has also motivated alternatives. Linear-time architectures such as Mamba (Gu & Dao, 2023), based on selective state space models, show promise for long sequences and high throughput. As the authors observed in their abstract, however, almost all foundation models at the time were Transformers. The technical barriers and migration costs of complete replacement are high in the near term. A more immediately practical route is to modify the structure or introduce sparsity within the Transformer architecture, for example through mixture-of-experts routing, to balance performance and efficiency.

From an industry perspective, the metaphor of AI as electricity has acquired new force in the LLM era. Just as electrification enabled advances across industries, LLMs serve as general-purpose engines for semantic processing and generation in content creation, programming, retrieval and question answering, workflow automation, and multimodal interaction. They are becoming a shared foundation for digital technology and machine intelligence. We begin with the mathematical structure of the Transformer in GPT-2 (Hugging Face, 2020; Radford et al., 2019) in §5.2. We then examine attention and its correspondence to ONNX (§5.3), trace its historical development (§5.4), and give node-level equations and ADT variant code (§5.5–§5.13).

5.2 A Mathematical Definition of the 12-Layer GPT-2 Transformer

I relate common symbols and equations to weight names, submodule names, and recurring operator patterns in Hugging Face and ONNX exports.

The following definition uses pre-layer normalization (Pre-LN) and causal self-attention.

5.2.1 Input Embeddings

Token and position embeddings

X0=Embed(input_ids)+PosEmbed(position_ids)X_{0} = Embed(input\_ ids) + PosEmbed(position\_ ids);

Here (V)(V) is the vocabulary size and (D)(D) the hidden dimension. In Hugging Face the tables are wte (V×DV \times D) and wpe (Npos×DN_{pos} \times D). Dropout is applied to the output.

5.2.2 Layer 𝓁\mathcal{l} (𝓁=𝟎,…,𝐋−𝟏\mathcal{l}\mathbf{=}\mathbf{0}\mathbf{,\ldots,}\mathbf{L}\mathbf{-}\mathbf{1})

  1. Pre-normalization

    X̂𝓁=LNγ𝓁,1,β𝓁,1(X𝓁){\widehat{X}}_{\mathcal{l}} = {LN}_{\gamma_{\mathcal{l},1},\beta_{\mathcal{l},1}}(X_{\mathcal{l}}),

    LN(x)=γx−μσ2+ε+βLN(x) = \gamma\frac{x - \mu}{\sqrt{\sigma^{2} + \varepsilon}} + \beta.

    GPT-2 defaults to ε=10−5\varepsilon = 10^{- 5} (layer_norm_epsilon).

  2. Fused QKV projection (one linear transformation produces width 3D, then splits the result):

    [Q𝓁,K𝓁,V𝓁]=X̂𝓁Wc_attn(𝓁)+bc_attn(𝓁)\lbrack Q_{\mathcal{l}},K_{\mathcal{l}},V_{\mathcal{l}}\rbrack = {\widehat{X}}_{\mathcal{l}}W_{c\_ attn}^{\mathcal{(l)}} + b_{c\_ attn}^{\mathcal{(l)}},

    Here Wc_attn(𝓁)∈ℝD×3DW_{c\_ attn}^{(\mathcal{l})} \in \mathbb{R}^{D \times 3D}. Hugging Face uses Conv1D(3D,D), effectively a linear layer with transposed weight storage.

  3. Splitting into heads and scaled dot-product attention. Reshape (Q,K,V)(Q,K,V) to [B,H,S,Dh]\lbrack B,H,S,D_{h}\rbrack, where D=H⋅DhD = H \cdot D_{h}.

    α=softmax(QK⊤Dh+Mcausal+Mattn)\alpha = softmax\left( \frac{QK^{\top}}{\sqrt{D_{h}}} + M_{\text{causal}} + M_{\text{attn}} \right), Attn=αVAttn = \alpha V.

    Here McausalM_{\text{causal}} is the lower-triangular mask. Hugging Face implements it with attn.bias (triangular zeros and ones) and attn.masked_bias (−104- 10^{4}). The attention_mask is incorporated additively.

  4. Merging heads and projecting the output

    A𝓁=concat_heads(Attn)Wc_proj(𝓁)+bc_proj(𝓁)A_{\mathcal{l}} = concat\_ heads(Attn)W_{c\_ proj}^{(\mathcal{l})} + b_{c\_ proj}^{(\mathcal{l})},

    X𝓁′=X𝓁+dropout(A𝓁)X_{\mathcal{l}'} = X_{\mathcal{l}} + dropout(A_{\mathcal{l}}).

  5. The pre-LN MLP branch with GELU

    X̃𝓁=LNγ𝓁,2,β𝓁,2(X′𝓁){\widetilde{X}}_{\mathcal{l}} = {LN}_{\gamma_{\mathcal{l},2},\beta_{\mathcal{l},2}}({X'}_{\mathcal{l}});

    H𝓁=GELU(X̃𝓁Wfc(𝓁)+bfc(𝓁))H_{\mathcal{l}} = GELU\left( {\widetilde{X}}_{\mathcal{l}}W_{fc}^{(\mathcal{l})} + b_{fc}^{(\mathcal{l})} \right);

    U𝓁=dropout(H𝓁Wproj(𝓁)+bproj(𝓁))U_{\mathcal{l}} = dropout\left( H_{\mathcal{l}}W_{proj}^{(\mathcal{l})} + b_{proj}^{(\mathcal{l})} \right);

    X𝓁+1=X′𝓁+U𝓁X_{\mathcal{l} + 1} = {X'}_{\mathcal{l}} + U_{\mathcal{l}}.

    GELU is defined by (x,Φ(x))(x,\Phi(x)), often approximated using tanh.

5.2.3 Output Layer

Final layer normalization and language-model head

Y=LNγf,βf(XL)Y = {LN}_{\gamma_{f},\beta_{f}}(X_{L}),

logits=YWE⊤logits = YW_{E}^{\top}

The lm_head and wte share their weights.

5.2.4 Notation and Typical Shapes

(B)(B) is the batch size, (S)(S) the sequence length, (D)(D) the hidden dimension (768 in GPT-2 small), (H)(H) the head count (12), (Dh=D/H)(D_{h} = D/H) (64) the dimension per head, and (V)(V) the vocabulary size (50,257). The attention tensor has shape [B,H,Sq,Sk]\lbrack B,H,S_{q},S_{k}\rbrack.

Table 5-1. ONNX operators, parameter names, and subgraph patterns. Hugging Face's Conv1D is effectively a linear layer with transposed weight notation and usually lowers to MatMul or Gemm in ONNX. This makes it easy to recognize in attn/c_attn, c_proj, mlp/c_fc, and mlp/c_proj.

Mathematical object Hugging Face weight name (layer 𝓁\mathcal{l}) Typical operator or subgraph
Token embedding (WE)(W_{E}) wte.weight Gather (table lookup) → add wpe
Position embedding wpe.weight Gather → add wte
LN1 (γ,β)(\gamma,\beta) h.𝓁\mathcal{l}.ln_1.(weight | bias) A sequence of ReduceMean/Sub/Pow/…/Div/Mul/Add (or LayerNormalization)
Fused QKV matrix (Wc_attn)(W_{c\_ attn})

h.𝓁\mathcal{l}.attn.c_attn.

(weight | bias)

MatMul | Gemm (producing width 3D in one operation), then Reshape/Split/Transpose
Causal mask

h. 𝓁\mathcal{l}.attn.bias,

h.𝓁\mathcal{l}.attn.masked_bias

Where/Add adds (−104)( - 10^{4}) at the masked positions in the triangular pattern.
Attention output projection (Wc_proj)(W_{c\_ proj})

h. 𝓁\mathcal{l}.attn.c_proj.

(weight | bias)

MatMul | Gemm
LN2 (γ,β)(\gamma,\beta)

h. 𝓁\mathcal{l}.ln_2.

(weight | bias)

As for LN1
MLP intermediate projection (Wfc)(W_{fc})

h. 𝓁\mathcal{l}.mlp.c_fc.

(weight | bias)

MatMul | Gemm+GELU
MLP output projection (Wproj)(W_{proj})

h. 𝓁\mathcal{l}.mlp.c_proj.

(weight | bias)

MatMul | Gemm
Final layer normalization ln_f.(weight | bias) LN subgraph
LM head (weights shared with wte) lm_head.weight == wte.weight MatMul to dimension (V)(V)

Incremental decoding and past/present (KV cache)

5.2.5 A Compact Form Ready for Implementation

Recurrence for a complete layer

X𝓁+1=X𝓁+Attn(LN(X𝓁))⏟h.𝓁.attn+MLP(LN(X𝓁+Attn(⋅)))⏟h.𝓁.mlpX_{\mathcal{l} + 1} = X_{\mathcal{l}} + \underset{\text{h.}\mathcal{l}\text{.attn}}{\underbrace{Attn\left( LN(X_{\mathcal{l}}) \right)}} + \underset{\text{h.}\mathcal{l}\text{.mlp}}{\underbrace{MLP\left( LN(X_{\mathcal{l}} + Attn( \cdot )) \right)}}

The table above gives the names of the linear weights in Attn and MLP. In ONNX, layer normalization is often decomposed into primitives. This exactly matches the pre-LN structure of Block.forward in the Hugging Face source.

ONNX computation graph for the final GPT-2 Transformer block, h.11.

Figure 5-1. ONNX computation graph for the final GPT-2 Transformer block (h.11)

Attention kernel

Attn(Z)=Drop(ConcatHeads(softmax(QK⊤Dh+M)V)Wc_proj+bc_proj),Attn(Z) = Drop\left( ConcatHeads\left( softmax\left( \frac{QK^{\top}}{\sqrt{D_{h}}} + M \right)V \right)W_{c\_ proj} + b_{c\_ proj} \right),

[Q,K,V]=ZWc_attn+bc_attn.\quad\lbrack Q,K,V\rbrack = ZW_{c\_ attn} + b_{c\_ attn}.

The c_attn projection produces width 3D in one pass, followed by Reshape/Split/Transpose. The mask combines attn.bias with the input attention_mask additively.

MLP kernel

MLP(Z)=Drop(GELU(ZWfc+bfc)Wproj+bproj)MLP(Z) = Drop\left( GELU(ZW_{fc} + b_{fc})W_{proj} + b_{proj} \right).

Figure 5-1 uses Netron to visualize the final GPT-2 Transformer block (scope prefix transformer/h.11/...). It shows pre-normalization ln_1, the self-attention subgraph (attn/c_attn for fused QKV and attn/c_proj for projection), and the first residual Add. These are followed by ln_2, the feedforward MLP (mlp/c_fc → gelu → mlp/c_proj), and the second residual Add. On the left, the input comes from the residual output of the preceding layer, h.10. The path ends at the second Add in h.11. These names and this structure agree with Hugging Face's GPT-2 implementation.

5.3 Attention and Its Correspondence to GPT-2 and ONNX

Single-head scaled dot-product self-attention. Given three sets of vectors (tensors):

Q∈ℝB×H×Sq×DhQ \in \mathbb{R}^{B \times H \times S_{q} \times D_{h}},K,V∈ℝB×H×Sk×DhK,V \in \mathbb{R}^{B \times H \times S_{k} \times D_{h}};

Here BB is the batch size, HH the number of heads, SS the sequence length, and DhD_{h} the dimension per head, with D=H⋅DhD = H \cdot D_{h}.

Standard attention is written as

Attn(Q,K,V)=softmax(QK⊤Dh+M)VAttn(Q,K,V) = softmax\left( \frac{QK^{\top}}{\sqrt{D_{h}}} + M \right)V

Here MM combines the causal mask (the lower-triangular mask in autoregressive models) with the optional attention_mask. This is the central operation of the Transformer.

Multi-head attention (MHA) computes each head in parallel, concatenates the results along the channel dimension, and multiplies by the output projection WOW^{O}:

MHA(X)=Concat(Attn(Qi,Ki,Vi))WOMHA(X) = Concat\left( Attn(Q_{i},K_{i},V_{i}) \right)W^{O}

In GPT-2 and ONNX, a single linear layer jointly computes (Q,K,V)(Q,K,V) (see “Fused QKV projection” below). Reshape and Transpose put the result into shape [B,H,S,Dh]\lbrack B,H,S,D_{h}\rbrack for the equation above. Common weight and node names in the exported model include the following.

Fused QKV projection. For each layer input X∈ℝB×S×DX \in \mathbb{R}^{B \times S \times D}:

[Q,K,V]=XWcattn+bcattn,Wcattn∈ℝD×3D\lbrack Q,K,V\rbrack = XW_{c_{attn}} + b_{c_{attn}},\quad W_{c_{attn}} \in \mathbb{R}^{D \times 3D}

In an ONNX graph this usually appears as MatMul/Gemm(+Add) → Reshape/Split/Transpose, corresponding to c_attn above. Concatenating (WQ,WK,WV)(W_{Q},W_{K},W_{V}) horizontally replaces three GEMMs with one and improves efficiency.

KV caching and incremental decoding. At each autoregressive step, only the new token needs its QQ computed. Earlier (K,V)(K,V) are reused and extended along the sequence dimension to produce present.<ℓ>.{key,value} for the next step. The Hugging Face documentation and community use the names past_key_values and present (Hugging Face, 2020).

Standard dense attention has O(S2)O(S^{2}) time and space complexity in the sequence length (the attention matrix has size Sq×SkS_{q} \times S_{k}) (Vaswani et al., 2017). This cost motivated much subsequent research.

5.4 A Brief History: From Translation Alignment to the Dominance of Attention

5.5 Equations and ADT Variant Code for LLM Computation-Graph Nodes

We describe each common LLM graph node in four parts: specification, equations, typical uses in a GPT-2 graph, and correspondence with the F# ADT in AlgebraicCode. The official ONNX operator specification (ONNX Project, n.d.-b) is authoritative. When behavior changes between opsets—for example, the axes attribute in Squeeze v11 becomes a tensor input in v13—the entry identifies the specification to resolve ambiguity. Elementwise operations follow ONNX multidirectional broadcasting rules (ONNX Project, n.d.-a). Examples refer to the GPT-2 ONNX graph visualized in Netron. The nodes fall into seven semantic categories:

  1. Tensor and linear algebra (MatMul, Gemm).

  2. Elementwise algebra (Add, Sub, Mul, Div, Pow, Sqrt).

  3. Reductions and statistics (ReduceMean).

  4. Shapes, layouts, indexing, and types (Reshape, Transpose, Concat, Split, Slice, Gather, Shape, Unsqueeze, Squeeze, Cast).

  5. Constants and tensor generation (Constant, ConstantOfShape, Range).

  6. Conditional selection (Where).

  7. Activations and normalization (Softmax, Gelu, LayerNormalization).

For each operator we give a verifiable mathematical definition and an ADT record type (using NodeBaseInfo and related types), mapping the specification directly to its implementation.

Notation and conventions

5.6 Tensor and Linear Algebra Nodes

5.6.1 MatMul (Matrix Multiplication)

Specification

The behavior matches numpy.matmul, including higher-dimensional batched matrix multiplication over broadcastable batch dimensions. Inputs and output are floating-point or integer tensors. The output has the input dtype. (ONNX)

Equation and shapes. If

A∈ℝ𝐛×M×K,B∈ℝ𝐛′×K×N,A \in \mathbb{R}^{\mathbf{b} \times M \times K},\quad B \in \mathbb{R}^{\mathbf{b}^{\mathbf{'}} \times K \times N},

where the batch shapes 𝐛\mathbf{b} and 𝐛′\mathbf{b}^{\mathbf{'}} support multidirectional broadcasting (take the larger dimension when the other is 1), then

Y=A×B∈ℝbroadcast(𝐛,𝐛′)×M×N.Y = A \times B \in \mathbb{R}^{broadcast(\mathbf{b},\mathbf{b}^{\mathbf{'}}) \times M \times N}.

Use in GPT-2

Computing attention weights and applying them to values

QK⊤∈ℝB×H×Tq×Tk,Softmax(⋅)V∈ℝB×H×Tq×dh.QK^{\top} \in \mathbb{R}^{B \times H \times T_{q} \times T_{k}},\quad Softmax( \cdot )V \in \mathbb{R}^{B \times H \times T_{q} \times d_{h}}.

ADT correspondence and checks (MatMulNode)

type MatMulNode = {
    Base: NodeBaseInfo
    A: string  // First matrix input
    B: string  // Second matrix input
    Y: string  // Matrix product
    Attributes: AttributeADT list
}

5.6.2 Gemm (General Matrix Multiplication)

Semantics

Transpose and scale as specified by the attributes:

A′={transpose(A),if transA≠0A,else,A' = \left\{ \begin{matrix} transpose(A), & \text{if }transA \neq 0 \\ A, & \text{else} \end{matrix} \right.\ ,

B′={transpose(B),transB≠0B,else\quad B' = \left\{ \begin{matrix} transpose(B), & transB \neq 0 \\ B, & \text{else} \end{matrix} \right.\

Y=α(A′B′)+βC,Y = \alpha(A'B') + \beta C,

C is optional and defaults to scalar 00. It must support unidirectional broadcasting to (M,N)(M,N). Both alpha and beta default to 11.

Shapes. If AA has shape (M,K)(M,K) or (K,M)(K,M) and BB has shape (K,N)(K,N) or (N,K)(N,K), then Y∈ℝM×NY \in \mathbb{R}^{M \times N}.

Typical use in GPT-2

Projection layers and MLPs commonly implement a fully connected linear layer with Gemm(A=X, B=W^T, C=b).

ADT checks (GemmNode)

type GemmNode = {
    Base: NodeBaseInfo
    A: string  // First matrix
    B: string  // Second matrix
    C: string  // Bias vector
    Y: string  // Result matrix
    Alpha: float option  // Scale factor alpha (attribute)
    Beta: float option   // Scale factor beta (attribute)
    TransA: bool option  // Whether to transpose A (attribute)
    TransB: bool option  // Whether to transpose B (attribute)
    Attributes: AttributeADT list
}

TransA/TransB determine which dimensions must match for multiplication. C may be omitted, and alpha/beta default to 1. Validate C using ONNX unidirectional broadcasting.

5.7 Elementwise Algebra Nodes

5.7.1 Add, Sub, Mul, and Div (Elementwise Binary Operators)

Specification

These elementwise operations support NumPy-style multidirectional broadcasting. The output has the same numerical dtype as the inputs. From opset 14 onward, these operators also support small integer types. (ONNX) Broadcasting rules. As in NumPy, pad the shorter shape on the left with ones. A dimension of 1 can expand to the other input's corresponding dimension. (ONNX)

Equations for a broadcast output index 𝐢\mathbf{i}:

Add(A,B)[𝐢]=A[𝐢]+B[𝐢],Sub(A,B)[𝐢]=A[𝐢]−B[𝐢],Mul(A,B)[𝐢]=A[𝐢]⋅B[𝐢],Div(A,B)[𝐢]=A[𝐢]⊘B[𝐢].\begin{aligned} Add(A,B)\lbrack\mathbf{i}\rbrack & = A\lbrack\mathbf{i}\rbrack + B\lbrack\mathbf{i}\rbrack, \\ Sub(A,B)\lbrack\mathbf{i}\rbrack & = A\lbrack\mathbf{i}\rbrack - B\lbrack\mathbf{i}\rbrack, \\ Mul(A,B)\lbrack\mathbf{i}\rbrack & = A\lbrack\mathbf{i}\rbrack \cdot B\lbrack\mathbf{i}\rbrack, \\ Div(A,B)\lbrack\mathbf{i}\rbrack & = A\lbrack\mathbf{i}\rbrack \oslash B\lbrack\mathbf{i}\rbrack. \end{aligned}

Use in GPT-2

ADT correspondence and checks (AddNode/SubNode/MulNode/DivNode)

type AddNode = {
    Base: NodeBaseInfo
    A: string  // First addend
    B: string  // Second addend
    C: string  // Sum
    Attributes: AttributeADT list
}

type SubNode = {
    Base: NodeBaseInfo
    A: string  // Minuend
    B: string  // Subtrahend
    C: string  // Difference
    Attributes: AttributeADT list
}

type MulNode = {
    Base: NodeBaseInfo
    A: string  // First factor
    B: string  // Second factor
    C: string  // Product
    Attributes: AttributeADT list
}

type DivNode = {
    Base: NodeBaseInfo
    A: string  // Dividend
    B: string  // Divisor
    C: string  // Quotient
    Attributes: AttributeADT list
}

5.7.2 Pow

Semantics (elementwise, with broadcasting)

z=xy(with NumPy-style multidirectional broadcasting).z = x^{y}\quad(\text{with NumPy-style multidirectional broadcasting}).

Type rules (v15): for X:TX:T and Y:T1Y:T1, the output Z:TZ:T has the same type as the base. The allowed types for T∈{bf16,f64,f32,f16,int32,int64}T \in \{ bf16,f64,f32,f16,int32,int64\} and T1T1 include a wider range of integer and floating-point types.

Typical use in a GPT-2 graph. LayerNorm variance calculations often use a constant exponent Y of 2. Powers can also be computed in preparation for RMSNorm or scaling.

ADT correspondence and implementation notes

type PowNode = {
    Base: NodeBaseInfo
    X: string  // Base
    Y: string  // Exponent
    Z: string  // Power
    Attributes: AttributeADT list
}

Enforce output type = type of X during type checking. Check that broadcasting is valid by aligning and comparing trailing dimensions.

5.7.3 Sqrt

Semantics (elementwise)

y=x=x1/2,if x<0, return NaN (floating point).y = \sqrt{x} = x^{1/2},\quad\text{if }x < 0\text{, return NaN (floating point)}.

Only floating-point types are supported, including bf16, fp16, fp32, and fp64.

Typical use in a GPT-2 graph

Computing the standard deviation in LayerNorm.

ADT correspondence and implementation notes

type SqrtNode = {
    Base: NodeBaseInfo
    X: string  // Input
    Y: string  // Square root
    Attributes: AttributeADT list
}

Require input and output to have the same shape and floating-point dtype. During constant folding, allow Pow(x, 0.5) to be normalized to Sqrt(x).

5.8 Reduction and Statistics Nodes

5.8.1 ReduceMean

Semantics

Take the mean over a given set of axes AA. Let x∈𝕋(s0,…,sr−1)x \in \mathbb{T}^{(s_{0},\ldots,s_{r - 1})}. Then

y[𝐢¬A]=1∏a∈Asa∑𝐣Ax[𝐢¬A,𝐣A],y\lbrack\mathbf{i}_{\neg A}\rbrack = \frac{1}{\prod_{a \in A}^{}s_{a}}\sum_{\mathbf{j}_{A}}^{}x\lbrack\mathbf{i}_{\neg A},\mathbf{j}_{A}\rbrack,

Here 𝐢¬A\mathbf{i}_{\neg A} fixes the indices of the unreduced axes, and 𝐣A\mathbf{j}_{A} ranges over the reduced axes. With keepdims=1, set the size of each reduced dimension to 11. With keepdims=0, remove those dimensions.

Typical use in a GPT-2 graph

Expanding LayerNorm:

μ=ReduceMean(x;,A),σ=ReduceMean!((x−μ)2;A)+ε,\mu = ReduceMean(x;,A),\quad\sigma = \sqrt{ReduceMean!\left( (x - \mu)^{2};A \right) + \varepsilon},

Here A is usually the last dimension or a designated channel dimension.

ADT correspondence and implementation notes

type ReduceMeanNode = {
    Base: NodeBaseInfo
    Data: string  // Input tensor
    Reduced: string  // Reduced tensor
    Axes: int list option  // Reduction axes (attribute)
    KeepDims: bool option  // Whether to retain the dimensions (attribute)
    NoopWithEmptyAxes: bool option  // How to handle empty axes (attribute)
    Attributes: AttributeADT list
}

Static checks: allow negative axes and normalize them to [0,r-1]. When Axes=Unspecified, use NoopWithEmptyAxes to determine whether to reduce over all axes or return the input unchanged.

5.9 Shape, Layout, Indexing, and Type Nodes

5.9.1 Reshape

Specification

The shape input is a 1-D int64 tensor. It can contain -1 at most once for automatic inference and 0 with a meaning determined by allowzero.

Constraint and equation

∏shape(data)=∏shape(reshaped),and#{−1}≤1.\prod shape(\text{data}) = \prod shape(\text{reshaped}),\quad\text{and}\ \#\{ - 1\} \leq 1.

Use in GPT-2

ADT correspondence and checks (ReshapeNode)

type ReshapeNode = {
    Base: NodeBaseInfo
    Data: string  // Input tensor
    Shape: string  // New shape
    Reshaped: string  // Reshaped tensor
    AllowZero: bool option  // Whether to allow zero-sized dimensions (attribute)
    Attributes: AttributeADT list
}

The Shape input must be 1-D int64. Implement -1 inference and allowzero semantics. When allowzero=1, prohibit a shape containing both 0 and -1.

5.9.2 Transpose (Permuting Dimensions)

Semantics

perm is a permutation of the axes. When omitted, it reverses their order, as in numpy.transpose.

Shape. If xx has shape (s0,…,sr−1)(s_{0},\ldots,s_{r - 1}), then Transposeperm(x){Transpose}_{perm}(x) has shape (sperm[0],…,sperm[r−1])(s_{perm\lbrack 0\rbrack},\ldots,s_{perm\lbrack r - 1\rbrack}).

Typical use in GPT-2

Switch between (B,T,H,d)(B,T,H,d) and (B,H,T,d)(B,H,T,d) to match the axis order expected by the attention operator.

ADT checks (TransposeNode)

type TransposeNode = {
    Base: NodeBaseInfo
    Data: string  // Input tensor
    Transposed: string  // Transposed tensor
    Perm: int list option  // Axis permutation (attribute)
    Attributes: AttributeADT list
}

Perm=None reverses the axes. Otherwise, perm must have length equal to the rank and be a permutation of the axes.

5.9.3 Concat (Concatenation)

Specification

Concatenate tensors along axis. Inputs must have identical dimensions everywhere except along axis. Negative indices are allowed: axis∈[-r,r-1].

Equation and shapes. If Xi∈𝕋(s0,…,sâ(i),…,sr−1)X_{i} \in \mathbb{T}^{(s_{0},\ldots,s_{\widehat{a}}^{(i)},\ldots,s_{r - 1})} and sj(i)=sjs_{j}^{(i)} = s_{j} (j≠â)(j \neq \widehat{a}), then

Y=Concata(X1,…,Xm),shape(Y)=(s0,…,∑isâ(i),…,sr−1).Y = {Concat}_{a}(X_{1},\ldots,X_{m}),\quad shape(Y) = (s_{0},\ldots,\sum_{i}^{}s_{\widehat{a}}^{(i)},\ldots,s_{r - 1}).

Use in GPT-2

Split the width-[3dh]\lbrack 3d_{h}\rbrack output of a linear layer along its last dimension into Q|K|VQ|K|V, or concatenate the head outputs along the head or hidden dimension.

ADT correspondence and checks (ConcatNode)

type ConcatNode = {
    Base: NodeBaseInfo
    Inputs: string list  // List of tensors to concatenate (inputs...)
    ConcatResult: string  // Concatenated tensor
    Axis: int  // Concatenation axis (attribute)
    Attributes: AttributeADT list
}

5.9.4 Split

Specification and opset changes

Split a tensor into segments along an axis. In v11, split was an INTS attribute. From v13, it became an optional second input (1-D int64). v18 added the num_outputs attribute, mutually exclusive with the split input. When specified, the split is uniform unless the dimension is not divisible by the count, in which case the last segment is shorter as described in the specification.

Mathematical formulation. Let x∈𝕋(s0,…,sr−1)x \in \mathbb{T}^{(s_{0},\ldots,s_{r - 1})} and normalize axis a∈[−r,r−1]a \in \lbrack - r,r - 1\rbrack to â\widehat{a}.

Typical use in GPT-2

ADT correspondence and implementation notes

type SplitNode = {
    Base: NodeBaseInfo
    Input: string  // Input tensor
    Split: string option  // Split specification
    Outputs: string list  // List of output tensors (outputs...)
    Axis: int option  // Split axis (attribute)
    NumOutputs: int option  // Number of outputs (attribute)
    Attributes: AttributeADT list
}

5.9.5 Slice

Semantics (starts, ends, axes, and steps are inputs from v10 onward)

For each axis ii, compute the effective triple (start[i],end[i],step[i])(start\lbrack i\rbrack,end\lbrack i\rbrack,step\lbrack i\rbrack). The defaults are axes=[0..r-1] and steps=1. Negative axes and negative start/end indices are allowed, counting from the end. A step cannot be zero. The end index is exclusive.

Shapes and indexing. Slicing and strides follow NumPy conventions. The specification gives clamping rules for negative and out-of-range indices and recommends INT_MAX/INT_MIN for the appropriate direction when the dimension length is unknown.

Typical use in GPT-2

ADT checks (SliceNode)

type SliceNode = {
    Base: NodeBaseInfo
    Data: string  // Input tensor
    Starts: string  // Starting indices
    Ends: string  // Ending indices
    Axes: string option  // Axes
    Steps: string option  // Step sizes
    Output: string  // Slice result
    Attributes: AttributeADT list
}

Starts/Ends/Steps/Axes must be 1-D int32 or int64 tensors. starts and ends must have equal length, as must steps and axes when supplied. Require steps!=0 and normalize axes to [0,r-1].

5.9.6 Gather (Indexing Along One Axis)

Semantics

Select slices along axis (default 0) using indices. If data has rank rr and indices has rank qq, the output rank is =q+(r−1)= q + (r - 1). Indices must lie in [−s,s−1]\lbrack - s,s - 1\rbrack and may be negative. (ONNX)

Shape. Replace the selected axis with the shape of indices, leaving all other axes in their original order. The documentation tabulates several examples.

Inputs

Output shape

shape(Y)=(s0,…,sâ−1,t0,…,tq−1,sâ+1,…,sr−1).shape(Y) = \left( s_{0},\ldots,s_{\widehat{a} - 1},\ t_{0},\ldots,t_{q - 1},\ s_{\widehat{a} + 1},\ldots,s_{r - 1} \right).

Elementwise definition. For any

(i0,…,iâ−1)∈∏j<â[0,sj),(j0,…,jq−1)∈∏𝓁<q[0,t𝓁),(iâ+1,…,ir−1)∈∏j>â[0,sj),(i_{0},\ldots,i_{\widehat{a} - 1}) \in \prod_{j < \widehat{a}}^{}\lbrack 0,s_{j}),\quad(j_{0},\ldots,j_{q - 1}) \in \prod_{\mathcal{l} < q}^{}\lbrack 0,t_{\mathcal{l}}),\quad(i_{\widehat{a} + 1},\ldots,i_{r - 1}) \in \prod_{j > \widehat{a}}^{}\lbrack 0,s_{j}),

let

k=ν(I[j0,…,jq−1];sâ),k = \nu\left( I\lbrack j_{0},\ldots,j_{q - 1}\rbrack;\ s_{\widehat{a}} \right),

Then

Y[i0,…,iâ−1,j0,…,jq−1,iâ+1,…,ir−1]=X[i0,…,iâ−1,k,iâ+1,…,ir−1].Y\lbrack i_{0},\ldots,i_{\widehat{a} - 1},\ j_{0},\ldots,j_{q - 1},\ i_{\widehat{a} + 1},\ldots,i_{r - 1}\rbrack = X\lbrack i_{0},\ldots,i_{\widehat{a} - 1},\ k,\ i_{\widehat{a} + 1},\ldots,i_{r - 1}\rbrack.

In effect, the shape of indices replaces the selected axis. All other axes are preserved. Negative indices are normalized by ν(⋅;sâ)\nu( \cdot ;s_{\widehat{a}}).

Typical use in GPT-2

ADT checks (GatherNode)

type GatherNode = {
    Base: NodeBaseInfo
    Data: string  // Input tensor
    Indices: string  // Indices
    Output: string  // Gathered result
    Axis: int option  // Gather axis (attribute)
    Attributes: AttributeADT list
}

Axis defaults to 0 and may be negative. Indices may have any rank and must be int32 or int64. Out-of-bounds indices are errors.

5.9.7 Shape (Returning a Shape Vector)

Semantics

The output is a 1-D int64 tensor containing the input dimension sizes. Optional start/end attributes slice the shape vector. The end is exclusive, negative axes are supported, and out-of-range bounds are clamped to [0,r]\lbrack 0,r\rbrack. If start>end, the result is empty.

Basic function

Shape(X)=[s0,s1,…,sr−1]∈ℤ≥0(r).Shape(X) = \left\lbrack s_{0},\ s_{1},\ \ldots,\ s_{r - 1} \right\rbrack \in \mathbb{Z}_{\geq 0}^{(r)}.

Subinterval with bounds start,end\text{start},\text{end} (a slice of the shape vector with exclusive endpoint end\text{end}):

Typical use in GPT-2

Together with Gather, Unsqueeze, Concat, and Reshape, this forms a shape subgraph that drives reshaping or broadcasting.

ADT checks (ShapeNode)

type ShapeNode = {
    Base: NodeBaseInfo
    Data: string  // Input tensor
    Shape: string  // Shape output
    Start: int option  // Starting axis (attribute)
    End: int option    // Ending axis (attribute)
    Attributes: AttributeADT list
}

The output dtype is always int64. Start and End may be negative. Clamp out-of-range bounds and handle an empty shape.

5.9.8 Unsqueeze (Inserting Dimensions of Size One at Specified Axes)

Semantics and version differences

Insert dimensions of size 1 at the positions specified by axes. In v11, axes is an attribute. From v13 onward, it is a required input (1-D int64). The axes must be distinct. The output rank equals the input rank plus |axes|. Negative axes are interpreted relative to the output rank.

Shape example. data:[3,4,5], axes=[0,4] → [1,3,4,5,1].

Inputs

Normalization to output rank. The output rank is r′=r+mr' = r + m. For each a∈Aa \in A,

â={a,a≥0,r′+a,a<0,with 0≤â<r′.\widehat{a} = \left\{ \begin{matrix} a, & a \geq 0, \\ r' + a, & a < 0, \end{matrix} \right.\ \quad\text{with }0 \leq \widehat{a} < r'.

Write Â={â∣a∈A}\widehat{A} = \{\widehat{a} \mid a \in A\} and denote its elements in ascending order by â(1)<⋯<â(m){\widehat{a}}_{(1)} < \cdots < {\widehat{a}}_{(m)}.

Output shape. Insert ones at the positions in Â\widehat{A}:

shape(Y)=𝐬′=(s′0,…,s′r′−1),s′j={1,j∈Â,sρ(j),j∉Â,shape(Y) = \mathbf{s}' = ({s'}_{0},\ldots,{s'}_{r' - 1}),\quad{s'}_{j} = \left\{ \begin{matrix} 1, & j \in \widehat{A}, \\ s_{\rho(j)}, & j \notin \widehat{A}, \end{matrix} \right.\

Here ρ(⋅)\rho( \cdot ) maps output coordinates back to input coordinates:

ρ(j)=j−#{â∈Â∣â<j}.\rho(j) = j - \#\{\widehat{a} \in \widehat{A} \mid \widehat{a} < j\}.

Each insertion shifts subsequent indices one place to the right.

Elementwise correspondence (index injection). For every (i0,…,ir−1)∈∏k<r[0,sk)(i_{0},\ldots,i_{r - 1}) \in \prod_{k < r}^{}\lbrack 0,s_{k}), define the injection

ϕ(i0,…,ir−1)=(j0,…,jr′−1),j𝓁={0,𝓁∈Â,iρ(𝓁),𝓁∉Â,\phi(i_{0},\ldots,i_{r - 1}) = (j_{0},\ldots,j_{r' - 1}),\quad j_{\mathcal{l}} = \left\{ \begin{matrix} 0, & \mathcal{l} \in \widehat{A}, \\ i_{\rho(\mathcal{l})}, & \mathcal{l} \notin \widehat{A}, \end{matrix} \right.\

Then

Y[ϕ(i0,…,ir−1)]=X[i0,…,ir−1],Y\lbrack\phi(i_{0},\ldots,i_{r - 1})\rbrack = X\lbrack i_{0},\ldots,i_{r - 1}\rbrack,

Every index along an inserted dimension of size one coincides with its sole position.

In short, axes are interpreted relative to output rank, may be negative, and must be distinct. The operation injects input indices into a higher-rank index space, fixing each inserted position to 0 (length 1).

Typical use in GPT-2

Increase the rank of a scalar or vector for broadcasting, for instance by turning scalar ϵ\epsilon into [1,1,…,1]\lbrack 1,1,\ldots,1\rbrack.

ADT checks (UnsqueezeNode)

type UnsqueezeNode = {
    Base: NodeBaseInfo
    Data: string  // Input tensor
    AxesInput: string option  // Input tensor specifying the axes to insert
    AxesAttr: int64 list option  // Axes supplied directly as an attribute
    Expanded: string  // Expanded tensor
    Attributes: AttributeADT list
}

Support either AxesInput (v13+) or AxesAttr (v11). Reject a specification that supplies both.

5.9.9 Squeeze (Removing Axes of Size One)

Specification and opset differences

Purpose. Remove dimensions of size 11. If axes is given, remove only the specified axes of size 11. It is an error if such an axis has size other than 11. From opset 13 onward, axes is an optional second input (a 1-D int64 tensor). Earlier versions, including v1 and v11, use an axes attribute. Omitting axes removes all dimensions of size one.

Mathematical definition

Given x∈𝕋𝐬x \in \mathbb{T}^{\mathbf{s}}:

Properties on the domain of definition

Typical uses in a GPT-2 graph

ADT correspondence

type AxesSpec =
  | AllImplicit                // No axes provided: remove all size-one dimensions
  | Attr of int list           // opset <= 12: axes from the attribute
  | Input of string            // opset >= 13: name of the axes tensor (1-D int64)

type SqueezeNode = {
  Base       : NodeBaseInfo
  Data       : string          // Input tensor name
  Axes       : AxesSpec
  Squeezed   : string          // Output tensor name
  Opset      : int option
  Attributes : AttributeADT list
}

Implementation identities and assertions for static checking and simplification

5.9.10 Cast (Data Type Conversion)

Specification

Mathematical formulation

Let CT1→T2C_{T_{1} \rightarrow T_{2}} be the elementwise conversion function, including rounding, truncation, and clamping. Then

CastT2(x)=reshape−1(CT1→T2(vec(x))){Cast}_{T_{2}}(x) = {reshape}^{- 1}\left( C_{T_{1} \rightarrow T_{2}}\left( vec(x) \right) \right),

shape(CastT2(x))=shape(x).shape({Cast}_{T_{2}}(x)) = shape(x).

For a float8 target with saturate=1, there is a threshold mmaxm_{\max} such that

C*→f8(u)={clip(u,−mmax,mmax) then round as specified,general caseapply the tabulated rules to {±∞,NaN,±0},special valuesC_{* \rightarrow f8}(u) = \left\{ \begin{matrix} clip(u, - m_{\max},m_{\max})\text{ }\text{then round as specified}, & \text{general case} \\ \text{apply the tabulated rules to}\text{ }\{ \pm \infty,NaN, \pm 0\}, & \text{special values} \end{matrix} \right.\

Note. The composition law for casts can fail: error and clamping in two successive casts can differ from a single direct cast.

Typical uses in a GPT-2 graph

ADT correspondence

type CastNode = {
    Base: NodeBaseInfo
    Input: string  // Input tensor
    Output: string  // Converted tensor
    To: ACNN.Abstract.DType  // Target data type (attribute)
    Attributes: AttributeADT list
}

When building or validating the graph, check the following:

  1. dtype(Output)=To and shape(Output)=shape(Input).

  2. If To is in the float8 family, allow saturate/round_mode, which may be included in Attributes.

  3. Reject complex input types.

Implementation identities and assertions for static checking and simplification

5.10 Constant and Tensor Generation Nodes

5.10.1 Constant (Constant Tensor)

Specification

Mathematical formulation

Constantθ()=tensor constructed from θ,{Constant}_{\theta}() = \text{tensor constructed from }\theta,

Here θ\theta is the single attribute chosen from those allowed, for example value for a whole tensor or value_float for a scalar.

Typical uses in a GPT-2 graph

ADT correspondence

type ConstantNode = {
    Base: NodeBaseInfo
    Output: string  // Constant tensor
    Value: obj option  // Constant value (attribute)
    ValueFloat: float option  // Floating-point constant (attribute)
    ValueInt: int option      // Integer constant (attribute)
    Attributes: AttributeADT list
}

At validation time or runtime, enforce mutual exclusivity with exactlyOne(Value, ValueFloat, ValueInt, …), then derive dtype(Output) and shape(Output). Extend the ADT with value_strings/value_ints/value_floats where the 1-D cases are needed.

Implementation identities and assertions for static checking and simplification

Constant folding. Constants passed through a chain of pure operators such as Add/Mul can be folded at compile time. A shape pipeline such as Constant → (Concat/Gather/Unsqueeze) can be evaluated in advance.

5.10.2 ConstantOfShape

Specification

Mathematical formulation

If the input shape is 𝐬=(s0,…,sr−1)\mathbf{s} = (s_{0},\ldots,s_{r - 1}) and the attribute supplies the scalar vv (or the default 00), then

y[i0,…,ir−1]≡v,0≤ik<sk.y\lbrack i_{0},\ldots,i_{r - 1}\rbrack \equiv v,\quad 0 \leq i_{k} < s_{k}.

Typical use in GPT-2

Construct a tensor filled with zeros or another constant for a mask, an ϵ\epsilon padding value, or a shape-driven operation combined with Expand or Where.

ADT correspondence and implementation notes

type ConstantOfShapeNode = {
    Base: NodeBaseInfo
    Input: string  // Shape tensor
    Output: string  // Output tensor
    Value: obj option  // Fill value (attribute)
    Attributes: AttributeADT list
}

Static checks: every entry of the shape vector must be nonnegative. When Value=None, infer dtype=Float32 and value=0. (ONNX)

5.10.3 Range

Semantics (from opset 11). The inputs start, limit, and delta are scalars of the same type TT. The output is a 1-D tensor. Its number of elements is

n:=max⁡(⌈limit−startdelta⌉,0),yi:=start+i⋅delta,i=0,…,n−1.n: = \max\left( \left\lceil \frac{\text{limit} - \text{start}}{\text{delta}} \right\rceil,\, 0 \right),\quad\quad y_{i}: = \text{start} + i \cdot \text{delta},\quad i = 0,\ldots,n - 1.

The upper bound is exclusive. If the step points away from the interval, n=0n = 0. The specification uses delta as a divisor, so implementations require δ≠0\delta \neq 0, a constraint implied by the formula and function body.

Typical use in a GPT-2 graph. Rare in standard GPT-2 exports, Range sometimes appears in function expansions such as RMSNorm or test models, or in shape construction, to generate evenly spaced indices.

ADT correspondence

type RangeNode = {
    Base: NodeBaseInfo
    Start: string  // Starting value
    Limit: string  // Exclusive limit
    Delta: string  // Step size
    Output: string  // Range tensor
    Attributes: AttributeADT list
}

When building or checking the graph, assert the following:

  1. Start, Limit, and Delta are all scalars (rank=0).

  2. Their dtypes match and belong to {float,double,int16,int32,int64}.

  3. Delta ≠ 0;

  4. Output is 1-D, and its length can be inferred statically from the equation above.

5.11 Conditional Selection Nodes

5.11.1 Where

Specification

Elementwise ternary selection: condition is bool. NumPy-style multidirectional broadcasting gives the output the broadcast shape of condition, X, and Y. X, Y, and the output share a type. (ONNX)

Mathematical formulation

For each output index 𝐢\mathbf{i} after broadcasting,

Where(c,x,y)[𝐢]={x[𝐢],c[𝐢]=true,y[𝐢],c[𝐢]=false.Where(c,x,y)\lbrack\mathbf{i}\rbrack = \left\{ \begin{matrix} x\lbrack\mathbf{i}\rbrack, & c\lbrack\mathbf{i}\rbrack = true, \\ y\lbrack\mathbf{i}\rbrack, & c\lbrack\mathbf{i}\rbrack = false. \end{matrix} \right.\

For numerical types this can also be written as y+𝟏c⊙(x−y)y + \mathbf{1}_{c} \odot (x - y), an equivalent expression for derivation that leaves the specification unchanged.

Typical use in GPT-2

ADT correspondence and implementation notes

type WhereNode = {
    Base: NodeBaseInfo
    Condition: string  // Condition tensor
    X: string  // Tensor selected when true
    Y: string  // Tensor selected when false
    Output: string  // Selection result
    Attributes: AttributeADT list
}

Check that dtype(Condition)=bool, broadcast(X,Y,Condition) is valid, and dtype(Output)=dtype(X)=dtype(Y).

5.12 Activation and Normalization Nodes

5.12.1 Softmax

Specification and opset changes

Mathematical formulation

Along axis aa (normalized to â\widehat{a}), fix all other indices 𝐢¬a\mathbf{i}_{\neg a}:

Softmax(x)[𝐢¬a,j]=exp⁡(x[𝐢¬a,j])∑texp⁡(x[𝐢¬a,t]).Softmax(x)\lbrack\mathbf{i}_{\neg a},j\rbrack = \frac{\exp\left( x\lbrack\mathbf{i}_{\neg a},j\rbrack \right)}{\sum_{t}^{}\exp\left( x\lbrack\mathbf{i}_{\neg a},t\rbrack \right)}.

Implementations often use x↦x−max⁡txx \mapsto x - \max_{t}x for numerical stability. It is mathematically equivalent to the equation above and is optional under the specification.

Typical use in GPT-2

Apply softmax to the attention score matrix along its last dimension, the sequence of keys for each query: axis=-1.

ADT correspondence and implementation notes

type SoftmaxNode = {
    Base: NodeBaseInfo
    Input: string  // Input tensor
    Output: string  // Softmax output
    Axis: int option  // Axis of computation (attribute)
    Attributes: AttributeADT list
}

Three useful properties of Softmax

Common questions

A miniature worked example

Raw scores: [2,1,0]\lbrack 2,\ 1,\ 0\rbrack. Subtract the maximum: [0,−1,−2]\lbrack 0,\ - 1,\ - 2\rbrack. Exponentiate: [1,e−1,e−2]≈[1,0.3679,0.1353]\lbrack 1,\ e^{- 1},\ e^{- 2}\rbrack \approx \lbrack 1,0.3679,0.1353\rbrack. Normalize: [0.665,0.245,0.090]\lbrack 0.665,\ 0.245,\ 0.090\rbrack. The first entry's share is amplified exponentially, but remains below 100%, leaving some room to explore the other choices.

Practical tips

Remember Softmax as exponential amplification, normalization to 100%, shift invariance, and adjustable temperature.

5.12.2 GELU

Semantics and equations (elementwise)

Exact form (default):

y=12x(1+erf(x/2)).y = \frac{1}{2}x\left( 1 + erf(x/\sqrt{2}) \right).

If approximate="tanh", use the fast approximation:

y=12x(1+tanh(2/π(x+0.044715x3))).y = \frac{1}{2}x\left( 1 + tanh\left( \sqrt{2/\pi}(x + 0.044715x^{3}) \right) \right).

The approximate attribute accepts "none" (default) or "tanh". Input and output share a floating-point type (bf16/f16/f32/f64). This operator is available from opset 20.

Typical use in GPT-2

FFN (MLP) activation: Gemm → Add → Gelu → Gemm. Many exports use the tanh approximation for speed. (ONNX)

ADT correspondence and recommendations

type GeluNode = {
    Base: NodeBaseInfo
    X: string  // Input tensor
    Y: string  // GELU activation output
    Approximate: string option  // Approximation method (attribute)
    Attributes: AttributeADT list
}

5.12.3 LayerNormalization

Two-stage definition and equations

The normalized subspace runs from axis to the last dimension. Let normalized_axes = [axis, …, rank(X)-1]. The first stage standardizes:

μ=ReduceMean(X;normalized_axes),D=X−μ,Var=ReduceMean(D⊙D;normalized_axes),InvStdDev=(Var+ε)−1/2,Normalized=D⊙InvStdDev.\begin{aligned} \mu & = ReduceMean(X;\,\text{normalized\_axes}), \\ D & = X - \mu,\quad Var = ReduceMean(D \odot D;\,\text{normalized\_axes}), \\ InvStdDev & = (Var + \varepsilon)^{- 1/2}, \\ Normalized & = D \odot InvStdDev. \end{aligned}

The second stage is an affine transformation, broadcast to give the same output shape as X:

Y=Normalized⊙Scale+B.Y = Normalized \odot Scale + B.

Optional outputs are Mean = μ\mu and InvStdDev. Their shapes replace the normalized dimensions with 11, for example [d0,…,daxis−1,1,…,1]\lbrack d_{0},\ldots,d_{axis - 1},1,\ldots,1\rbrack. Attributes. axis defaults to (−1)( - 1), epsilon to 1e−51e - 5. stash_type (default 1) specifies the precision of the mean, inverse standard deviation, and first-stage computation. For example, stash_type=1 requires the first stage to compute in fp32. Type constraints: the inputs and Y are floating point (bf16/f16/f32/f64). Mean/InvStdDev allow {bf16, f32}. Scale and B are applied with unidirectional broadcasting. This operator is available from opset 17.

Typical use in GPT-2. axis=-1 normalizes along the last dimension, epsilon≈1e-5, and the final dimension of Scale/B matches the hidden dimension and broadcasts to X.

ADT correspondence and recommendations

type LayerNormalizationNode = {
    Base: NodeBaseInfo
    X: string  // Input tensor
    Scale: string  // Scale parameter
    B: string  // Bias parameter
    Y: string  // Normalized output
    Mean: string option  // Mean output
    InvStdDev: string option  // Inverse standard deviation output
    Axis: int option  // Normalization axis (attribute)
    Epsilon: float option  // Small value to prevent division by zero (attribute)
    Stash_type: int option  // Intermediate-value type (attribute)
    Attributes: AttributeADT list
}

Static checks

  1. Scale and B must support unidirectional broadcasting to X.

  2. The shape of Mean/InvStdDev replaces the normalized dimensions with 11.

  3. dtype(X)=dtype(Y)∈{bf16,f16,f32,f64},dtype(Mean)=dtype(InvStdDev)∈{bf16,f32}.

5.13 Building the NodeADT Type by Composition in Place of Object Inheritance

Modern deep learning frameworks often create computation-graph nodes through object inheritance. This design makes extension straightforward but can also result in deep class hierarchies and unnecessary complexity. Here we use algebraic data types (ADTs) in place of traditional inheritance to give graph nodes a more concise and flexible representation.

In this implementation, NodeADT represents every kind of computation-graph node, including tensor operations, arithmetic operations, and shape transformations. Each node kind is an ADT variant. All variants share the common base information in NodeBaseInfo, providing a uniform structure.

// Union type representing all supported node types
type NodeADT =
    | MatMul of MatMulNode
    | Concat of ConcatNode
    | Reshape of ReshapeNode
    | Add of AddNode
    | Sub of SubNode
    | Mul of MulNode
    | Div of DivNode
    | Gemm of GemmNode
    | Transpose of TransposeNode
    | Slice of SliceNode
    | Gather of GatherNode
    | Shape of ShapeNode
    | Unsqueeze of UnsqueezeNode
    | Squeeze of SqueezeNode
    | Cast of CastNode
    | Constant of ConstantNode
    | Range of RangeNode
    | ReduceMean of ReduceMeanNode
    | Pow of PowNode
    | Sqrt of SqrtNode
    | Split of SplitNode
    | ConstantOfShape of ConstantOfShapeNode
    | Where of WhereNode
    | Softmax of SoftmaxNode
    | Gelu of GeluNode
    | LayerNormalization of LayerNormalizationNode
    | Generic of {| // For operator types not explicitly defined
        Base: NodeBaseInfo
        OpType: string
        Inputs: string list
        Outputs: string list
        Attributes: AttributeADT list
      |}

With object inheritance, each computation becomes a subclass of Node, and inheritance provides polymorphism. With an ADT, distinct variants represent the different nodes. Each variant carries only its own data structure and operations and inherits no properties from other types. This reduces class complexity, improves expressiveness, and avoids a web of inheritance relationships that can be difficult to maintain.

This section used composition of ADTs to represent graph nodes directly and concisely. Avoiding the machinery of object inheritance makes node types easier and more flexible to extend. This follows the approach to Algebraic Code design discussed in §3.4, with its emphasis on structure and higher-order composition.

5.14 Concluding Remarks

The method throughout the chapter is abstraction → alignment → lowering. Begin with a mathematical or operator-level abstraction, align it with the concrete GPT-2/ONNX graph, and then use a profile and backend kernels to lower and optimize it.

CHAPTER 6

Implementing Automatic Differentiation for Deep Neural Networks

This chapter introduces the established and widely used theory of automatic differentiation and implements it in Algebraic Code, primarily with variants.

Machine learning uses data to select and train models that perform well on unseen examples. We supply data and a learnable rule (the model), define a loss function that measures performance, and train the model to reduce that loss. Deep learning (Goodfellow et al., 2016) is a branch of machine learning that uses multilayer neural networks to learn successive levels of representation, reducing the need for hand-designed features. Optimization drives training. At each iteration, the model's performance on a small batch of data guides a parameter adjustment in a direction that reduces loss. Automatic differentiation (AD) provides the gradient used to find this descent direction. It decomposes a computation into primitive operations and applies the chain rule to obtain gradients automatically, accurately, and efficiently. Deep learning generally uses reverse mode (VJP) to obtain update signals for all parameters in one pass. AD supplies gradients, the optimizer uses them to update parameters, and deep learning trains a network through many such updates, all within the broader field of machine learning.

The literature distinguishes four broad approaches to computing derivatives in programs (Baydin et al., 2018):

  1. Manually derive and code the derivatives.

  2. Numerical differentiation using finite differences.

  3. Symbolic differentiation using a computer algebra system (CAS).

  4. Automatic or algorithmic differentiation (AD).

AD became the prevailing approach because it combines correctness with time efficiency. It computes gradients accurate to machine precision at the same order of complexity as the forward program, without explicitly constructing a Jacobian. In a deep learning framework, AD connects the forward computation to the optimizer's update.

Automatic differentiation, particularly reverse-mode VJP, is central to a deep learning framework's ability to train models. It automatically and accurately converts a network's forward computation into gradients that optimizers such as SGD and Adam use to update large numbers of parameters. Training networks at modern scales would be almost impractical without AD. Frameworks also rely on efficient tensor operators and kernels, graph compilation and scheduling, memory management and numerical stability, distributed parallelism and device management, and data pipelines (Elliott, 2018; Pearlmutter & Siskind, 2008).

Table 6-1. Comparison of differentiation methods

Method Typical difficulty Suitable applications
Manual differentiation High maintenance cost: changing the model means changing its derivative. Small, fixed formulas or heavily hand-tuned implementations
Finite differences (forward or central) Rounding error and very slow computation in high dimensions Gradient checking and rough estimates for black-box functions
Symbolic differentiation Difficult control flow and data dependencies; large generated programs Algebraic derivation and closed-form analysis
Automatic differentiation (AD) Requires runtime or compile-time transformations and a library of rules The default for modern deep learning and differentiable programming

Implementing AD in Algebraic Code establishes a one-to-one correspondence between program structure and mathematical formulas. We concentrate on the principles of AD and practical computational techniques. The chapter includes many formulas for use in implementations, without pursuing every derivation, formal proof, or purely mathematical question.

6.1 Terminology: Analytical and Geometric Perspectives

Early AD research, including work by Griewank and Walther (Griewank et al., 2012; Griewank & Walther, 2008), drew on the language of numerical differentiation and differential geometry. Geometric terminology has persisted in the literature: pushforward and pullback are a natural pair of names for the JVP and VJP. Deep learning increasingly deals with non-Euclidean structures in graph neural networks, manifold embeddings, and group convolutions. Two theoretical languages are therefore common when implementing AD for deep networks. They describe the same underlying operations at different levels of abstraction.

6.1.1 The Perspective of Mathematical Analysis (Default)

6.1.2 The Differential-Geometric Perspective: Manifolds

In Euclidean space, Tₓℝ² can be identified with ℝ², and a tangent vector is a two-dimensional direction or velocity. At the same point,

Txℝ2≅ℝ2T_{x}\mathbb{R}^{2} \cong \mathbb{R}^{2}.

A position vector x and its time derivative v.

Figure 6-1. A point in ℝ2\mathbb{R}^{2}, its tangent space, and a tangent vector.

The Jacobian maps a tangent vector from input space to output space.

Figure 6-2. Geometric interpretation of the JVP. Given a point x and an input direction v, push the direction forward to obtain the instantaneous direction of change at the output, ẏ=Jf(x)v\dot{y} = J_{f}(x)v.

Table 6-2. Terminology and notation used in this book

Concept Analytical perspective (default notation) Geometric perspective
Tangent vector v∈ℝnv \in \mathbb{R}^{n} (also written ẋ\dot{x}) ẋ∈TxM\dot{x} \in T_{x}M
Covector / upstream gradient y‾∈ℝm\bar{y} \in \mathbb{R}^{m} y‾∈Tf(x)*N\bar{y} \in T_{f(x)}^{*}N
JVP JVPf(x;v)=Jf(x)v{JVP}_{f}(x;v) = J_{f}(x)v dfx(ẋ)df_{x}(\dot{x})
VJP VJPf(x;y‾)=Jf(x)⊤y‾{VJP}_{f}(x;\bar{y}) = J_{f}(x)^{\top}\bar{y} dfx*(y‾)df_{x}^{*}(\bar{y})
Duality identity ⟨Jv,y‾⟩=⟨v,J⊤y‾⟩\langle Jv,\bar{y}\rangle = \langle v,J^{\top}\bar{y}\rangle ⟨dfx(ẋ),y‾⟩=⟨ẋ,dfx*(y‾)⟩\langle df_{x}(\dot{x}),\bar{y}\rangle = \langle\dot{x},df_{x}^{*}(\bar{y})\rangle

This chapter primarily uses ℝn\mathbb{R}^{n} notation, with a dot ̇\dot{} denoting a tangent vector and a bar ‾\bar{} denoting a covector. Batch examples are stacked in columns by default. We use manifold terminology when the geometric meaning matters, for instance for pushforwards, pullbacks, or manifold parameterizations. This keeps the notation close to common engineering practice and permits extension to more general settings.

6.2 Machine Learning Methods

In supervised learning and most deep learning, we treat model parameters θ\theta as variables and solve for them by optimizing an objective (risk or loss). AD supplies the gradients via VJP/JVP, and an optimizer such as SGD or Adam updates the variables. Treating parameters as variables and minimizing loss is the most common operational principle in practical machine learning, particularly deep learning. The broader field also includes probabilistic inference, sequential decision-making, and nonparametric methods that go beyond parameter optimization.

6.2.1 Empirical Risk Minimization (ERM): The Baseline in Deep Learning

Model the problem as fθ:ℝn→ℝmf_{\theta}:\mathbb{R}^{n} \rightarrow \mathbb{R}^{m}. Given a training set {(xi,yi)}i=1N\{(x_{i},y_{i})\}_{i = 1}^{N}, define the following objective, optionally with regularization:

θ⋆=argminθ︸1N∑i=1N𝓁(fθ(xi),yi)empirical loss L(θ)+λΩ(θ).\theta^{\star} = arg\min_{\theta}\mspace{6mu}\underset{\text{empirical loss }L(\theta)}{\overset{\frac{1}{N}\sum_{i = 1}^{N}\mathcal{l}\left( f_{\theta}(x_{i}),y_{i} \right)}{︸}}\mspace{6mu} + \mspace{6mu}\lambda\,\Omega(\theta).

A first-order method updates the parameters as follows:

θt+1=θt−ηt∇θL(θt),\theta_{t + 1} = \theta_{t} - \eta_{t}\,\nabla_{\theta}L(\theta_{t}),

∇θL\nabla_{\theta}L\ is computed efficiently with a VJP or backpropagation.

6.2.2 The Bayesian Perspective: Learning as Inference Beyond Optimization

Treat the parameters as random variables with prior p(θ)p(\theta) and likelihood p(D∣θ)p(D \mid \theta). Learning becomes posterior inference:

p(θ∣D)∝p(D∣θ)p(θ).p(\theta \mid D) \propto p(D \mid \theta)\, p(\theta).

Seeking only a point estimate (MAP) brings us back to optimization:

θ⋆=argmaxθ[logp(D∣θ)+logp(θ)]=argminθ[−logp(D∣θ)−logp(θ)].\theta^{\star} = arg\max_{\theta}\left\lbrack \log p(D \mid \theta) + logp(\theta) \right\rbrack = arg\min_{\theta}\left\lbrack - \log p(D \mid \theta) - logp(\theta) \right\rbrack.

Full Bayesian inference involves integration or sampling. Variational inference introduces a distribution qϕ(θ)q_{\phi}(\theta) and optimizes ϕ\phi to approximate the posterior by optimizing the evidence lower bound (ELBO).

6.2.3 Reinforcement Learning: Optimizing Expected Return

Learn a policy πθ\pi_{\theta} that maximizes the expected return:

J(θ)=𝔼τ∼πθ[∑t=0∞γtrt],J(\theta) = \mathbb{E}_{\tau \sim \pi_{\theta}}\left\lbrack \sum_{t = 0}^{\infty}\gamma^{t}r_{t} \right\rbrack,\quad\quad

∇θJ(θ)=𝔼[∑t∇θlogπθ(at∣st)Gt].\nabla_{\theta}J(\theta\mathbb{) = E}\left\lbrack \sum_{t}^{}\nabla_{\theta}\log\pi_{\theta}(a_{t} \mid s_{t})\, G_{t} \right\rbrack.

This remains an optimization problem, now with an expectation over sequential decisions as the objective.

6.2.4 Nonparametric Methods and Other Algorithms

6.2.5 Connections to VJPs and JVPs

Most deep learning fits the paradigm of optimizing over θ\theta, where the gradient provides the central information:

∇θL(θ)=(∂fθ∂θ)⊤∂L∂y\nabla_{\theta}L(\theta) = (\frac{\partial f_{\theta}}{\partial\theta})^{\top}\frac{\partial L}{\partial y}\quad

6.3 Introducing Batches

6.3.1 Minibatches

6.3.2 Vectorization and Shapes

6.4 Computational Techniques for JVPs and VJPs

6.4.1 Scalar Outputs (𝐦=𝟏\mathbf{m}\mathbf{=}\mathbf{1}) and Gradients

If y=f(x)∈ℝy = f(x\mathbb{) \in R}, or more generally L=L(f(x))L = L(f(x)) with y‾=∂L/∂y\bar{y} = \partial L/\partial y, then

∇xL=Jf(x)⊤y‾=VJPf(x;y‾).\nabla_{x}L = J_{f}(x)^{\top}\bar{y} = {VJP}_{f}(x;\bar{y})\,.

The entire gradient of a scalar loss can therefore be obtained in a single reverse chain of VJPs. This accounts for the efficiency of reverse mode.

6.4.2 Functions of Several Arguments: JVPs and VJPs for Selected Arguments

If ff takes several arguments, as in f(x1,…,xk)f(x_{1},\ldots,x_{k}), write the Jacobian block as

Jxi(x)=∂f∂xi∈ℝm×ni.J_{x_{i}}(x) = \frac{\partial f}{\partial x_{i}} \in \mathbb{R}^{m \times n_{i}}.

In a typical training computation, view ff as f(X,θ)f(X,\theta). Then (X‾,θ‾)=(JX⊤y‾,Jθ⊤y‾)(\bar{X},\bar{\theta}) = \left( J_{X}^{\top}\bar{y},\mspace{6mu} J_{\theta}^{\top}\bar{y} \right). Thus one reverse pass produces both activation gradients for continued backpropagation and parameter gradients for the update.

6.4.3 Batches and Seed Matrices (Batched or Multiple Seeds)

Column-wise batching. Write X=[x1,…,xB]∈ℝn×BX = \lbrack x_{1},\ldots,x_{B}\rbrack \in \mathbb{R}^{n \times B} and y=[y1,…,yB]∈ℝm×By = \lbrack y_{1},\ldots,y_{B}\rbrack \in \mathbb{R}^{m \times B}. Let Y‾=[y‾1,…,y‾B]\bar{Y} = \lbrack{\bar{y}}_{1},\ldots,{\bar{y}}_{B}\rbrack.

6.4.4 Linear Layers: Dot Products and Outer Products in Notation

For an affine map z=Wx+bz = Wx + b (or Z=WX+bZ = WX + b for a column-wise batch):

x‾=W⊤z‾,W‾=z‾x⊤(or Z‾X⊤),b‾=reduce_sum(z‾;batch axis).\bar{x} = W^{\top}\bar{z},\quad\quad\bar{W} = \bar{z}\, x^{\top}\ (\text{or }\bar{Z}\, X^{\top}),\quad\quad\bar{b} = reduce\_ sum(\bar{z};\ \text{batch axis}).

Main observation. The pullback to inputs or intermediate values uses matrix multiplication (dot-product contraction). The pullback to parameters uses outer products summed over the batch. This is a concrete example of the block VJP rule above.

6.4.5 Higher-Order Derivatives

Hessian–vector(Pearlmutter trick):

H(θ)v=∇θ2L(θ)v=JVPθ(∇θL(θ);v),H(\theta)\, v = \nabla_{\theta}^{2}L(\theta)\, v = {JVP}_{\theta}\left( \nabla_{\theta}L(\theta);\ v \right),

This is also commonly written as a nested JVP/VJP, in reverse-over-forward or forward-over-reverse form.

Table 6-3. JVP and VJP quick reference

Case Input/output Seed Result
Basic JVP f:ℝn→ℝmf:\mathbb{R}^{n} \rightarrow \mathbb{R}^{m} v∈ℝnv \in \mathbb{R}^{n} Jv∈ℝmJv \in \mathbb{R}^{m}
Basic VJP As above y‾∈ℝm\bar{y} \in \mathbb{R}^{m} J⊤y‾∈ℝnJ^{\top}\bar{y} \in \mathbb{R}^{n}
VJP with multiple arguments f(x1,…,xk)f(x_{1},\ldots,x_{k}) y‾∈ℝm\bar{y} \in \mathbb{R}^{m} (Jx1⊤y‾,…,Jxk⊤y‾)(J_{x_{1}}^{\top}\bar{y},\ldots,J_{x_{k}}^{\top}\bar{y})
Batched VJP (inputs) X∈ℝn×BX \in \mathbb{R}^{n \times B} Y‾∈ℝm×B\bar{Y} \in \mathbb{R}^{m \times B} X‾∈ℝn×B\bar{X} \in \mathbb{R}^{n \times B}
Batched VJP (parameters) Shared θ\theta Y‾\bar{Y} θ‾=∑bJθ(xb)⊤y‾b\bar{\theta} = \sum_{b}^{}J_{\theta}(x_{b})^{\top}{\bar{y}}_{b}
Multiple-direction JVP V∈ℝn×KV \in \mathbb{R}^{n \times K} — JV∈ℝm×KJV \in \mathbb{R}^{m \times K}

Summary

6.5 AD in Learning: Forward Pass → Reverse Pass (AD/VJP) → Optimizer Update

Optimization objective. Minimize empirical risk, optionally with regularization:

minθL(θ)=1B∑(x,y)∈ℬt𝓁(fθ(x),y)+λΩ(θ).\min_{\theta}\mspace{6mu} L(\theta) = \frac{1}{B}\sum_{(x,y) \in \mathcal{B}_{t}}^{}\mathcal{l}\left( f_{\theta}(x),y \right)\mspace{6mu} + \mspace{6mu}\lambda\,\Omega(\theta).

One training iteration on the current minibatch ℬt\mathcal{B}_{t} has three steps:

  1. Forward pass. Compute the predictions and minibatch loss L̂t(θt){\widehat{L}}_{t}(\theta_{t}).

  2. Reverse pass (AD/VJP). Automatic differentiation gives the parameter gradient

    gt=∇θL̂t(θt)=Jfθ(θt)⊤∂L̂t∂y.g_{t}\mspace{6mu} = \mspace{6mu}\nabla_{\theta}{\widehat{L}}_{t}(\theta_{t})\mspace{6mu} = \mspace{6mu} J_{f_{\theta}}(\theta_{t})^{\top}\,\frac{\partial{\widehat{L}}_{t}}{\partial y}\,.

    This step is independent of the optimizer. AD's task is to compute gradients accurately and efficiently.

  3. Optimizer update. Use gtg_{t} and the optimizer's internal state to advance θ\theta to the next step.

6.5.1 Typical First-Order Optimizers (Depending Only on 𝐠𝐭\mathbf{g}_{\mathbf{t}}, Independently of AD)

6.5.2 An ADT Perspective: The Optimizer as a Pure Update Function

Define the optimizer state, retaining only the quantities it needs:

OptState::=SGD∣Mom(μ,v)∣Adam(β1,β2,ε,m,v).\text{OptState}\mspace{6mu}:: = \mspace{6mu}\text{SGD}\mspace{6mu} \mid \mspace{6mu}\text{Mom}(\mu,v)\mspace{6mu} \mid \mspace{6mu}\text{Adam}(\beta_{1},\beta_{2},\varepsilon,m,v).

A common update interface, expressed as a composable pure function:

Update:(θ,g,OptState)↦(θ′,OptState′).\text{Update}:(\theta,g,\text{OptState})\mspace{6mu} \mapsto \mspace{6mu}(\theta',\text{OptState}').

For example,

Step(θ,g,Adam(⋯))⇒(θ−ηm̂/(v̂+ε),Adam(⋯)′).\text{Step}(\theta,g,\text{Adam}(\cdots))\mspace{6mu} \Rightarrow \mspace{6mu}\left( \theta - \eta\,\widehat{m}/(\sqrt{\widehat{v}} + \varepsilon),\mspace{6mu}\text{Adam}(\cdots)' \right).

Design principle. AD produces gtg_{t}. The optimizer uses gtg_{t} and its own state to update the parameters. Expressing the optimizer as an ADT and a pure function keeps the definition of learning algebraic and composable, so optimization strategies can be exchanged or combined independently of AD.

6.6 AD for a Multilayer Perceptron

We derive the JVP and VJP for a multilayer perceptron (MLP) as a chain of equalities. By default, stack the batch in columns: X=a0∈ℝn0×BX = a^{0} \in \mathbb{R}^{n_{0} \times B}. For layer 𝓁\mathcal{l} (𝓁=1…L\mathcal{l} = 1\ldots L):

z𝓁=W𝓁a𝓁−1+b𝓁,z^{\mathcal{l}} = W^{\mathcal{l}}a^{\mathcal{l} - 1} + b^{\mathcal{l}},

a𝓁=ϕ𝓁(z𝓁),a^{\mathcal{l}} = \phi^{\mathcal{l}}\left( z^{\mathcal{l}} \right),

y=aLy = a^{L}

A bar ‾\bar{} denotes a covector (upstream gradient), and a dot ̇\dot{} a tangent vector (directional derivative). Use the Frobenius inner product:

⟨A,B⟩=def∑(A⊙B)\langle A,B\rangle\mspace{6mu}\overset{\text{def}}{=}\mspace{6mu}\sum(A \odot B)

That is, take A⊙BA \odot B and sum all its elements. More explicitly:

Relation to batches and broadcasting. The tensors must have the same shape, possibly after broadcasting. For example, in ⟨z‾L,dbL⟩\langle{\bar{z}}^{L},\, db^{L}\rangle, the shapes are z‾L∈ℝm×B{\bar{z}}^{L} \in \mathbb{R}^{m \times B} and dbL∈ℝm×1db^{L} \in \mathbb{R}^{m \times 1}. Broadcast dbLdb^{L} along the batch axis to m×Bm \times B, then sum over all m×Bm \times B elements. Equivalently,

⟨z‾L,dbL⟩=⟨reduce_sumbatch(z‾L),dbL⟩,\langle{\bar{z}}^{L},\, db^{L}\rangle = \left\langle {reduce\_ sum}_{\text{batch}}({\bar{z}}^{L}),\, db^{L} \right\rangle,

This yields b‾L=reduce_sumbatch(z‾L){\bar{b}}^{L} = {reduce\_ sum}_{\text{batch}}({\bar{z}}^{L}). Below, ′' denotes differentiation (the prime). The expression ϕL′(zL)\phi^{L\,'}(z^{L}) is the first derivative of the activation ϕL\phi^{L} of layer LL, evaluated at zLz^{L}. It acts elementwise and has the same shape as zLz^{L}. Thus

z‾L=a‾L⊙ϕL′(zL){\bar{z}}^{L} = {\bar{a}}^{L}\mspace{6mu} \odot \mspace{6mu}\phi^{L\,'}(z^{L})\mspace{6mu}

This multiplies the upstream gradient a‾L{\bar{a}}^{L} elementwise by the derivative of the activation. Common elementwise examples are:

6.6.1 VJP / Reverse Mode: All Gradients in a Single Backward Chain

Let the loss be L=L(y)L = L(y), with y‾=∂L/∂y\bar{y} = \partial L/\partial y having the same shape as yy. Starting at the final layer, expand the inner products of differentials in a chain of equalities:

dL=⟨a‾L,daL⟩dL = \left\langle {\bar{a}}^{L},\, da^{L} \right\rangle

=⟨a‾L,ϕL′(zL)⊙dzL⟩= \left\langle {\bar{a}}^{L},\,\phi^{L\,'}\left( z^{L} \right) \odot dz^{L} \right\rangle

=⟨︸a‾L⊙ϕL′(zL)z‾L,dzL⟩= \left\langle \underset{{\bar{z}}^{L}}{\overset{{\bar{a}}^{L} \odot \phi^{L\,'}\left( z^{L} \right)}{︸}},\, dz^{L} \right\rangle

=⟨z‾L,d(WLaL−1+bL)⟩= \left\langle {\bar{z}}^{L},\, d\left( W^{L}a^{L - 1} + b^{L} \right) \right\rangle

=⟨z‾L,dWLaL−1⟩+⟨z‾L,WLdaL−1⟩+⟨z‾L,dbL⟩= \left\langle {\bar{z}}^{L},\, dW^{L}\, a^{L - 1} \right\rangle + \left\langle {\bar{z}}^{L},\, W^{L}\, da^{L - 1} \right\rangle + \left\langle {\bar{z}}^{L},\, db^{L} \right\rangle

=⟨︸z‾L(aL−1)⊤W‾L,dWL⟩+⟨︸(WL)⊤z‾La‾L−1,daL−1⟩+⟨︸reduce_sumbatch(z‾L)b‾L,dbL⟩= \left\langle \underset{{\bar{W}}^{L}}{\overset{{\bar{z}}^{L}(a^{L - 1})^{\top}}{︸}},\, dW^{L} \right\rangle + \left\langle \underset{{\bar{a}}^{L - 1}}{\overset{(W^{L})^{\top}{\bar{z}}^{L}}{︸}},\, da^{L - 1} \right\rangle + \left\langle \underset{{\bar{b}}^{L}}{\overset{{reduce\_ sum}_{\text{batch}}({\bar{z}}^{L})}{︸}},\, db^{L} \right\rangle

This gives three VJP results for the layer's parameters and activations:

z‾L=a‾L⊙ϕL′(zL),{\bar{z}}^{L} = {\bar{a}}^{L} \odot \phi^{L\,'}\left( z^{L} \right),

W‾L=z‾L(aL−1)⊤,{\bar{W}}^{L} = {\bar{z}}^{L}(a^{L - 1})^{\top},

b‾L=sumbatch(z‾L),{\bar{b}}^{L} = {sum}_{\text{batch}}\left( {\bar{z}}^{L} \right),

a‾L−1=(WL)⊤z‾L.{\bar{a}}^{L - 1} = (W^{L})^{\top}{\bar{z}}^{L}.\mspace{6mu}

For any intermediate layer 𝓁=L−1,…,1\mathcal{l} = L - 1,\ldots,1, the same chain of equalities gives

dL=⟨a‾𝓁,da𝓁⟩dL = \left\langle {\bar{a}}^{\mathcal{l}},\, da^{\mathcal{l}} \right\rangle

=⟨a‾𝓁,ϕ𝓁′(z𝓁)⊙dz𝓁⟩= \left\langle {\bar{a}}^{\mathcal{l}},\,\phi^{\mathcal{l}\,'}\left( z^{\mathcal{l}} \right) \odot dz^{\mathcal{l}} \right\rangle

=⟨︸a‾𝓁⊙ϕ𝓁′(z𝓁)z‾𝓁,dz𝓁⟩= \left\langle \underset{{\bar{z}}^{\mathcal{l}}}{\overset{{\bar{a}}^{\mathcal{l}} \odot \phi^{\mathcal{l}\,'}\left( z^{\mathcal{l}} \right)}{︸}},\, dz^{\mathcal{l}} \right\rangle

=⟨z‾𝓁(a𝓁−1)⊤,dW𝓁⟩+⟨(W𝓁)⊤z‾𝓁,da𝓁−1⟩+⟨sumbatch(z‾𝓁),db𝓁⟩.= \left\langle {\bar{z}}^{\mathcal{l}}(a^{\mathcal{l} - 1})^{\top},\, dW^{\mathcal{l}} \right\rangle + \left\langle (W^{\mathcal{l}})^{\top}{\bar{z}}^{\mathcal{l}},\, da^{\mathcal{l} - 1} \right\rangle + \left\langle {sum}_{\text{batch}}({\bar{z}}^{\mathcal{l}}),\, db^{\mathcal{l}} \right\rangle.

The recurrence is therefore

z‾𝓁=a‾𝓁⊙ϕ𝓁′(z𝓁),{\bar{z}}^{\mathcal{l}} = {\bar{a}}^{\mathcal{l}} \odot \phi^{\mathcal{l}\,'}\left( z^{\mathcal{l}} \right),

W‾𝓁=z‾𝓁(a𝓁−1)⊤,{\bar{W}}^{\mathcal{l}} = {\bar{z}}^{\mathcal{l}}(a^{\mathcal{l} - 1})^{\top},

b‾𝓁=sumbatch(z‾𝓁),{\bar{b}}^{\mathcal{l}} = {sum}_{\text{batch}}\left( {\bar{z}}^{\mathcal{l}} \right),

a‾𝓁−1=(W𝓁)⊤z‾𝓁{\bar{a}}^{\mathcal{l} - 1} = (W^{\mathcal{l}})^{\top}{\bar{z}}^{\mathcal{l}}

Summing over all layers gives

dL=∑𝓁=1L(⟨W‾𝓁,dW𝓁⟩+⟨b‾𝓁,db𝓁⟩)+⟨X‾,dX⟩,dL = \sum_{\mathcal{l} = 1}^{L}\left( \langle{\bar{W}}^{\mathcal{l}},\, dW^{\mathcal{l}}\rangle + \langle{\bar{b}}^{\mathcal{l}},\, db^{\mathcal{l}}\rangle \right) + \langle\bar{X},\, dX\rangle,

where X‾=a‾0\bar{X} = {\bar{a}}^{0}.

This shows that ∇W𝓁L=W‾𝓁\nabla_{W^{\mathcal{l}}}L = {\bar{W}}^{\mathcal{l}}, ∇b𝓁L=b‾𝓁\nabla_{b^{\mathcal{l}}}L = {\bar{b}}^{\mathcal{l}}, and ∇XL=X‾\nabla_{X}L = \bar{X}. A single reverse chain of VJPs gives every gradient.

6.6.2 JVP / Forward Mode: Pushing Directions to the Output

Given directional seeds (tangent vectors)

Ẋ,Ẇ𝓁,ḃ𝓁,\dot{X},\mspace{6mu}{\dot{W}}^{\mathcal{l}},\mspace{6mu}{\dot{b}}^{\mathcal{l}},

Proceed layer by layer in the forward direction, moving the dotted quantities to the right-hand side of the equalities:

ż1=Ẇ1X+W1Ẋ+ḃ1,ȧ1=ϕ1′(z1)⊙ż1,ż2=Ẇ2a1+W2ȧ1+ḃ2,ȧ2=ϕ2′(z2)⊙ż2,⋮żL=ẆLaL−1+WLȧL−1+ḃL,ẏ=ȧL=ϕL′(zL)⊙żL\begin{aligned} {\dot{z}}^{1} & = {\dot{W}}^{1}X + W^{1}\dot{X} + {\dot{b}}^{1},\quad\quad{\dot{a}}^{1} = \phi^{1\,'}(z^{1}) \odot {\dot{z}}^{1}, \\ {\dot{z}}^{2} & = {\dot{W}}^{2}a^{1} + W^{2}{\dot{a}}^{1} + {\dot{b}}^{2},\quad\quad{\dot{a}}^{2} = \phi^{2\,'}(z^{2}) \odot {\dot{z}}^{2}, \\ & \mspace{6mu}\mspace{6mu} \vdots \\ {\dot{z}}^{L} & = {\dot{W}}^{L}a^{L - 1} + W^{L}{\dot{a}}^{L - 1} + {\dot{b}}^{L},\quad\dot{y} = {\dot{a}}^{L} = \phi^{L\,'}(z^{L}) \odot {\dot{z}}^{L} \end{aligned}

That is,

ẏ=JVP(X,θ)(f;Ẋ,θ̇)\dot{y} = {JVP}_{(X,\theta)}\left( f;\,\dot{X},\dot{\theta} \right)

This pushes directions in the inputs and parameters to a direction at the output in a single pass.

6.6.3 Duality of the JVP and VJP as a Chain of Equalities

︸L̇=⟨y‾,ẏ⟩=⟨y‾,JVP(f;Ẋ,θ̇)⟩\underset{= \left\langle \bar{y},\dot{y} \right\rangle}{\overset{\dot{L}}{︸}} = \left\langle \bar{y},\, JVP\left( f;\dot{X},\dot{\theta} \right) \right\rangle

=⟨VJP(f;y‾),(Ẋ,θ̇)⟩= \left\langle VJP\left( f;\bar{y} \right),\,\left( \dot{X},\dot{\theta} \right) \right\rangle

=⟨X‾,Ẋ⟩+∑𝓁(⟨W‾𝓁,Ẇ𝓁⟩+⟨b‾𝓁,ḃ𝓁⟩),= \langle\bar{X},\dot{X}\rangle + \sum_{\mathcal{l}}^{}\left( \langle{\bar{W}}^{\mathcal{l}},{\dot{W}}^{\mathcal{l}}\rangle + \langle{\bar{b}}^{\mathcal{l}},{\dot{b}}^{\mathcal{l}}\rangle \right),

The chain of equalities relates the forward directional derivative exactly to the reverse gradient. The left-hand side takes a JVP and then an inner product. The right-hand side takes a VJP and then an inner product. Both paths give the same number.

In summary:

6.7 How AD Improves Computational Efficiency

6.7.1 The Complexity of AD

Time complexity: classical results and practical observations

Conclusion. In deep learning, training almost always has m=1m = 1, a scalar loss. VJP/reverse mode therefore has the time advantage.

6.7.2 Why AD Is Fast: Multiplying by the Jacobian Without Constructing It

Explicitly constructing J∈ℝm×nJ \in \mathbb{R}^{m \times n} at a cost on the order of 𝒪(mn)\mathcal{O(}mn) function calls would almost always be prohibitive. AD directly computes

JvorJ⊤y‾Jv\quad\text{or}\quad J^{\top}\bar{y}

without materializing JJ. This is the matrix-free approach: treat the operator as a black box and ask only for products with vectors. Many second- or higher-order algorithms, including conjugate gradients and Newton approximations, require only a Hessian–vector product:

Hv=∇2L(θ)v=ddϵ|ϵ=0∇L(θ+ϵv)=JVP∇L(θ;v),Hv = \nabla^{2}L(\theta)\, v = \frac{d}{d\epsilon}|_{\epsilon = 0}\,\nabla L(\theta + \epsilon v) = {JVP}_{\,\nabla L}(\theta;v),

Alternatively, use mixed mode: Hv=VJPθ(f;JVPθ(f;v))Hv = {VJP}_{\theta}\left( f;{JVP}_{\theta}(f;v) \right) (Pearlmutter's trick). This makes second-order information available at the cost of one or two first-order passes.

6.7.3 Acceleration Techniques Used in Mainstream Frameworks

Mode selection and mixing

Batched seeds and vectorization (vmap/pmap)

Stack several seeds as a matrix, using vv or y‾\bar{y}. Compute JVJV or J⊤YJ^{\top}Y in one operation to exploit BLAS or GPU parallelism. This can be much faster than repeated calls in a for loop.

Operator fusion and JIT/graph compilation

Activation recomputation (checkpointing/rematerialization)

Structured VJP/JVP rules

Implicit differentiation

For an inner optimization or a fixed-point equation Φ(θ*,ϕ)=0\Phi(\theta^{*},\phi) = 0, use

∂θ*∂ϕ=−(∂Φ∂θ)−1∂Φ∂ϕ\frac{\partial\theta^{*}}{\partial\phi} = - (\frac{\partial\Phi}{\partial\theta})^{- 1}\frac{\partial\Phi}{\partial\phi}

and replace explicit backpropagation through a long iteration with a linear solve or CG using Hessian–vector products. This requires less time and memory than unrolling T steps and differentiating backward through them.

Exploiting sparse and block structure

Numerical stability and mixed precision

Techniques including logsumexp, stable normalization or scaling factors, and loss scaling for bf16/fp16 can reduce the number of iterations or retries and thereby shorten total execution time.

These techniques do two things: avoid explicitly constructing JJ and reduce the cost or increase the parallelism of each product with a vector.

Table 6-4. Efficiency of different differentiation methods

Method Correctness Complexity (computing ∇f\nabla f)
Manual differentiation Depends on the programmer; error-prone Can match the complexity of AD
Finite differences (forward or central) Approximate, with a step-size trade-off 𝒪(ncost(f))\mathcal{O(}n\, cost(f)) / 𝒪(2ncost(f))\mathcal{O}(2n\, cost(f))
Symbolic differentiation Exact formula Expression-dependent, often with expression swell
Automatic differentiation (AD) Gradients accurate to machine precision Scalar output: ≈c⋅cost(f)\approx c \cdot cost(f). General case: min{m,n}min\{ m,n\} first-order passes.

In the usual deep learning setting of many parameters and a scalar loss, AD based on reverse-mode VJPs has better time complexity than finite differences. It avoids the maintenance problems of symbolic and hand-coded differentiation while delivering gradients accurate to machine precision.

6.7.4 The Efficiency of Computing Intermediate and Parameter VJPs Together

Consider two fully connected layers with the batch in columns:

z1=W1X+b1,a1=ϕ(z1),y=W2a1+b2.z_{1} = W_{1}X + b_{1},\quad a_{1} = \phi(z_{1}),\quad y = W_{2}a_{1} + b_{2}.

Given y‾=∂L/∂y\bar{y} = \partial L/\partial y:

The same VJP pass yields both activation gradients for continued backpropagation and parameter gradients for the update. Both use matrix–vector products or outer products. No Jacobian is constructed, and the time complexity matches that of the forward pass. This is the source of backpropagation's efficiency.

6.7.5 Efficiency at Second and Higher Orders

6.7.6 Conclusion

AD's time efficiency comes from using JVP/VJP products with vectors in place of explicit Jacobians or black-box differences, choosing the mode according to output and input dimensions, and using fusion, vectorization, recomputation, structured rules, and implicit differentiation to bring each product close to the cost of the underlying linear algebra. In deep learning with a scalar loss, one reverse chain of VJPs gives all parameter gradients at the same order of cost as a forward pass. This makes modern training scalable.

6.8 Rules for Reverse-Mode Backpropagation: The ReverseGraph Transformation

The VJP is the mathematical basis of backpropagation in neural networks. We begin with a scalar loss LL and compute gradients such as ∂L∂x\frac{\partial L}{\partial x}. Let y=f(x)y = f(x). If we know the loss gradient with respect to the output, ∂L∂y=y‾\frac{\partial L}{\partial y} = \bar{y}, the chain rule gives its gradient with respect to the input as ∂L∂x=y‾TJf(x)\frac{\partial L}{\partial x} = {\bar{y}}^{T}J_{f}(x). Thus a VJP maps the output gradient back to the inputs, the essential operation of backpropagation. An implementation applies a VJP at each layer and propagates the gradient backward without constructing the Jacobian. A typical network's final training output, its loss, is scalar. One reverse chain of VJPs therefore computes all parameter gradients at the same order of complexity as the forward calculation. Forward-mode JVPs generally need repeated computations to obtain every parameter gradient, equivalent to computing one Jacobian column at a time. That cost becomes very large in high parameter dimensions. A single scalar output, such as a network loss, consequently favors reverse mode.

This section expresses backpropagation as programmable rules for ReverseGraph. The aim is to obtain gradients for parameters and intermediate values in one backward pass, using local VJP rules and structural composition laws. The central idea is:

Each node denotes a value and a pullback, a linear operator that propagates sensitivities backward. Primitives provide local VJPs. Structural nodes for composition, parallelism, and packing provide the composition laws.

6.8.1 ReverseGraph Semantics and Interface

The WithPB pair (value and pullback)

WithPB⟨value:V,pb:V‾→𝚞𝚗𝚒𝚝⟩.\text{WithPB}\mspace{6mu}\langle\text{value}:V,\mspace{6mu}\text{pb}:\mspace{6mu}\bar{V}\mathtt{\rightarrow unit\rangle.}

The Reverse transformation: from forward nodes to nodes with pullbacks. For any forward node n, write

ℛ(n)=WithPB⟨v,pb⟩.\mathcal{R(}n)\mspace{6mu} = \mspace{6mu}\text{WithPB}\langle v,\mspace{6mu}\text{pb}\rangle.

Here v is the forward value and pb the node's pullback. Apply the outermost pb to the output covector to obtain the gradients of the entire graph.

6.8.2 Composition Laws for Structural Nodes, Independent of the Primitives

Consequently, once the primitive VJPs are defined, the composition laws suffice to run the entire ReverseGraph.

6.8.3 VJP Rules for Common Primitives (Obvious Shape Details Omitted)

Write z=o(⋅)z = o( \cdot ). All elementwise rules include unbroadcast where needed.

Elementwise and linear operations

Activations (elementwise)

Shape operations and aggregation

Softmax and cross-entropy (batch mean)

If z=softmax(s)z = softmax(s) and 𝓁=−1B∑iyilog⁡zi\mathcal{l} = - \frac{1}{B}\sum_{i}^{}y_{i}\log z_{i}, the combined formula is s‾=1B(z−y)\bar{s} = \frac{1}{B}(z - y). It is numerically stable and straightforward to implement as a primitive pullback.

6.8.4 Rules for the Reverse Transformation ℛ\mathcal{R} (Illustrative Semantics)

These rules are the interpreter semantics of ReverseGraph. To execute them, (1) run the forward pass once to obtain each node's value and pullback closure, then (2) invoke the outermost pb with the upstream covector for the loss. Gradients accumulate automatically throughout the graph.

6.8.5 Batches

We now incorporate batch-aware rules into the ReverseGraph transformation from the preceding discussion. Retain the value-and-pullback structure of ReverseGraph and make axis information and reduction and broadcasting explicit in the VJP rules.

A minimal extension for batch axes

Named axes. Label the dimensions of each tensor, for example axes(X)=[feat,batch]\text{axes}(X) = \lbrack\text{feat},\text{batch}\rbrack and axes(b)=[feat,singleton]\text{axes}(b) = \lbrack\text{feat},\text{singleton}\rbrack.

Two basic operators used at the end of VJP rules

For a shared parameter broadcast across a batch, first use the local formula to compute z‾\bar{z} of the same shape as the output. Then reduce over the broadcast axes using reduce_sumreduce\_ sum. This one rule covers BiasAdd, affine biases, and weights broadcast across a batch.

Batch-aware VJP rules for primitives, with explicit axes

The rules below show only the mathematical core. In implementation, replace shape tests with axis tests.

Addition / BiasAdd

For z=x+bz = x + b, suppose bb is broadcast along axes SS (for example, S={batch}S = \{\text{batch}\}).

x‾=z‾,b‾=reduce_sumS(z‾)\bar{x} = \bar{z},\quad\quad\bar{b} = {reduce\_ sum}_{S}(\bar{z})

Sum (reduction over axes)

z=∑axis=Sxz = \sum_{\text{axis} = S}^{}x

x‾=broadcast_to_axes(z‾;axes(x))\bar{x} = broadcast\_ to\_ axes(\bar{z};\ \text{axes}(x))

Concat / Stack (concatenating or stacking along an axis)

z=concatS(x1,…,xk)⇒(x‾1,…,x‾k)=splitS(z‾).z = {concat}_{S}(x_{1},\ldots,x_{k})\quad \Rightarrow \quad({\bar{x}}_{1},\ldots,{\bar{x}}_{k}) = {split}_{S}(\bar{z}).

z=stackS(x1,…,xk)⇒(x‾1,…,x‾k)=unstackS(z‾).z = {stack}_{S}(x_{1},\ldots,x_{k})\quad \Rightarrow \quad({\bar{x}}_{1},\ldots,{\bar{x}}_{k}) = {unstack}_{S}(\bar{z}).

Affine layer (column-wise batch)

Z=WX+bZ = WX + b

X‾=W⊤Z‾,W‾=Z‾X⊤,b‾=reduce_sumbatch(Z‾)\bar{X} = W^{\top}\bar{Z},\quad\bar{W} = \bar{Z}\, X^{\top},\quad\bar{b} = {reduce\_ sum}_{\text{batch}}(\bar{Z})

If the loss is a batch mean, the upstream Z‾\bar{Z} already includes the factor 1/B1/B. No further division is needed here.

MatMul as batched matrix multiplication with leading axes S

Write ZSij=ASikBSkjZ_{Sij} = A_{Sik}B_{Skj}. Then

A‾Sik=Z‾SijBSkj,B‾Skj=ASikZ‾Sij{\bar{A}}_{Sik} = {\bar{Z}}_{Sij}B_{Skj},\quad\quad{\bar{B}}_{Skj} = A_{Sik}{\bar{Z}}_{Sij}

This covers three common cases:

Elementwise activations (ReLU/Sigmoid/Tanh/…)

As in the unbatched case, x‾=z‾⊙ϕ′(x)\bar{x} = \bar{z} \odot \phi'(x). The implementation need only ensure correct axis alignment and broadcasting.

Softmax and cross-entropy (batch mean)

If z=softmax(s)z = softmax(s) and 𝓁=−1B∑ylog⁡z\mathcal{l} = - \frac{1}{B}\sum y\log z, then

s‾=1B(z−y)\bar{s} = \frac{1}{B}(z - y)

This already includes the batch-averaging factor 1/B1/B.

How ReverseGraph incorporates the rules

Reuse the preceding framework and introduce axis parameters only in the VJPs of primitive nodes:

A worked example: two-layer MLP with examples in columns

z1=W1X+b1,a1=ϕ(z1),y=W2a1+b2.z^{1} = W^{1}X + b^{1},\quad a^{1} = \phi(z^{1}),\quad y = W^{2}a^{1} + b^{2}.

We obtain

a‾1=(W2)⊤y‾,{\bar{a}}^{1} = (W^{2})^{\top}\bar{y},\quad

z‾1=a‾1⊙ϕ′(z1),{\bar{z}}^{1} = {\bar{a}}^{1} \odot \phi'(z^{1}),\quad

W‾2=y‾(a1)⊤,{\bar{W}}^{2} = \bar{y}(a^{1})^{\top},

b‾2=sumbatch(y‾),\ {\bar{b}}^{2} = {sum}_{\text{batch}}\left( \bar{y} \right),\

W‾1=z‾1X⊤,{\bar{W}}^{1} = {\bar{z}}^{1}X^{\top},\

b‾1=sumbatch(z‾1),{\bar{b}}^{1} = {sum}_{\text{batch}}\left( {\bar{z}}^{1} \right),\

X‾=(W1)⊤z‾1\bar{X} = (W^{1})^{\top}{\bar{z}}^{1}

The axis-aware rules give exactly this result: for every parameter broadcast across the batch, including biases and broadcast weights, reduce over batch\text{batch}. Everything else follows the unbatched case.

Implementation notes

  1. Axis metadata. Attach axes to Value, or keep a dictionary from tensors to axis labels in DefContext.

  2. Common library functions. Provide reduce_sum_axes(T,S), broadcast_to_axes(G,axesX), and split_axis/stack_axis.

  3. Rules specify which axes to use. Pass S (for example, {batch}) as a parameter and avoid hard-coding shapes.

  4. Consistent means and sums. Specify whether the loss is averaged over the batch. If it is, apply 1/B1/B upstream, as in the combined CE formula. Downstream rules should not scale it again.

  5. Generalization. Extend SS to additional axes such as time for BPTT/TBPTT. For parameters broadcast across time, take an additional reduction over {time}.

In brief: keep ReverseGraph's value-and-pullback structure and give each primitive VJP rule explicit axis parameters. The gradient of any parameter broadcast over those axes is summed over them. The same rules cover BiasAdd, Sum, Concat, and MatMul (including batched MatMul) and naturally handle several axes, such as batch and time.

6.8.6 Design Considerations

  1. Linearity and accumulation. pb must be linear. Add gradient contributions from every path to the same variable at a join in the DAG.

  2. Consistent broadcasting. Pair elementwise rules with unbroadcast/broadcast_to_shape. Distinguish batch and channel axes explicitly.

  3. Numerical stability. Use a fused pullback for softmax and cross-entropy, and specify normalization and summation axes explicitly.

  4. Extensibility. A new primitive needs one VJP rule. The structural and composition layers need no changes.

  5. Subgraphs and shared parameters. ParamMap must send all gradient contributions for a given parameter to the same slot.

  6. Optional memory strategy. With checkpointing, pb can recompute forward values internally as needed.

Apply ℛ\mathcal{R} to transform the forward graph into a ReverseGraph of WithPB pairs (value and pullback). Primitives define VJPs, and structural nodes define composition laws. A single call to pb accumulates gradients across the graph in reverse order. These are the rules of backpropagation.

6.9 Concluding Remarks

In short, AD turns a differentiable program into a trainable model. An algebraic implementation connects naturally to the abstract syntax or computation graph, to type and shape checking, and to backend lowering (Chapters 4–5).

CHAPTER 7

Approximating the Logical Meaning of Natural Language with ADT Variants

Turning natural language into executable meaning is a critical step between language, knowledge, and inference. This chapter develops a controlled engineering approach. Using ADT variants (sums of products) as a skeleton, we recast sentences and fragments as well-typed tokens. The representation preserves distinctions that matter: predicates and arguments, modification, value constraints, events, and participants. It also gives us something we can compose, check, and run. The aim is a stable intermediate representation for structured retrieval, rule checking, and verifiable inference, without requiring a complete linguistic semantics.

Background and motivation. Since Montague, formal semantics has emphasized compositionality: the meaning of an expression depends on the meanings of its parts and how syntax combines them. A typed lambda calculus commonly implements this syntax–semantics homomorphism. The tradition established that natural language can be mapped to logical terms and typed objects. It also explains how a small number of combinators and types can build up complex expressions. In parallel, frameworks such as combinatory categorial grammar (CCG) tightly couple syntax and semantics in a computationally tractable way. They provide working examples of how to derive semantic constructions from syntax.

Semantic representations and their trade-offs. Engineering-oriented semantic resources often use graph representations. Abstract Meaning Representation (AMR), for example, represents a sentence as a directed, labeled graph that highlights semantic roles and event structure. Discourse representation theory (DRT) addresses cross-sentence phenomena such as anaphora and tense. It constructs representations incrementally to handle reference and scope. Both approaches offer expressive detail, but annotation and parsing can be costly at scale, and the resulting representations may have little direct connection to downstream executors. Here we place the information a program most needs to compute in ADT variants, then add optional fields and constraints as needed. This balances coverage, complexity, and executability.

From semantic parsing to executable approximations. Semantic parsing maps text directly to logical forms or programs. Surveys trace rule-based, statistical, and neural methods. Neural sequence-to-tree and sequence-to-program approaches, such as the work of Dong and Lapata, show that systems can learn task-specific executable semantics. They still need well-defined target representations and constraints for control and transfer. We choose strongly typed ADTs and tokens as the target. Structured output and function calling constrain LLM generation to that schema, reducing ambiguity and cleanup afterward.

What will we do?

  1. Establish minimal principles for mapping natural language to a token ADT. Prioritize predicates and arguments, modification and scope, events and participants, and common forms of quantification and negation. Preserve ambiguity explicitly where a reading is unresolved or still needs evidence.

  2. Develop a reproducible treatment of the Jones Problem. Separate the passage into linguistic constructions, align them with ADT variants, and test the mapping with executable checks on types, constraints, and sample inferences. Compare the approach with PTQ, CCG, DRT, and AMR in terms of coverage, precision, and executability.

  3. Pass the token representation to retrieval, constraint-checking, and inference programs. Connect representations to evidence and conclusions, and use evidence carried with a result and explicit proof objects to assess quality.

What will you take away?

Within the book, Chapter 7 narrows the language-to-token step to something reliable. ADT variants carry the essential semantic distinctions, and types and constraints let us compose and execute them. A text becomes input we can compute over, inspect, and trace. Chapter 8 draws these ideas together as engineering principles.

7.1 An Engineering Approximation to Compositional Semantics: From Montague to ADTs and LLMs

Compositionality holds that the meaning of a complex expression depends on the meanings of its parts and the way they combine. Montague semantics made this idea systematic. A typed lambda calculus supplies the semantic machinery, and a correspondence between syntax and semantics maps phrase structure step by step to a composed semantic expression. Quantification, reference, and intensional terms, for example, receive interpretations by typed function application. This work set the course for modern formal semantics. For derivations from lexical types to sentence meanings and for typical operators, see the Stanford Encyclopedia of Philosophy entry and the textbook by Heim and Kratzer.

Formalizing natural language in full at this level and implementing the result is expensive. It requires fine-grained lexical types, inventories of semantic terms, and derivation rules. Ambiguity, scope, indexicals, and adverbial expressions all need attention. Products often use an engineering approximation that preserves enough compositionality for the job. We can use an algebraic data type to encode sentence patterns as constructors such as If, And, and Will, then use pattern matching and small rewrite or propagation rules for inference. Constructors determine what may combine. A match branch specifies what can be assembled or inferred when that shape appears. F# directly supports discriminated unions (ADTs) and pattern matching, making an interpretation of semantics as data shape easy to read and maintain.

The approach follows Montague in principle: meanings of parts plus rules of composition yield a meaning for the whole. In implementation, it replaces demanding higher-order logical inference with structured data and terminating local reductions. For example, we encode “If P and Q, then R will happen” as Force(If(And(P,Q)), Will R). Constructors and matches execute the composition without a general theorem prover. We give up formal completeness and open-domain coverage in exchange for readability, ease of change, and predictable runtime behavior.

LLMs have brought new questions to compositional semantics. Researchers continue to test compositional generalization in large models, including systematic generation and transfer in morphology and syntax. Even strong instruction-tuned models can be inconsistent on some challenges. This motivates external structural constraints and data that expose parts, relationships, and ways of combining them (Ismayilzada et al., 2024). Meanwhile, retrieval-augmented generation (RAG) (Lewis et al., 2020) introduces verifiable external knowledge into generation. It gives the LLM a kind of nonparametric memory, improving factual accuracy and traceability. It fits naturally with the idea of keeping composable semantic resources outside the model and invoking them during inference.

Work on knowledge graphs (KGs) and LLMs and on neurosymbolic methods couples structured knowledge (graphs, ontologies, and rules) to a model’s linguistic and statistical abilities in both directions. A KG can constrain or augment factual and logical reasoning, while an LLM can help construct and align a KG. Research distinguishes KG-enhanced LLMs, LLM-enhanced KGs, and joint reasoning frameworks. These illustrate the convergence of semantics and statistics (Pan et al., 2024). Surveys of neurosymbolic AI likewise identify the combination of interpretable symbolic rules with neural learning and generalization as a route toward controllable, verifiable intelligence (Hitzler & Sarker, 2021).

The position of this chapter is pragmatic. We use ADTs, pattern matching, and a small propagation kernel as an engineering approximation to compositional semantics. The path from natural language through a composable semantic structure to intuitive inference becomes runnable code. If stronger proofs or greater scale are needed, the same structure can be compiled to a stricter logic such as Horn clauses or Datalog, or connected to external knowledge through RAG or a KG. Montague offers a model of how meanings compose, ADTs offer a way to encode them, and LLMs, KGs, and RAG help extend the method to complex settings.

7.2 The Jones Problem: Modeling Meaning and Running Inference with an ADT

7.2.1 The Problem and Its Source

The classic statement of the Jones Problem comes from Logic for Applications (Nerode & Shore, 1997). The exercise asks the reader to convert a passage to Prolog and use resolution to prove that the directors will declare a dividend. The authors’ 2023 errata correct the sentence about Patterson in the second paragraph: if Patterson comes, he will bring Robinson to his senses, and he will come only if Jones is ill.

Here is a slightly modified version of the Jones Problem:

If you are told that Jones has fallen deathly ill and Smith has gone off to his bedside, you could determine if the directors will declare a dividend. If Jones is ill or Smith is away, then the directors will meet and declare a dividend if Robinson comes to his senses and takes matters into his own hands. If Patterson comes, he will force Robinson back to his senses but, of course, he will come only if Jones is ill. On the other hand, if Townsend, who is inseparable from Smith, stays away, Robinson will have to take matters into his own hands. Show that the directors will declare a dividend.

In the Chinese edition the passage is restated as follows, rendered here in English:

You are told that Jones is seriously ill and that Smith has gone to his bedside to look after him. Can you determine whether the directors will declare a dividend? If Jones is ill or Smith is away, the directors will meet. They will declare a dividend if Robinson comes to his senses and takes matters into his own hands. If Patterson comes, he will bring Robinson to his senses; of course, he will come only if Jones is ill. On the other hand, if Townsend, who is inseparable from Smith, fails to appear, Robinson will have to take matters into his own hands. Prove that the directors will eventually declare a dividend.

7.2.2 Why Can We Reason Before Building a Full Formal Logic?

Mapping natural language precisely to first-order logic or an ontology has occupied researchers for decades, as the tradition of Montague semantics illustrates. Going directly from full formalization to inference sets a high entry threshold and entails considerable implementation work on lexical items, quantifiers, scope, ambiguity, and reference. We can instead start from engineering needs and semantic intuitions: write the semantic structures directly into ADT constructors and execute inference by matching patterns and applying simple propagation or rewrite rules. This follows the tradition of defining program meaning through rewrite relations or operational semantics.

7.2.3 An ADT Gives “Meaning as Data Structure” a Type Boundary

A minimal ADT:

type fact = Fact(id*string) | If of fact | Will of fact | And of fact*fact
type force = Force of fact * fact // When the fact on the left holds, trigger the Will or fact on the right.

Why is this minimal construction intuitive?

  1. The constructors express the semantics. If denotes a condition, Will an anticipated event or consequence, and And(…, …) a conjunction. They are semantic names chosen for the reader. Someone reading the AST can recognize the shape of the original sentence.

  2. Pattern matching dispatches the rules. Each constructor has a match branch whose body says what to do with that shape. The compiler’s exhaustiveness check turns the requirement to cover every semantic case into a compile-time issue the programmer must address.

  3. Small-step semantics provides an executable interpretation. Read each Force(If α, Will β) as a rewrite or propagation rule: when α is satisfied or simplifies to a satisfied condition, add Will β to the results. For And(a,b), check recursively that both a and b can hold. This is a programming realization of structural operational semantics (SOS) and term rewriting, restricted to the part that is simple enough to read and run.

Implementation note: discriminated unions and pattern matching in F#, OCaml, and Haskell suit this style of programming. The languages and their compilers support checks for exhaustiveness and unreachable cases.

7.2.4 Translating the Jones Problem into an ADT: From the Chinese Wording to Constructors

A condensed paraphrase:

Facts and names for the ADT, showing the essential structure:

Each rule can be encoded as Force(If α, Will β) or Force(α, β). For readability, we wrap a condition explicitly in If and mark what will happen or be inferred with Will. The result reads like the original wording: “If α, then β will follow.” At this stage we are giving natural language an executable skeleton. We name the participants, states, and relationships. The semantic expressions “if/then,” “and,” and “will” become constructors or rule entries. This step alone does not prove that the logic is correct.

7.2.5 Running the Inference: Propagation, Closure, and Termination

Put the observations taken as true, such as Jones_ill and Smith_away, into a set of known facts. Then run a small forward-chaining procedure:

  1. Maintain Known, the set of observed or derived facts, and Agenda, the facts or conditions still to check.

  2. Take an element x from Agenda:

    • If there is a rule Force(If a, Will b) and Known satisfies a (for example, a = And(p,q) and p,q ∈ Known), add Will b or b itself to Known and put consequences of b that remain to be checked on Agenda.

    • When you encounter And(u,v), put u and v on Agenda so that each subcondition can be checked or satisfied.

  3. Continue until Agenda is empty and the computation has reached a fixed point.

The algorithm combines rewriting or propagation with a fixed point over a finite set. There are finitely many facts and rules. A rule only adds new entries and never removes an existing one, so the process is monotone and must terminate. This is the principle behind computing closure in Datalog. ADT constructors let us express the semantics in a form close to the original wording.

Semantically, firing a rule, adding its consequence, and repeating to a fixed point turns a readable natural-language skeleton into executable operational semantics. SOS and term rewriting supply the theoretical background. The engineering result we need is a small interpreter that terminates.

7.2.6 The Jones Problem Step by Step: Deriving the Dividend

The problem supplies the observations Jones_ill and Smith_away. Follow the propagation order from the preceding section:

  1. The meeting: Jones_ill or Smith_away can trigger Directors_meet. There are two rules, and either one suffices.

  2. Patterson comes → Robinson comes to his senses:

    Jones_ill ⟹ Patterson_come ⟹ Robinson_back.

  3. Townsend is away → Robinson takes matters into his own hands: if we model “inseparable” as Smith_away ⟹ Townsend_away, we obtain Robinson_takes immediately. Without that rule, we can supply Townsend_away as a background fact from the same context as Smith_away.

  4. The necessary and sufficient condition for declaring the dividend:

    And(Robinson_back, Robinson_takes) ⟹ Will(Directors_dividend). The preceding two steps establish both premises, yielding the desired conclusion.

We can do all this by reading the rules and propagating over data structures, without invoking the full machinery of first-order logic, resolution, or unification. We give up the generality and completeness guarantees of traditional Prolog SLD resolution in exchange for an expression close to natural language and a small, readable implementation. If needed, the rules can later be translated into Horn clauses for a more rigorous proof by SLD resolution.

7.2.7 What Makes the ADT Intuitive, Maintainable, and Reliable Enough?

7.2.8 Natural Language to ADTs and Formal Logic to Theorem Proving

7.2.9 Why Is This Practical Now?

  1. Mature language support. F# and other mainstream languages give discriminated unions and pattern matching concise, safe, first-class support.

  2. Firm theoretical foundations. Defining execution by a rewrite or transition relation is a basic technique of programming-language semantics. We translate it into a small kernel that a developer can implement.

  3. Compatibility with traditional logic. The same knowledge can be mapped to Horn clauses and SLD resolution or to a Datalog fixed-point calculation for stronger proof guarantees and scalability.

The result is a readable, runnable, extensible prototype for intuitive inference: natural language → ADT sentence forms → pattern-matching rules → forward-chaining closure → conclusion. In teaching, prototyping, and many domain-bounded business rule systems, a small amount of code can produce an inference process that people can explain.

7.3 Implementations in F# and Swift

The AlgebraicCode repository contains implementations that express and solve the Jones Problem directly:

The implementation illustrates the preceding argument. We can use ADTs to make sentence forms such as If, Will, and And into a semantic skeleton, then use pattern matching and forward propagation (monotone closure) to carry out intuitive inference. F# discriminated unions and pattern matching fit this style directly. The propagation kernel computes a closure in the same fixed-point tradition as Datalog. For comparison with conventional logic, the same rules can be written as Horn clauses.

7.3.1 Running the Example

F# (cross-platform)

dotnet fsi fsharp/JonesEngine.fsx

Swift (use swiftc or the Swift REPL on macOS)

swift swift/JonesEngine.swift

The two files print the same derivation trace and final conclusion.

Expected output from both versions

Derived (step 1): The directors meet. ; Patterson comes. ; Townsend is away.
Derived (step 2): Robinson comes to his senses. ; Robinson takes matters into his own hands.
Derived (step 3): The directors declare a dividend.
✔ Goal reached: The directors declare a dividend.
All true facts:
- Jones is ill.
- Smith is away.
- Directors meet.
- Patterson comes.
- Townsend is away.
- Robinson comes to his senses.
- Robinson takes matters into his own hands.
- The directors declare a dividend.

7.3.2 How the kernel works

An ADT for the structure of a natural-language statement

The kernel needs only a few constructors.

The constructors form a semantic vocabulary. Reading the AST is much like reading a sentence. F# discriminated unions and pattern matching make it natural to encode meaning in the shape of the data. The compiler’s exhaustiveness checks catch missing cases.

Translating the problem statements into rules

Jones_ill ⟹ Directors_meet
Smith_away ⟹ Directors_meet
And(Robinson_back, Robinson_takes) ⟹ Will(Directors_dividend)
Patterson_come ⟹ Robinson_back
Jones_ill ⟹ Patterson_come, following the 2023 erratum.
Townsend_away ⟹ Robinson_takes
Smith_away ⟹ Townsend_away models the statement that the two are inseparable.

Execution by forward chaining with a worklist

7.3.3 The core F# code

type fact = Fact of int * string | If of fact | Will of fact | And of fact * fact
type force = Force of fact * fact

let rec holds known = function
  | Fact _     as f -> known.Contains f
  | If g | Will g   -> holds known g
  | And(a,b)        -> holds known a && holds known b

let step forces known =
  forces
  |> List.collect (fun (Force(cond,res)) ->
       if holds known cond then
         match res with
         | Will (Fact _ as at) | (Fact _ as at) -> [at]  // Assert atomic facts only
         | _ -> [] else [])
  |> List.distinct
  |> List.filter (fun f -> not (known.Contains f))

let rec closure forces known trace =
  match step forces known with
  | []      -> known, List.rev trace
  | newly   -> closure forces (Set.union known (set newly)) (newly::trace)

7.3.4 Relation to formal methods and scope for extension

7.4 Compiling natural-language paragraphs into the Jones semantic ADT with GPT-4o

7.4.1 Approach and API choice

7.4.2 System and user prompts for the LLM

System prompt for the required JSON output

You convert English paragraphs into input for a semantic ADT. Extract the following from the paragraph.

  1. atoms is a table of atomic facts of the form {id, name, text}. Number the IDs from 1 to N, use Snake_Case for name, and make text a human-readable sentence ending in a period.

  2. rules is a table of trigger rules. Each rule has the form { "if_all": [<atom.name>...], "then": "<atom.name>", "will": true }.

  3. observations is a list of names of atoms that the paragraph explicitly identifies as true.

Mapping constraints

Example structure (illustrative, not the solution)

{
  "atoms": [{"id":1,"name":"Jones_ill","text":"Jones is ill."}],
  "rules": [{"if_all":["Jones_ill"],"then":"Directors_meet","will":true}],
  "observations": ["Jones_ill","Smith_away"]
}

User prompt with the original problem statement

Turn the following paragraph into the JSON defined by the system instructions.

If you are told that Jones has fallen deathly ill and Smith has gone off to his bedside, you could determine if the directors will declare a dividend. If Jones is ill or Smith is away, then the directors will meet and declare a dividend if Robinson comes to his senses and takes matters into his own hands. If Patterson comes, he will force Robinson back to his senses but, of course, he will come only if Jones is ill. On the other hand, if Townsend, who is inseparable from Smith, stays away, Robinson will have to take matters into his own hands. Show that the directors will declare a dividend.

To process a Chinese paragraph, replace the English problem statement with its Chinese counterpart. The same prompt can produce JSON with the same structure.

7.4.3 Running the example

Code location

Before running the example, set these environment variables.

Set AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY, and AZURE_OPENAI_DEPLOYMENT (the name of your GPT-4o deployment, such as gpt-4o). Optional settings are AZURE_OPENAI_API_VERSION (default 2024-08-01-preview) and USE_JSON_SCHEMA (1 requests Structured Outputs where available, with an automatic fallback to JSON mode).
This follows the Chat Completions and Structured Outputs conventions in the API documentation.

Expected output

The terminal prints a sequence of derivation steps ending with “✔ Goal reached: The directors declare a dividend.” If the input paragraph is in Chinese, the names remain in English Snake_Case and the descriptions become Chinese sentences. The inference process stays the same.

7.4.4 Reliability and extensibility

7.5 From an engineering approximation of compositional semantics to executable knowledge

7.5.1 What the example establishes

Compositional semantics holds that the meaning of a whole is determined by the meanings of its parts and how they combine. This chapter puts that principle into code. ADT constructors (If, And, Will, and others), pattern matching, and forward closure give the sentences in a paragraph an executable semantic structure. This retains the compositional insight of Montague semantics while limiting the formal machinery to what the application needs.

7.5.2 A repeatable three-step method

  1. Sentence forms to ADTs. Map familiar forms such as “if … and … then …” to ADT constructors. The type defines the permitted shapes, and matching can be checked for exhaustiveness.

  2. Rules to closure. Use monotone forward chaining to compute the least fixed point, as in Datalog, deriving the desired conclusion step by step. For the positive propositional fragment used here, termination and a unique closure are guaranteed.

  3. LLM to JSON to ADT. With Structured Outputs or JSON mode, ask the LLM to produce {atoms, rules, observations}, then compile the result into the ADT and execute it. This automates the sequence from reading a paragraph to structuring its contents and drawing inferences. RAG can link results back to supporting evidence when needed.

7.5.3 Choosing this approach and extending it

7.5.4 How this complements modern LLMs

7.5.5 Reusable results of the chapter

7.5.6 Limits and precautions

7.5.7 Toward the final chapter

The final chapter returns to the main thread of the book: how algebraic code brings generation, composition, execution, and verification into a common structure. Natural language enters the system as a representation that can be parsed. Types and rules constrain that representation to form a program. Executing the program produces traceable results, which tests, evidence, or proofs can check. The path from language to knowledge to inference has become an engineering process that can be run and verified.

CHAPTER 8

Structure Defines the Boundary: From Algebraic Code to Verifiable Intelligence

Large language models have changed how programs receive input and generate candidates. The requirements for reliable software still hold. Data must have a recognizable shape, operations must follow explicit interfaces, composition must be explicable, and results must be reproducible and open to inspection. We began with tokens and arrived at a way of integrating generation into an engineered system, one that requires no special-purpose syntax.

8.1 Structure Goes Beyond Output Format

Writing model output as JSON does not by itself give us structure. Each field needs a defined role, each variant a closed boundary, and each composition a checkable contract. A result must be traceable to its inputs, its rules, and the steps that produced it. ADTs, pattern matching, functors, combinators, and computation graphs matter because they express in the program what counts as valid, whatever theoretical tradition they come from.

Likewise, a token in an engineered system is more than a string cut out by a model’s tokenizer. It should carry a type, a source, a scope, constraints, and whatever evidence is necessary. A downstream program can then decide whether two tokens may be combined, how each can be transformed, and when one must be rejected. Constraining free-form generation in this way turns a model’s capabilities into reusable software.

8.2 The Model Proposes and Structure Constrains

LLMs are particularly well suited to generating candidates, aligning meanings, and making local transformations. A model can map natural language to a function call, an ADT variant, or a graph node. It can also suggest an ordering among candidates. The model should not be the sole judge of validity. Type checking rules out malformed values. Pattern matching supports exhaustive case analysis. Lowering gives an abstraction a consistent implementation on a backend. Tests, rules, and evidence determine whether a result can be accepted.

This division of labor frees the model from the unrealistic demand that it always be right. It can propose freely while the system accepts cautiously. A failure now has a location: parsing, a type mismatch, conflicting constraints, a construct the backend cannot implement, insufficient evidence, or a failed acceptance check. Locating a failure gives us somewhere to start improving the system.

8.3 Composition Outlasts Scale

Models, frameworks, and hardware change. The laws of composition are comparatively stable. Kleisli composition sequences long-chain functions with effects. Applicative combines independent effects. An ADT expresses a closed set of states, node contracts connect a graph, and automatic differentiation uses forward and reverse transformations of the same computational relationship. Making these laws explicit frees the system from dependence on any one model version or runtime.

When designing an LLM system, look first for a small, stable algebraic interface. Adding prompts, layers of agents, or more models can come later. A smaller interface is easier to test. A closed set of variants is easier to cover exhaustively. Pure composition makes a computation easier to replay. Keeping evidence close to a result makes it easier to audit. Scale can raise the ceiling on capability. Structure determines whether that capability can be deployed safely.

8.4 Verify Before Accepting

Verification does not require a formal proof for every conclusion. Depending on the task, it may mean successful compilation, a type or shape check, unit tests, a numerical error bound, closure under a set of rules, citation coverage, or human review. What matters is that the system provides a criterion independent of linguistic fluency, before or after generation. A plausible sentence alone cannot show that a program runs, that the evidence is sufficient, or that a rule applies.

This gives a minimal meaning to “algebraic agent” as we use it here: an execution interface governed by types, operations, and laws of composition. A humanlike persona is incidental. Retrieval, inference, tool calls, and result rendering may all play a part, provided that they exchange structured tokens and leave a trace that can be reviewed. The value of an agent lies in its ability to turn a complex workflow into steps we can compose, observe, and check against acceptance criteria.

8.5 From the Printed Book to Running Code

The core edition keeps enduring material in the printed book and brings assignments, starter code, and acceptance criteria together at https://github.com/PanWuming/AlgebraicCode. The arrangement illustrates the book’s method. The printed text records lasting structures, while the repository carries implementations that need to run and evolve. From any chapter you can turn to the repository and use its tests to check your understanding of the corresponding contract.

If you carry away one way of judging a result, let it be this: ask what structure carries it, how that structure is composed and executed, and who will verify it. Large language models make generation inexpensive. Algebraic code helps us see the boundaries of correctness again. Reliable intelligence can give an answer and account for how it was constructed, executed, and verified.

References

[1] Abbott, M., Altenkirch, T., & Ghani, N. (2005). Containers: Constructing Strictly Positive Types. Theoretical Computer Science, 342(1), 3–27. https://doi.org/10.1016/j.tcs.2005.06.002

[2] Apple Inc. (2024a). The Swift Programming Language. https://docs.swift.org/swift-book/

[3] Apple Inc. (2024b). The Swift Programming Language: Enumerations. https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html

[4] Apple Inc. (2025a). flatMap(_:)—AsyncSequence. https://developer.apple.com/documentation/swift/asyncsequence/flatmap(_:)-5j8ra

[5] Apple Inc. (2025b). flatMap(_:)—Optional. https://developer.apple.com/documentation/swift/optional/flatmap(_:)

[6] Apple Inc. (2025c). flatMap(_:)—Result. https://developer.apple.com/documentation/swift/result/flatmap(_:)

[7] Apple Inc. (2025d). flatMap(_:)—Sequence. https://developer.apple.com/documentation/swift/sequence/flatmap(_:)-jo2y

[8] Backus, J. (1978). Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs. Communications of the ACM, 21(8), 613–641. https://doi.org/10.1145/359576.359579

[9] Bahdanau, D., Cho, K., & Bengio, Y. (2015). Neural machine translation by jointly learning to align and translate. arXiv preprint, arXiv:1409.0473. https://arxiv.org/abs/1409.0473

[10] Baydin, A. G., Pearlmutter, B. A., Radul, A. A., & Siskind, J. M. (2018). Automatic Differentiation in Machine Learning: A Survey. Journal of Machine Learning Research, 18(153), 1–43.

[11] Bengio, Y., Simard, P., & Frasconi, P. (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2), 157–166. https://doi.org/10.1109/72.279181

[12] Burris, S. N., & Sankappanavar, H. P. (1981). A Course in Universal Algebra. Springer. https://math.unl.edu/~s-burris/

[13] Burstall, R. M., MacQueen, D., & Sannella, D. (1980). HOPE: An Experimental Applicative Language. Proceedings of the 1980 ACM Conference on LISP and Functional Programming. https://doi.org/10.1145/800087.802799

[14] Carion, N., Massa, F., Synnaeve, G., Usunier, N., Kirillov, A., & Zagoruyko, S. (2020). End-to-End Object Detection with Transformers. arXiv preprint, arXiv:2005.12872. https://arxiv.org/abs/2005.12872

[15] Chen, W., Ma, X., Wang, X., & Cohen, W. W. (2022). Program of Thoughts Prompting: Disentangling Computation from Reasoning for Numerical Reasoning Tasks. arXiv preprint, arXiv:2211.12588. https://doi.org/10.48550/arXiv.2211.12588

[16] Crocker, D., & Overell, P. (2008). RFC 5234: Augmented BNF for Syntax Specifications: ABNF. IETF. https://www.rfc-editor.org/rfc/rfc5234

[17] Dai, Z., Yang, Z., Yang, Y., Carbonell, J., Le, Q. V., & Salakhutdinov, R. (2019). Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context. Proceedings of ACL 2019. https://aclanthology.org/P19-1285/

[18] Damas, L., & Milner, R. (1982). Principal type-schemes for functional programs. POPL ’82: Proceedings of the 9th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 207–212. https://doi.org/10.1145/582153.582176

[19] d’Avila Garcez, A., & Lamb, L. C. (2023). Neurosymbolic AI: the 3rd wave. Artificial Intelligence Review, 56, 12387–12406. https://doi.org/10.1007/s10462-023-10448-w

[20] Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., & Houlsby, N. (2021). An Image is Worth 16×16 Words: Transformers for Image Recognition at Scale. International Conference on Learning Representations (ICLR 2021). https://arxiv.org/abs/2010.11929

[21] Eilenberg, S., & Mac Lane, S. (1945). General Theory of Natural Equivalences. Transactions of the American Mathematical Society, 58(2), 231–294.

[22] Eilenberg, S., & Moore, J. C. (1965). Adjoint Functors and Triples. Transactions of the American Mathematical Society, 80, 246–285.

[23] Elliott, C. (2018). The simple essence of automatic differentiation. Proceedings of the ACM on Programming Languages (PACMPL), 2(ICFP), 1–29. https://doi.org/10.1145/3236765

[24] Ford, B. (2004). Parsing Expression Grammars: A Recognition-Based Syntactic Foundation. POPL ’04: Proceedings of the 31st ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 111–122. https://doi.org/10.1145/964001.964011

[25] Gao, L., Madaan, A., Zhou, S., Alon, U., Liu, P., Yang, Y., Callan, J., & Neubig, G. (2022). PAL: Program-aided Language Models. arXiv preprint, arXiv:2211.10435. https://doi.org/10.48550/arXiv.2211.10435

[26] Gers, F. A., Schmidhuber, J., & Cummins, F. (2000). Learning to forget: Continual prediction with LSTM. Neural Computation, 12(10), 2451–2471. https://doi.org/10.1162/089976600300015015

[27] GHC Development Team. (2025). The Glasgow Haskell Compiler (GHC). https://www.haskell.org/ghc/

[28] Gibbons, J., & Oliveira, B. C. d. S. (2009). The Essence of the Iterator Pattern. Journal of Functional Programming, 19(3–4), 377–402. https://doi.org/10.1017/S0956796809007291

[29] Goguen, J. A., Thatcher, J. W., Wagner, E. G., & Wright, J. B. (1977). Initial Algebra Semantics and Continuous Algebras. Journal of the ACM, 24(1), 68–95. https://doi.org/10.1145/321992.321997

[30] Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press. https://www.deeplearningbook.org/

[31] Google DeepMind. (2025a). Function calling with the Gemini API. https://ai.google.dev/gemini-api/docs/function-calling

[32] Google DeepMind. (2025b). Structured output | Gemini API. https://ai.google.dev/gemini-api/docs/structured-output

[33] Graves, A., Fernández, S., Gomez, F., & Schmidhuber, J. (2006). Connectionist temporal classification: Labelling unsegmented sequence data with recurrent neural networks. Proceedings of the 23rd International Conference on Machine Learning (ICML ’06), 369–376. https://doi.org/10.1145/1143844.1143891

[34] Graves, A., Mohamed, A., & Hinton, G. (2013). Speech recognition with deep recurrent neural networks. 2013 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), 6645–6649. https://doi.org/10.1109/ICASSP.2013.6638947

[35] Greff, K., Srivastava, R. K., Koutník, J., Steunebrink, B. R., & Schmidhuber, J. (2017). LSTM: A search space odyssey. IEEE Transactions on Neural Networks and Learning Systems, 28(10), 2222–2232. https://doi.org/10.1109/TNNLS.2016.2582924

[36] Griewank, A., Kulshreshtha, K., & Walther, A. (2012). On the numerical stability of algorithmic differentiation. Computing, 94(2–4), 125–149. https://doi.org/10.1007/s00607-011-0162-z

[37] Griewank, A., & Walther, A. (2008). Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation (2nd ed.). Society for Industrial and Applied Mathematics (SIAM). https://epubs.siam.org/doi/book/10.1137/1.9780898717761

[38] Gu, A., & Dao, T. (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. arXiv preprint, arXiv:2312.00752. https://arxiv.org/abs/2312.00752

[39] HaskellWiki Contributors. (2025). Catamorphisms. https://wiki.haskell.org/Catamorphisms

[40] Hitzler, P., & Sarker, M. K. (Eds.). (2021). Neuro-Symbolic Artificial Intelligence: The State of the Art (Vol. 338). IOS Press.

[41] Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8), 1735–1780. https://doi.org/10.1162/neco.1997.9.8.1735

[42] Hoffmann, J., Borgeaud, S., Mensch, A., Buchatskaya, E., Cai, T., Rutherford, E., de Las Casas, D., Hendricks, L. A., Welbl, J., Clark, A., Hennigan, T., Noland, E., Millican, K., van den Driessche, G., Damoc, B., Guy, A., Osindero, S., Simonyan, K., Elsen, E., … Sifre, L. (2022). Training Compute-Optimal Large Language Models. Advances in Neural Information Processing Systems 35 (NeurIPS 2022). https://arxiv.org/abs/2203.15556

[43] Huang, L., Yu, W., Ma, W., Zhong, W., Feng, Z., Wang, H., Chen, Q., Peng, W., Feng, X., Qin, B., & Liu, T. (2023). A Survey on Hallucination in Large Language Models: Principles, Taxonomy, Challenges, and Open Questions. arXiv preprint arXiv:2311.05232. https://doi.org/10.48550/arXiv.2311.05232

[44] Huang, Y., & et al. (2024). A survey on retrieval-augmented generation for large language models. arXiv, 2404.10981.

[45] Hugging Face. (2020). GPT-2—Hugging Face Transformers Documentation. https://huggingface.co/docs/transformers/en/model_doc/gpt2

[46] Hughes, J. (1989). Why Functional Programming Matters. The Computer Journal, 32(2), 98–107. https://doi.org/10.1093/comjnl/32.2.98

[47] Hughes, J. (2000). Generalising Monads to Arrows. Science of Computer Programming, 37(1–3), 67–111. https://doi.org/10.1016/S0167-6423(99)00023-4

[48] Hutton, G. (2016). Programming in Haskell (2nd ed.). Cambridge University Press.

[49] Ismayilzada, M., Circi, D., Sälevä, J., Sirin, H., Köksal, A., Dhingra, B., Bosselut, A., Ataman, D., & van der Plas, L. (2024). Evaluating Morphological Compositional Generalization in Large Language Models. arXiv preprint, arXiv:2410.12656. https://doi.org/10.48550/arXiv.2410.12656

[50] Janssen, T. M. V. (2008). Montague Semantics. In E. N. Zalta (Ed.), The Stanford Encyclopedia of Philosophy. Stanford University. https://plato.stanford.edu/entries/montague-semantics/

[51] JAX Team. (2025). JAX Documentation. https://jax.readthedocs.io/en/latest/

[52] JetBrains Kotlin Team. (2025). Kotlin Compiler and Language Reference. https://kotlinlang.org/

[53] Jiang, A. Q., Sablayrolles, A., Mensch, A., & et al. (2023). Mistral 7B. arXiv preprint, arXiv:2310.06825. https://arxiv.org/abs/2310.06825

[54] Jiang, P., & Cai, X. (2024). A Survey of Semantic Parsing Techniques. Symmetry, 16(9), 1201. https://doi.org/10.3390/sym16091201

[55] Jones, S. P. (Ed.). (2003). Haskell 98 Language and Libraries: The Revised Report. Journal of Functional Programming, 13(1). https://www.haskell.org/definition/haskell98-report.pdf

[56] Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B., Chess, B., Child, R., Gray, S., Radford, A., Wu, J., & Amodei, D. (2020). Scaling Laws for Neural Language Models. arXiv preprint, arXiv:2001.08361. https://arxiv.org/abs/2001.08361

[57] Kelly, G. M. (1982). Basic Concepts of Enriched Category Theory. Cambridge University Press.

[58] Klabnik, S., & Nichols, C. (2018). The Rust Programming Language—Enums and Pattern Matching. https://doc.rust-lang.org/book/ch06-00-enums.html

[59] Kleisli, H. (1965). Every Standard Construction is Induced by a Pair of Adjoint Functors. Proceedings of the American Mathematical Society, 16(3), 544–546.

[60] Kowalski, R. A. (1974). Predicate Logic as a Programming Language. Proceedings of IFIP Congress 1974, 569–574. https://www.doc.ic.ac.uk/~rak/papers/IFIP74.pdf

[61] Leijen, D., & Meijer, E. (2001). Parsec: Direct Style Monadic Parser Combinators for the Real World. Proceedings of the 2001 Haskell Workshop, 1–12.

[62] Leroy, X., Doligez, D., Frisch, A., Garrigue, J., Rémy, D., & Vouillon, J. (2025). The OCaml System: Documentation and User’s Manual. https://ocaml.org/manual/

[63] Lewis, P., Perez, E., Piktus, A., & others. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. Advances in Neural Information Processing Systems (NeurIPS 2020). https://proceedings.neurips.cc/paper/2020/hash/6b493230205f780e1bc26945df7481e5-Abstract.html

[64] Liskov, B., & Zilles, S. (1974). Programming with Abstract Data Types. Proceedings of the ACM SIGPLAN Conference on Very High Level Languages. https://doi.org/10.1145/800233.807045

[65] Luong, M.-T., Pham, H., & Manning, C. D. (2015). Effective Approaches to Attention-based Neural Machine Translation. Proceedings of EMNLP 2015, 1412–1421. https://doi.org/10.18653/v1/D15-1166

[66] Mac Lane, S. (1963). Natural Associativity and Commutativity. Rice University Studies, 49(4), 28–46.

[67] Mac Lane, S. (1998). Categories for the Working Mathematician (2nd ed., Vol. 5). Springer.

[68] Maranget, L. (2007). Warnings for Pattern Matching. INRIA.

[69] Marlow, S. (Ed.). (2010a). Haskell 2010 Language Report. https://www.haskell.org/onlinereport/haskell2010/

[70] Marlow, S. (2010b). Haskell 2010 Language Report. Haskell Prime Committee.

[71] Marlow, S. & others. (2016). Desugaring Haskell’s do-Notation into Applicative Operations. https://simonmar.github.io/bib/papers/applicativedo.pdf

[72] McBride, C., & Paterson, R. (2008). Applicative Programming with Effects. Journal of Functional Programming, 18(1), 1–13. https://doi.org/10.1017/S0956796807006326

[73] Microsoft. (2025). Pattern matching overview—A tour of C#. https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/pattern-matching

[74] Microsoft Azure AI. (2025). How to use structured outputs with Azure OpenAI. https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/structured-outputs

[75] Microsoft Learn. (2021a). Discriminated Unions—F#. https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/discriminated-unions

[76] Microsoft Learn. (2021b). Results—F#. https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/results

[77] Microsoft Learn Team. (2025). F# Recursive Functions and Pattern Matching. https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/functions/recursive-functions

[78] Milner, R., Tofte, M., Harper, R., & MacQueen, D. (1997). The Definition of Standard ML (Revised). MIT Press. https://smlfamily.github.io/sml97-defn.pdf

[79] Moggi, E. (1991). Notions of Computation and Monads. Information and Computation, 93(1), 55–92. https://doi.org/10.1016/0890-5401(91)90052-4

[80] Nerode, A., & Shore, R. A. (1997). Logic for Applications (2nd ed.). Springer. https://doi.org/10.1007/978-1-4612-2318-4

[81] .NET Foundation & Microsoft. (2025a). TorchSharp: .NET bindings for PyTorch—Documentation. https://dotnet.microsoft.com/en-us/learn/ml-dotnet/get-started-torchsharp

[82] .NET Foundation & Microsoft. (2025b). TorchSharp: .NET for Torch and PyTorch (GitHub Repository). https://github.com/dotnet/TorchSharp

[83] ONNX Project. (n.d.-a). Broadcasting in ONNX. Retrieved October 18, 2025, from https://onnx.ai/onnx/repo-docs/Broadcasting.html

[84] ONNX Project. (n.d.-b). ONNX Operators—ONNX 1.20.0 documentation. Retrieved October 18, 2025, from https://onnx.ai/onnx/operators/

[85] ONNX Project. (2025). ONNX Documentation. https://onnx.ai/onnx/

[86] OpenAI. (2025a). Function Calling (Responses API Tools). https://platform.openai.com/docs/guides/function-calling

[87] OpenAI. (2025b). Structured Outputs. https://platform.openai.com/docs/guides/structured-outputs

[88] OpenJDK. (2021). JEP 409: Sealed Classes. https://openjdk.org/jeps/409

[89] OpenJDK. (2023). JEP 441: Pattern Matching for switch. https://openjdk.org/jeps/441

[90] Pan, S., Luo, L., Wang, Y., & others. (2024). Unifying Large Language Models and Knowledge Graphs: A Roadmap. IEEE Transactions on Knowledge and Data Engineering, 36(7), 3580–3599. https://doi.org/10.1109/TKDE.2023.3334770

[91] Paterson, R. (2007). Control.Applicative (Haskell Base Library) – Design Notes and Documentation.

[92] Pearlmutter, B. A., & Siskind, J. M. (2008). Reverse-Mode AD in a Functional Framework: Lambda the Ultimate Backpropagator. ACM Transactions on Programming Languages and Systems (TOPLAS), 30(2), 7:1-7:36. https://doi.org/10.1145/1330017.1330018

[93] Peyton Jones, S. L. (1987). The Implementation of Functional Programming Languages. Prentice Hall.

[94] Pierce, B. C. (2002). Types and Programming Languages. MIT Press.

[95] PyTorch Core Team. (2025). PyTorch Documentation (Stable). https://pytorch.org/docs/stable/

[96] Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners. OpenAI. https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf

[97] Reynolds, J. C. (1983a). Types, abstraction and parametric polymorphism. Information Processing 83, 513–523.

[98] Reynolds, J. C. (1983b). Types, Abstraction and Parametric Polymorphism. In R. E. A. Mason (Ed.), Information Processing 83 (Vol. 9, pp. 513–523). North-Holland.

[99] Robinson, J. A. (1965a). A machine-oriented logic based on the resolution principle. Journal of the ACM, 12(1), 23–41.

[100] Scala Center. (2025). Algebraic Data Types | Scala 3 Book. https://docs.scala-lang.org/scala3/book/types-adts-gadts.html

[101] Scala Center, EPFL. (2025). Scala 3 Compiler and Language Reference. https://www.scala-lang.org/

[102] Schuster, M., & Paliwal, K. K. (1997). Bidirectional recurrent neural networks. IEEE Transactions on Signal Processing, 45(11), 2673–2681. https://doi.org/10.1109/78.650093

[103] Shaw, P., Uszkoreit, J., & Vaswani, A. (2018). Self-Attention with Relative Position Representations. Proceedings of NAACL-HLT 2018. https://aclanthology.org/N18-2074/

[104] Sutskever, I., Vinyals, O., & Le, Q. V. (2014). Sequence to sequence learning with neural networks. Advances in Neural Information Processing Systems 27 (NeurIPS 2014), 3104–3112. https://papers.neurips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf

[105] Syme, D., Petricek, T., & Lomov, D. (2007). Active Patterns in F#. Microsoft Research.

[106] The Rust Project Developers. (2025). Rust Compiler (rustc) and Language Documentation. https://www.rust-lang.org/

[107] Touvron, H., Lavril, T., Izacard, G., Martinet, X., Lachaux, M.-A., Lacroix, T., Rozière, B., Goyal, N., Hambro, E., Azhar, F., Rodriguez, A., Joulin, A., Grave, E., & Lample, G. (2023). LLaMA: Open and Efficient Foundation Language Models. arXiv preprint, arXiv:2302.13971. https://arxiv.org/abs/2302.13971

[108] Touvron, H., Martin, L., Stone, K., & et al. (2023). Llama 2: Open Foundation and Fine-Tuned Chat Models. arXiv preprint, arXiv:2307.09288. https://arxiv.org/abs/2307.09288

[109] TypeScript Team. (2025a). Documentation—Narrowing. https://www.typescriptlang.org/docs/handbook/2/narrowing.html

[110] TypeScript Team. (2025b). Handbook—Unions and Intersection Types. https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html

[111] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. Advances in Neural Information Processing Systems 30 (NeurIPS 2017), 5998–6008. https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf

[112] Vytiniotis, D., Weirich, S., Jones, S. P., & Washburn, G. (2006). Simple Unification-based Type Inference for GADTs. ICFP ’06: Proceedings of the 11th ACM SIGPLAN International Conference on Functional Programming, 50–61. https://doi.org/10.1145/1159803.1159811

[113] Wadler, P. (1989a). Theorems for Free! Proceedings of the Fourth ACM Conference on Functional Programming Languages and Computer Architecture (FPCA ’89), 347–359. https://doi.org/10.1145/99370.99404

[114] Wadler, P. (1989b). Theorems for Free!

[115] Wadler, P. (1992a). Comprehending Monads. Mathematical Structures in Computer Science, 2(4), 461–493.

[116] Wadler, P. (1992b). The Essence of Functional Programming. Proceedings of the 19th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL ’92), 1–14. https://doi.org/10.1145/143165.143169

[117] Wadler, P. (1995). Monads for Functional Programming. In J. Jeuring & E. Meijer (Eds.), Advanced Functional Programming (Vol. 925, pp. 24–52). Springer. https://doi.org/10.1007/3-540-59451-5_2

[118] Wei, J., Wang, X., Schuurmans, D., Bosma, M., Ichter, B., Xia, F., Chi, E. H., Le, Q. V., & Zhou, D. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. NeurIPS 2022. https://arxiv.org/abs/2201.11903

[119] Wei, J., Wang, X., Schuurmans, D., & others. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. arXiv preprint, arXiv:2201.11903. https://doi.org/10.48550/arXiv.2201.11903

[120] Weirich, S., Vytiniotis, D., Jones, S. P., & Washburn, G. (2006). Translating GADTs to System F. University of Pennsylvania.

[121] Wikipedia contributors. (2025). Backus–Naur Form. https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form

[122] Wu, N., & Hinze, R. (2013). Unifying Structured Recursion Schemes. University of Oxford, Department of Computer Science Technical Report. https://www.cs.ox.ac.uk/people/nicolas.wu/papers/recursion.pdf

[123] Wu, Y., Schuster, M., Chen, Z., Le, Q. V., Norouzi, M., Macherey, W., Krikun, M., Cao, Y., Gao, Q., Macherey, K., Klingner, J., Shah, A., Johnson, M., Liu, X., Kaiser, Ł., Gouws, S., Kato, Y., Kudo, T., Kazawa, H., … Dean, J. (2016). Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint, arXiv:1609.08144. https://arxiv.org/abs/1609.08144

[124] Xiong, H., Wang, Z., Li, X., Bian, J., Xie, Z., Mumtaz, S., Al-Dulaimi, A., & Barnes, L. E. (2024). Converging Paradigms: The Synergy of Symbolic and Connectionist AI in LLM-Empowered Autonomous Agents. arXiv preprint, arXiv:2407.08516. https://doi.org/10.48550/arXiv.2407.08516

[125] Yao, S., Zhao, J., Yu, D., Du, N., Shafran, I., Narasimhan, K. R., & Cao, Y. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. ICLR 2023. https://openreview.net/forum?id=WE_vluYUL-X

Subject Index

Entries are in alphabetical order. Select a section number to jump to its discussion. Chapter and front-matter references point to the corresponding heading.

A B C D E F G H I J K L M N O P R S T U V W

A

Add
§ 5.7.1
Additive attention
§ 5.4
ADT
Roundtable 10 Chapter 1 § 1.2 § 1.5.2 § 3.1 § 3.2.6 § 3.4 § 3.4.4 § 3.5 § 3.5.1 § 3.5.7 § 3.6 § 5.5 § 6.5.2 § 7.1 § 7.2 § 7.2.3 § 7.2.4 § 7.2.7 § 7.2.8 § 7.4
Algebraic code
§ 1.1 § 1.5 § 8.1
Algebraic data type
Roundtable 10 Chapter 1 § 1.2 § 1.5.2 § 3.1 § 3.2.6 § 3.4 § 3.4.4 § 3.5 § 3.5.1 § 3.5.7 § 3.6 § 5.5 § 6.5.2 § 7.1 § 7.2 § 7.2.3 § 7.2.4 § 7.2.7 § 7.2.8 § 7.4
Algebraic effects
§ 1.2
Algebraic pattern matching
Roundtable 10 § 1.2 § 3.2 § 3.3 § 3.3.1
Alternative
Roundtable 6
APM
Roundtable 10 § 1.2 § 3.2 § 3.3 § 3.3.1
Applicative
Roundtable 2 § 2.3 § 2.3.2 § 2.3.3 § 2.3.5
AR-Agent
§ 1.4 § 1.4.3
Attention
§ 5.3 § 5.4 § 5.12
Attention architecture
Chapter 5
Automatic differentiation
Chapter 6 § 6.4 § 6.6 § 6.8

B

Batch
§ 6.3 § 6.4.3 § 6.8.5
Bayesian methods
§ 6.2.2
BNF
§ 3.5.6

C

Candidate generation
§ 8.2
Cast
§ 5.9.10
Category theory
§ 1.2 § 2.5.1
Chain rule
§ 6.1.1
Companion code
§ 8.5
Compositional semantics
§ 7.1 § 7.5
Concat
§ 5.9.3
Constant
§ 5.10 § 5.10.1
Constant tensors
§ 5.10.1
ConstantOfShape
§ 5.10.2

D

Deep learning
Chapter 6 § 6.2.1
Differential geometry
§ 6.1.2
Dimension permutation
§ 5.9.2
Div
§ 5.7.1
Duality identity
§ 6.1.1

E

Elementwise binary operators
§ 5.7.1
Empirical risk minimization
§ 6.2.1

F

F#
§ 1.2
FAM
Chapter 1 § 1.2
Function composition
§ 1.2
Functor
Roundtable 1 § 2.2 § 2.2.3 § 2.5.2 § 2.5.7

G

GADT
§ 3.5.3
Gather
§ 5.9.6
Gather along one axis
§ 5.9.6
GELU
§ 5.12.2
Gemm
§ 5.6.2
General matrix multiplication
§ 5.6.2
GPT-2
§ 5.1 § 5.2 § 5.3
GPT-4o
§ 7.4

H

Haskell
§ 1.2
Higher-order function
§ 1.2

I

Immutability
§ 1.2
Initial algebra
§ 3.5.2

J

Jacobian–vector product
§ 6.1.1 § 6.2.5 § 6.4 § 6.4.2 § 6.6.2 § 6.6.3
JAX
§ 2.8
Jones Problem
§ 7.2 § 7.2.4 § 7.2.6 § 7.3 § 7.4
JVP
§ 6.1.1 § 6.2.5 § 6.4 § 6.4.2 § 6.6.2 § 6.6.3

K

Kleisli
Roundtable 8 § 2.6 § 2.6.1
Kotlin
§ 1.2 § 2.4.4 § 3.2.3 § 3.6.1

L

Lambda calculus
Preface 1
Lambda closures
§ 1.2
Large language models
§ 1.3 § 1.3.2 § 1.4 § 1.4.5 § 1.6.4 § 4.5 § 5.1 § 5.5 § 7.1 § 7.4.2 § 7.5.4
Laws of composition
§ 2.7 § 8.3
LayerNormalization
§ 5.12.3
Lazy evaluation
§ 1.2
LLM
§ 1.3 § 1.3.2 § 1.4 § 1.4.5 § 1.6.4 § 4.5 § 5.1 § 5.5 § 7.1 § 7.4.2 § 7.5.4
Long-chain function
Roundtable 8 Roundtable 9 Roundtable, coda Chapter 1 § 1.1 Chapter 2 § 2.1 § 2.1.2 § 2.1.3 § 3.4.4 § 3.6
Lowering
§ 4.3 § 4.4.2 § 4.5
LSTM
§ 4.4 § 4.4.1 § 4.4.2

M

Machine learning
Chapter 6 § 6.2
Manifolds
§ 6.1.2
MatMul
§ 5.6.1
Matrix multiplication
§ 5.6.1 § 5.6.2
Monad
Roundtable 3 § 2.4 § 2.4.1 § 2.4.2 § 2.4.5
Monoidal
Roundtable 7
Montague semantics
§ 7.1
Mul
§ 5.7.1
Multi-head attention
§ 5.4

N

Natural transformation
Roundtable 1 Roundtable 4 Roundtable 5 Roundtable 7 Roundtable, coda § 1.2 Chapter 2 § 2.5 § 2.5.1 § 2.5.2 § 2.5.7
NodeADT
§ 5.13
Nonparametric methods
§ 6.2.4

O

Objective function
§ 6.2
ONNX
Chapter 5 § 5.3 § 5.5
Operators
§ 4.2.1 § 4.3.6 Chapter 5 § 5.7.1
Optimization
Chapter 6 § 6.2.2

P

Pattern matching
§ 3.2 § 3.3 § 3.4.3
Pow
§ 5.7.2
Product types
§ 3.1.1
Profile
§ 4.5
Pure function
§ 1.2 § 2.7 § 2.7.1

R

Range
§ 5.10.3
Recursion
Chapter 3 § 3.3 § 3.3.1 § 3.3.2 § 3.3.3
ReduceMean
§ 5.8.1
Reduction
§ 5.8
Reinforcement learning
§ 6.2.3
Reshape
§ 5.9.1
ReverseGraph
§ 6.8 § 6.8.1
Rust
§ 1.2 § 3.2.4

S

Scaling laws
§ 5.1
Shape
§ 4.3.2 § 5.2.4 § 5.9 § 5.9.7 § 6.3.2 § 6.8.3
Shape vector
§ 5.9.7
Slice
§ 5.9.5
Slicing
§ 5.9.5
Softmax
§ 5.12.1
Split
§ 5.9.4
Sqrt
§ 5.7.3
Squeeze
§ 5.9.9
Structured tokens
§ 1.3 § 1.3.3 § 8.2
Sub
§ 5.7.1
Sum types
§ 3.1.1
Sum-of-Products
Chapter 3
Sweetest layer
§ 4.2 § 4.4 § 4.4.2
Swift
§ 1.2 § 1.5.3 § 2.1.2 § 2.2.1 § 2.4.1 § 2.4.2 § 2.5.6 § 3.2.1 § 3.3.3 § 3.6.1 § 7.3

T

Token paradigm
Chapter 1 § 1.1 § 1.3 § 8.1
Transformer
§ 5.1 § 5.2
Transpose
§ 5.9.2
Traversable
Roundtable 4 Roundtable 5 Roundtable 7 Roundtable 10 Roundtable, coda § 2.7.4 § 2.7.5

U

Unit type
§ 3.1.1
Unsqueeze
§ 5.9.8
UR-Agent
§ 1.4 § 1.4.4

V

Variants
§ 1.2 § 3.4 § 3.5 § 3.5.4 § 3.6 § 4.2
Vector–Jacobian product
§ 6.1.1 § 6.2.5 § 6.4 § 6.4.2 § 6.5 § 6.6.1 § 6.6.3 § 6.7.4 § 6.8.3
Verifiable intelligence
§ 8.1 § 8.4
Verification
§ 8.4
VJP
§ 6.1.1 § 6.2.5 § 6.4 § 6.4.2 § 6.5 § 6.6.1 § 6.6.3 § 6.7.4 § 6.8.3

W

Where
§ 5.11.1