Skip to content

Blog

ExoJIT: define and run fused kernels in Python

User-schedulable languages like the Exo Python-DSL let users write numerical kernels and declaratively optimize their scheduling (e.g. loop unrolling).

So far, benchmarking any given schedule in the Python-DSL and invoking it in a CPython runtime required several tedious steps.

This is because Exo’s compiler emits C and header files, requiring separate compilation, linking process and FFI calls or CPython extensions.

We introduce exojit, a just-in-time compiler for Exo procedures that alleviates all these pain-points, by letting users annotate their Exo functions with @jit(optimize=...) and invoke them like regular Python functions.

The Exo compiler applies the schedule and verifies that invariances are held. Then we translate Exo’s LoopIR through xDSL to LLVM, use the MCJIT engine to generate the binary and bind it with CFFI.

---
config:
  htmlLabels: false
  flowchart:
    nodeSpacing: 18
    rankSpacing: 22
    padding: 8
    subGraphTitleMargin:
      top: 6
      bottom: 10
---
flowchart LR
    subgraph schedule["Part 1"]
        source["Python Exo<br/>@jit(optimize=...)"] --> rewrite["Schedule rewrite<br/>fission, reorder,<br/>tile, unroll"] --> loopir["LoopIR"]
    end

    subgraph lower["Part 2"]
        analyses["Analyses"] --> xdsl["xDSL MLIR"] --> dialect["LLVM dialect"]
    end

    subgraph jit["Part 3"]
        llvm["llvmlite IR"] --> optimize["O3 passes"] --> mcjit["MCJIT"] --> native["Native code"]
    end

    loopir --> analyses
    dialect --> llvm
    loopir -.-> exoc["C backend"] --> c["C<br/>--c"]
    dialect -.-> mlir["MLIR<br/>--mlir"]
    optimize -.-> asm["ASM<br/>AArch64"]

    style schedule fill:transparent
    style lower fill:transparent
    style jit fill:transparent
Part 1 - Exo source
@proc
def add4(x: f32[4], y: f32[4]):
    for i in seq(0, 4):
        x[i] += y[i]
Part 1 - Simplified C output
void add4(float *x, const float *y) {
    for (int i = 0; i < 4; i++) {
        x[i] += y[i];
    }
}
Part 2 - LLVM dialect
llvm.func @add4(%x: !llvm.ptr, %y: !llvm.ptr) {
  %c0 = llvm.mlir.constant(0 : i64) : i64
  %c1 = llvm.mlir.constant(1 : i64) : i64
  %c4 = llvm.mlir.constant(4 : i64) : i64
  llvm.br ^loop(%c0 : i64)

^loop(%i: i64):
  %more = llvm.icmp "slt" %i, %c4 : i64
  llvm.cond_br %more, ^body, ^exit

^body:
  %xi = llvm.getelementptr %x[%i] : (!llvm.ptr, i64) -> !llvm.ptr, f32
  %yi = llvm.getelementptr %y[%i] : (!llvm.ptr, i64) -> !llvm.ptr, f32
  %vx = llvm.load %xi : !llvm.ptr -> f32
  %vy = llvm.load %yi : !llvm.ptr -> f32
  %sum = llvm.fadd %vx, %vy : f32
  llvm.store %sum, %xi : f32, !llvm.ptr
  %next = llvm.add %i, %c1 : i64
  llvm.br ^loop(%next : i64)

^exit:
  llvm.return
}
Part 3 - AArch64 assembly
_add4:
    ldr     q0, [x1]
    ldr     q1, [x0]
    fadd.4s v0, v1, v0  ; SIMD optimization
    str     q0, [x0]
    ret

Users can now write, schedule, execute, benchmark and verify a kernel all in the same Python script, making experimentation with Exo a lot more pleasant to integrate into their existing workflow and opening up the door to faster iteration cycles for humans, LLMs and auto-schedulers.

For example, the following schedule reuses a small stack buffer and keeps memory accesses contiguous so the inner loop can be auto-vectorized. In our benchmark, the scheduled kernel ran 2.11x as fast as the unscheduled one.1

# /// script
# requires-python = "==3.14.*"
# dependencies = ["exojit @ git+https://github.com/sueszli/exojit"]
# ///

import math
import random

from exo import *
from exo.API import Procedure
from exo.libs.memories import DRAM_STACK
from exo.stdlib.scheduling import divide_loop, fission, lift_alloc, reorder_loops, set_memory, simplify, stage_mem

from exojit import jit


# The schedule transforms the 32×32 matmul into:
#
# acc = empty((2, 32), dtype=float32)  # one reusable stack tile
# for i in range(0, 32, 2):
#     acc[:, :] = 0.0
#     for k in range(32):
#         for ii in range(2):
#             for j in range(32):
#                 acc[ii, j] += A[i + ii, k] * B[k, j]
#     out[i:i + 2, :] = acc
def optimize_matmul(p: Procedure) -> Procedure:
    # found through llm autoresearch
    p = divide_loop(p, "j", 32, ["jo", "ji"], perfect=True)
    p = reorder_loops(p, "i jo")
    p = divide_loop(p, "i", 2, ["io", "ii"], perfect=True)
    p = stage_mem(p, p.find_loop("ii").as_block(), "out[2*io:2*io+2, 32*jo:32*jo+32]", "acc")
    p = fission(p, p.find_loop("k").before(), n_lifts=2)
    p = reorder_loops(p, "ji k")
    p = reorder_loops(p, "ii k")
    p = lift_alloc(simplify(p), "acc", n_lifts=2)
    return set_memory(p, "acc", DRAM_STACK)


@jit(optimize=optimize_matmul)
def matmul(
    out: f32[32, 32] @ DRAM,
    A: f32[32, 32] @ DRAM,
    B: f32[32, 32] @ DRAM,
):
    for i in seq(0, 32):
        for j in seq(0, 32):
            out[i, j] = 0.0
            for k in seq(0, 32):
                out[i, j] += A[i, k] * B[k, j]


def test_matmul():
    A = [[random.uniform(-1.0, 1.0) for _ in range(32)] for _ in range(32)]
    B = [[random.uniform(-1.0, 1.0) for _ in range(32)] for _ in range(32)]
    out = [[0.0] * 32 for _ in range(32)]
    expected = [[sum(A[i][k] * B[k][j] for k in range(32)) for j in range(32)] for i in range(32)]

    matmul(out, A, B)
    assert all(math.isclose(out[i][j], expected[i][j], rel_tol=1e-5, abs_tol=1e-5) for i in range(32) for j in range(32))


if __name__ == "__main__":
    test_matmul()

The matrix multiplication example shows what a schedule can do to optimize one kernel. We can also put several kernels behind a single @jit.

For instance, the query, key and value projections in attention are three matrix multiplications.

matmul(q, x, wq)
matmul(k, x, wk)
matmul(v, x, wv)

With ExoJIT, one call to fused_attention runs all three. Here matmul is the same matrix multiplication written as an Exo @proc.

from exo import DRAM, proc
from exojit import jit


@proc
def matmul(out: f32[32, 32] @ DRAM, a: f32[32, 32] @ DRAM, b: f32[32, 32] @ DRAM):
    ... # see above


@jit
def fused_attention(
    x: f32[32, 32] @ DRAM,
    wq: f32[32, 32] @ DRAM, wk: f32[32, 32] @ DRAM, wv: f32[32, 32] @ DRAM,
    q: f32[32, 32] @ DRAM, k: f32[32, 32] @ DRAM, v: f32[32, 32] @ DRAM,
):
    matmul(q, x, wq)
    matmul(k, x, wk)
    matmul(v, x, wv)


fused_attention(x, wq, wk, wv, q, k, v)

Separate dispatches

---
config:
  sequence:
    mirrorActors: false
    actorMargin: 28
    width: 100
    height: 34
---
sequenceDiagram
    participant P as CPython
    participant N as matmul
    P->>N: Project Q
    N-->>P: return
    P->>N: Project K
    N-->>P: return
    P->>N: Project V
    N-->>P: return

Fused kernel

---
config:
  sequence:
    mirrorActors: false
    actorMargin: 28
    width: 100
    height: 34
---
sequenceDiagram
    participant P as CPython
    participant F as fused_attention
    P->>F: Project Q, K and V
    F-->>P: return

We can apply the same principle to an entire machine learning model if it’s small enough, like Andrej Karpathy’s MicroGPT.

Median CPU time for a full 1,000-step training run for six MicroGPT implementations. Lower is better.

JAX was the only other compiler we tested that gave us the primitives to run the whole training loop in one compiled call. We wrote the loop with jax.lax.scan and compiled it with @jax.jit. On the CPU, ExoJIT was 1.37x faster than JAX and about 4x faster than NumPy and PyTorch.2

The MicroGPT implementation and its benchmark are in the ExoJIT repository.

It was fun to follow the model down to individual assembly instructions. We understand a little more now and there’s plenty left to try. Thanks for spending some of your curiosity with us.


  1. Apple M2 Pro (Arm64, 12 CPU cores). Median time per call across n = 9 timed batches per variant (10,000 calls/batch) after one untimed warm-up batch. ↩

  2. Apple M2 Pro (Arm64, 12 CPU cores). Median of n = 5 timed 1,000-step runs per implementation after one untimed 1,000-step warm-up. Model and optimizer reset before each run. Final weights checked against the MicroGPT reference after timing. ↩

JIT Execution of LLVM IR Modules

Following on from the previous blog post on emitting LLVM IR using xDSL, we now describe how to run it. Previously, going from an xDSL module to an executable meant first emitting the LLVM IR and then compiling. Setting up these two additional steps is tedious, depends on large dependencies and slows down iteration cycles. We wanted to be able to call the function from Python directly, without going via .ll files and shell scripting. By mapping xDSL’s LLVM backend to the llvmlite IR module we get to just-in-time compile our xDSL module. This is done by using the MC Just-in-Time compiler which can emit and execute assembly of an llvmlite IR module. xDSL is now able to execute native code, without a separate lowering and compilation step, opening up new doors for JIT development, benchmarking and end-to-end testing.

For example, to just-in-time compile this add.mlir file with jit.py:

builtin.module {
  llvm.func @main() -> i32 {
    %left = llvm.mlir.constant(21 : i32) : i32
    %right = llvm.mlir.constant(21 : i32) : i32
    %result = llvm.add %left, %right : i32
    llvm.return %result : i32
  }
}
# /// script
# requires-python = ">=3.11"
# dependencies = ["xdsl[llvm]"]
# ///
import sys

from xdsl.context import Context
from xdsl.dialects import builtin, llvm
from xdsl.jit.llvm.backend import LLVMJITBackend
from xdsl.parser import Parser

ctx = Context()
ctx.load_dialect(builtin.Builtin)
ctx.load_dialect(llvm.LLVM)

with open(sys.argv[1]) as f:
    module = Parser(ctx, f.read()).parse_module()

backend = LLVMJITBackend(lowering=())
main = backend.jit(module, "main", ctx)

print(main.c_func())
uv run jit.py add.mlir  # 42

This functionality is also provided directly through the CPython AST, in a frontend called “PyJIT”, as shown in the following Python script:

# /// script
# requires-python = ">=3.11"
# dependencies = ["xdsl[llvm]"]
# ///

from typing import Callable

from xdsl.dialects import arith, builtin, func
from xdsl.jit.context import JITContext, register_builtin_type_maps
from xdsl.jit.llvm.backend import LLVMJITBackend

ctx = JITContext(LLVMJITBackend())

ctx.pyast_ctx.register_function(float.__add__, arith.AddfOp)
ctx.pyast_ctx.register_dialect(arith.Arith)
ctx.pyast_ctx.register_dialect(builtin.Builtin)
ctx.pyast_ctx.register_dialect(func.Func)

register_builtin_type_maps(ctx)

@ctx.jit(Callable[[float, float], float])
def plus(a: float, b: float) -> float:
    return a + b

print(f"{plus(2.0, 2.0) = }")  # plus(2.0, 2.0) = 4.0

The backend takes care of selecting the native target, applying LLVM optimizations, compiling the module, deriving the function signature, and keeping the execution engine alive for as long as the compiled function can be called.

Please find a detailed user guide on the documentation page.

Exporting LLVM IR from xDSL

xDSL is a compiler toolkit optimised for accessibility and low iteration time during experimentation and development. Since the beginning, users have been able to design their own abstractions and rewrites on them, but getting an executable required going via mlir-translate, still requiring users to download and install MLIR. We recently bridged this gap, allowing users to emit LLVM directly in xDSL. We leverage llvmlite, a package developed by the Numba team, to convert xDSL modules in the llvm dialect to llvmlite modules. Users of the Python API can do this with the convert_module function, and the llvm IR can be printed via the command line with --target llvm. This functionality allows users to more easily produce LLVM IR files when prototyping, and unlocks JIT functionality which will describe in a future post.

Please find a detailed user guide on the documentation page.

We did a quick comparison of disk usage of xDSL + llvmlite and a full MLIR installation using Homebrew on MacOS ARM64.

# xdsl + llvmlite
uv venv /tmp/lite
uv pip install --python /tmp/lite/bin/python "xdsl[llvm]"
du -sh /tmp/lite                                     # 127M - total venv
du -sh /tmp/lite/lib/python*/site-packages/xdsl      # 5.5M - xdsl
du -sh /tmp/lite/lib/python*/site-packages/llvmlite  # 112M - llvmlite

# mlir-translate
brew install llvm
ls -lh /opt/homebrew/opt/llvm/bin/mlir-translate  # 34K  - binary
du -sh /opt/homebrew/opt/llvm/lib/libMLIR.dylib   # 149M - dependency
du -sh /opt/homebrew/opt/llvm/lib/libLLVM.dylib   # 156M - dependency
du -sh /opt/homebrew/Cellar/llvm                  # 1.7G - full keg

The actual mlir-translate binary is just 34 KB but it’s linked against two very large dylibs at around 305 MB that aren’t split by Homebrew, forcing you to download the entire ~2 GB keg. The optional llvmlite dependency with xDSL on the other hand is around 13x smaller and can be omitted from your build image.

We hope you find this functionality useful. Happy hacking!

xDSL at HiPEAC 2025

Please join us at the xDSL workshop, on Monday the 20th of January.

The talks will feature a general overview of xDSL, some success stories of xDSL being used in HPC and ML workloads, and some experiments leveraging xDSL infrastructure.

We look forward to seeing you there and discussing how xDSL can help you with your projects!

xDSL at ISC 2023

ISC 2023 runs between Sunday the 21st and Thursday the 25th of May, and sees the world of HPC descend on Hamburg, Germany, to discuss the latest advances in the field and share latest research. It is a busy week with many different activities going on, and the wider ExCALIBUR programme has published a blog article highlighting all the events that are going on which are associated with the wider ExCALIBUR programme.

xDSL is involved in three activities at ISC. Firstly, we have a project poster which will be displayed from Monday at 3pm until the Wednesday and highlights the major objectives and achivements to date of xDSL. The purpose is to both share with the HPC community what we are doing, and also encourage new groups to join us and leverage xDSL for their own work.

We are also involved in the Plasma-PEPSC – Pushing Flagship Plasma Simulation Codes to Tackle Exascale-Enabled Grand Challenges via Performance Optimisation and Codesign Birds of a Feather (BoF) session, which is running Tuesday 23rd of May between 9am and 10am in Hall E and aims to discuss the challenges associated with running plasma physics simulation codes on exascale supercomputers. Our input is around domain specific languages and how these can help scientists to abstractly describe their problem at the mathematical level but still target a rich variety of hardware.

Our activities conclude with the Second Combined Workshop on Interactive and Urgent Supercomputing which xDSL is a co-organiser of and will see the challenges that our community faces in enabling interactive and urgent workloads on supercomputers being focussed upon between 9am and 1pm in Hall Y6 on Thursday 25th of May.

It promises to be a busy week! If you wish to find out more about xDSL then pop by the EPCC booth (G715)

xDSL at Durham HPC Days

Between Tuesday 16th and Friday 19th of May Durham HPC Days was held in the Department of Computer Science at Durham University. A focus session was held on ExCALIBUR and specifically the novel hardware that has been made availble as part of the ExCALIBUR H&ES programme. However, novel hardware is of little use if scientific software developers are unable to programme it, and therefore xDSL gave a talk on our efforts to improve the field of Domain Specific Languages by developing a common ecosystem.

We described how MLIR and LLVM are ideal to solving the problems around siloed DSL ecosystems, before highlighting how xDSL enables DSL developers to construct a thin abstraction layer atop our Python based ecosystem. Some of our work on the PSyclone and Devito DSLs was then discussed, with the point being that whilst these DSLs are very different, for instance PSyclone is Fortran based whereas Devito is Python based, they can still leverage the same underlying compiler infrastructure and when running on ARCHER2 we observe performance benefits and significant code level reductions compared to their existing bespoke compilers.

The workshop was a fanstastic event, with a series of very interesting talks from a wide ranging audience and it was very useful for us to gain feedback from them around our existing and planned activities.

MLIR hackathon and workshop

Starting Monday 1st of May, we hosted a week long xDSL/MLIR hackathon that culminated in an MLIR workshop on 9th of May in Edinburgh. The idea of the hackathon was to bring together those who are using, an those who are interested in using, xDSL with xDSL developers to further enhance the ecosystem and support new, novel use-cases. There was strong involvement from the CONVOLVE project where a major focus was how to leverge xDSL and MLIR to enable efficient programming of the PULP snitch architecture, culminating in a new snitch and RISC-V dialect being added to xDSL.

We also spent time working on the core HPC dialects of xDSL, with enhancements made especially around the halo and MPI dialects in order to ensure that these provide good performance.

The hackathon culminated on Tuesday the 9th of May with an MLIR workshop organised by xDSL. We had a wide variety of speakers, from those involved in the xDSL project developing dialects and DSLs atop the technology, to those who are heavily leveraging MLIR and interested in the productivity enhancements provided by xDSL. The workshop culminated in round table discussions, where a series of topics were discussed in 30 minute sessions and the 40 or-so workshop participants selected the topic most relavent to them. These ranged from new vectorisation standards, to improved C frontends.

Overall the week was very tiring but a great success, special mentio should be given to Arjun Pitchanathan and Anton Lydike who undertook much of the organisation.

ETH Zurich presentation

This week saw xDSL’s Michel Weber give a presentation at the ETH Zurich computer science research lab seminar about the xDSL project. Michel was talking about how, in the past year or so, xDSL has grown into a fully fledged open source compiler infrastructure library that enables programmers to build compilers in a high productivity manner.

xDSL has been especially useful in Michel’s work as he is focussed around enriching database abstractions using compilation. With xDSL able to handle much of the overhead of writing DSLs, this significantly lowers the barrier to entry in fast prototyping for these architectures.

Michel has also been a core contributor to the central xDSL framework, and so was uniquely placed to give researchers at ETH Zurich an insight into what we believe xDSL can contribute and the current challenges. The slides are available to view here.

New year, new hackathon

Last week 2023 got off to a strong, but windy, start with an all week xDSL hackathon held in Edinburgh. With in-person participants from ETH Zurich and Imperial, and online attendees from as far away as Mumbai in India, it was a great opportunity to prioritise the list of tasks we wanted to get sorted and make that happen.

One of the exciting aspects about these hackathon (apart from all the tasty treats throughout the day!) is how, from day to day or even hour to hour, different groups form, work on something, and then break apart once the task has been completed for the cycle to restart all over again! An area of high priority during the session was the xDSL parsing functionality, which had been developed early on during the project and then been updated but without much overarching design. This was completely rewritten, and some enhancements to how people use IRDL were also developed which will find their way into the next release.

We also made a strong start on bringing over the GPU dialect and cleaning this up (watch this space, it will be available soon!) and the most obvious change has been the website, where a revamp of the main website has been undertaken. This is especially nice as it enabled us to bring in some of the Jupyter notebooks that we have been developing for interested users to experiment with online. We also discovered that Anton, who joined the project late last year, is a highly skilled photographer - he was busy taking photos of everyone (and the rather windswept group photo!) for the website’s new team page.

xDSL at the ExCALIBUR workshop

This week saw the two day ExCALIBUR workshop held at the Met Office where representatives from across the programme met and discussed project-level updates as well as opportunities for collaboration and interaction during the research. There were some very interesting projects presented, and clearly the programme is doing a fantastic job pushing UK science towards exascale and beyond.

As part of this workshop xDSL PI, Tobias Grosser, gave an update about the xDSL project itself and, considering that xDSL has been running for almost a year, this was also an ideal opportunity to take stock of where we are as a project, to reflect on early successes, and refine the strategy going forwards into the next two years. Tobias described the underlying xDSL framework that has been developed in the past 12 months, before highlighting work that has been undertaken to build on this for both the existing PSyclone and Devito DSLs.

The compilers of both these existing DSLs have been enhanced to run on-top of the xDSL stack, with bespoke dialects and transformations provided which are expressed via the IRDL MLIR-DSL. Exploitation of distributed memory parallelism and GPUs is also possible with xDSL, for instance the PSyclone xDSL work already having been demonstrated to run on 32768 cores of ARCHER2 and V100 GPUs. Moving forwards, the integration with xDSL provides numerous opportunities, including the ability to leverage the LLVM ecosystem more widely and easily build upon work being done elsewhere by the community.