Bagl compiler
I wrote the compiler for Bagl, a small functional language where tensor shapes are part of the type and the compiler derives gradients for you.
- Year
- 2025
- Built with
- OCaml, compilers, type inference
Overview
Bagl is a small functional language in which tensors, arrays of floats with one or two dimensions, are a built-in type. Two things set it apart.
- Tensor shapes are part of the type, so multiplying a 2x3 matrix by a 2x2 matrix is caught at compile time instead of failing at run time.
gradturns a function into its derivative. For a loss computed over tensors, the compiler writes the gradient code itself, so you can train a model in plain Bagl.
I wrote the compiler in OCaml, along with a bytecode virtual machine, a REPL, a language server for code editors and a browser playground. Compiled to JavaScript with js_of_ocaml, the whole compiler weighs about 160 KB (50 KB compressed). You can try it in the playground or in the language reference, where every example can be edited and run.

How it works
A hand-written lexer and a recursive descent parser turn the source into a syntax tree. Every node keeps its position in the file, so errors point at the exact spot.
Next, the compiler rewrites each grad call into ordinary Bagl code. Scalar functions get symbolic derivatives. Functions of a tensor get reverse mode code, which computes the gradient for every input in a single backward pass.
Type inference uses Hindley-Milner, the algorithm behind ML and OCaml that works out every type without annotations. Type variables live in a union-find structure, so unifying two types links them in place. Tensor dimensions have union-find variables of their own, and that is where shape errors surface.
The program is then lowered to an intermediate representation made of basic blocks, which are runs of instructions with no jumps in between. Four optimization passes run over it, and code generation emits stack bytecode for the virtual machine. The bytecode can also be saved to a .baglc file.
Design decisions
- OCaml. Algebraic data types and pattern matching keep the definitions of the syntax tree, the intermediate representation and the bytecode short and safe. In Rust, the shared union-find graph would have meant constant fights with the borrow checker.
- Differentiate before type checking. Because
gradis rewritten first, later stages need no special cases, and derivatives are type checked like any other code. The price is that tensor parameters must be annotated. Anything the rewrite can't handle becomes a compile error, never a wrong gradient. - No type classes.
+picks int or float from its operands, which keeps the checker to a single pass. The catch is thatfn x -> x + xis typedint -> intunless you annotate it. - A stack machine. Generating code for it is close to mechanical, and its bytecode is easy to save. A register machine would have needed a register allocator.
Problems I ran into
The virtual machine has separate instructions for ints and floats, and lowering chose between them by running type inference again on each subexpression. When a variable was missing from that environment, lowering fell back to int, so some correct float programs crashed the virtual machine. I found and fixed three cases, one for lambda parameters and two for letrec. An early grad test caught the first, because the derivative of x * x is x + x, a shape no hand-written test had used.
Smaller bugs followed the same pattern, a passing test suite hiding a shape nobody had tested.
(x + 1.0) + xtype checked but(x + x) + 1.0didn't. Inference now waits until a binding is generalized before defaulting to int.- A top level
ifcrashed code generation, because local variables were allocated lazily. Every test passed, since none had that shape. 0 - 5came back from a.baglcfile as 4294967291. The reader now extends the sign, and round trip tests cover it.
Results
- 104 test cases cover the lexer, the parser, types, lowering, tensors, gradients, and programs that must be rejected.
- Gradients are checked against finite differences, which estimate a slope from tiny changes in the input, and agree to within 1e-4.
examples/train_xor.baglruns 200 steps of gradient descent, and a test checks that the weights reach the exact solution [1, 1, -2] to within 1e-3.- CI runs the tests, the examples, and all 21 examples from the language reference through the browser build.
What I'd do next
- Lowering should read types from inference instead of inferring them again. A typed syntax tree is the next refactor in my notes, and it would remove the whole family of bugs described above.
- The intermediate representation isn't in SSA form, where each variable is assigned exactly once, so common subexpression elimination only works within a block. SSA would let it work across blocks.
- A
Numconstraint would make the numeric operators fully polymorphic.