What Is an ML Compiler? How Model Compilation Enables Cross-Platform Inference

AI compilers lower a framework graph through IR, fusion and kernel selection per target, so one model's latency and accuracy differ by runtime.

What Is an ML Compiler? How Model Compilation Enables Cross-Platform Inference
Written by TechnoLynx Published on 11 Jul 2026

AI compilers (XLA, Apache TVM, TensorRT, ONNX Runtime’s execution providers and the MLIR-based stacks) take the computation graph a framework emits and turn it into hardware-specific kernel invocations. The graph becomes an intermediate representation (IR), graph passes fold constants and fuse operators, and a backend then decides, for each operation, whether to call a vendor library or generate code, which memory layout to use and which kernel configuration to run. Because the backend makes those decisions for a particular target, “compiled” always means compiled for something, and latency, accuracy and energy per inference can differ from one runtime or target to the next. Understanding the stages lets you anticipate those shifts before shipping. Treating the compiler as a black box leaves them to be found on the device.

Where an ML Compiler Sits Between the Framework Graph and the Hardware

An ML compiler takes a model described in a deep learning framework as input and produces optimised code for a specific piece of hardware as output. A traditional compiler does the same kind of job for source code. The difference is what each one can see. A programming-language compiler reasons about loops, functions and memory accesses. An ML compiler starts from a dataflow graph of tensor operations, so it can make whole-graph decisions (merge a batch normalisation into the convolution before it, or run several element-wise operators over the same buffer in one pass) that a general-purpose compiler such as LLVM cannot make on its own. XLA, TVM and Glow hand the final step to a conventional backend: XLA’s CPU and GPU backends, TVM’s x86 and ARM paths and Glow’s CPU backend emit LLVM IR and let LLVM produce native code. It is more accurate to think of an ML compiler as a domain-specific layer sitting on top of a traditional compiler than as a replacement for one.

The Glow paper (2018) gives a clear reason the layer exists. Frameworks support hundreds of operators across many backends, and implementing every operator once per target does not scale. Glow instead lowers high-level nodes into a small set of linear algebra primitives. A fully connected layer becomes a matrix multiplication followed by a broadcast add, so a new backend only has to implement the primitives.

The Stages from Framework Graph to Generated Kernels

The names differ between compilers. The sequence is broadly the same, and XLA’s documented architecture shows it cleanly:

  1. Capture the framework graph. XLA receives the model from PyTorch, TensorFlow or JAX as StableHLO, a versioned set of high-level operations that acts as a portability layer. torch.compile traces Python into an FX graph through TorchDynamo.
  2. Raise it into a high-level IR. XLA works on HLO, a dataflow graph of tensor operations. TVM uses Relax functions for graph structure, and Glow uses a strongly typed high-level graph.
  3. Run target-independent passes. These include common subexpression elimination, generic operation fusion and buffer analysis for runtime memory.
  4. Run target-specific passes. Here the GPU backend fuses in ways that suit the GPU programming model, partitions work into streams and pattern-matches operations onto optimised library calls.
  5. Lower to a low-level IR and generate code. TVM moves from Relax to TensorIR functions with explicit loop nests, threading and vector instructions, then generates LLVM IR, CUDA C or OpenCL. Glow lowers to an instruction-level IR for scheduling and static memory allocation.

The target shapes passes before the last step too. In TVM, a target’s vector length changes vectorisation behaviour in passes that run before code generation, which means divergence between targets can start early in the pipeline.

How Does an ML Compiler Fuse Kernels, Fold Constants and Pick Hardware Backends, and Why Does That Make Inference Faster on a GPU or Other Accelerator?

Fusion reduces memory transfer and kernel launch overhead. Constant folding removes arithmetic whose answer is already known. Backend selection chooses, per operation, between fast vendor libraries and generated code.

On the GPU side, TechnoLynx’s GPU performance engineering practice covers this kind of compiler, kernel and profiling work.

Fusion, and the Places Where It Stops

Fusing several graph nodes into one kernel eliminates intermediate tensors and the HBM round trips they require. Optimizing AI Inference Across the Deployment Stack (arXiv, 2026) calls operator fusion the single most impactful compiler optimisation for inference. NVIDIA’s TensorRT documentation lists three effects of a fused kernel: no launch overhead for each absorbed layer, no intermediate tensors materialised in DRAM, and access to specialised implementations such as fused Conv+Bias+Activation. A convolution followed by ReLU is the textbook case, because the convolution kernel can apply ReLU to its output without a second kernel call.

Fusion has limits, and automatic fusion is far from a solved problem. XLA keeps a list of “expensive” operations it will not fuse (convolution, sort, all-reduce), checks whether a fused kernel would be too large, and stays within GPU limits on threads per block and shared memory per block. Custom calls and cuDNN or cuBLAS primitives stop a fused region from growing past them. XLA:GPU states the trade directly: vendor libraries have verified fast performance but often rule out complex fusion. Fusion also only pays off where memory traffic is the bottleneck. On a compute-bound kernel, cutting memory traffic does nothing. The useful first check before blaming the compiler for a slow model is which side of the roofline the hot kernels sit on. For a worked application, see how ML compilers optimise face recognition inference, and for what this means financially, see how machine learning compilers cut cost per request.

Constant Folding

Constant folding finds subgraphs where every input is known at compile time, evaluates them once and replaces them with the result. Constant propagation then passes the new constants downstream, which can make further nodes foldable. At inference time, batch normalisation statistics are frozen, so the whole layer collapses into a single scale and a single bias. Shape arithmetic folds as well: with a fixed 224×224 input, the flattened size is known in advance and the memory allocator can size buffers before the model runs.

Folding has two caveats. Folding something like a tile or repeat can bake a very large tensor into the binary. More subtly, the machine doing the compiling may round differently from the target accelerator, so a value folded on an x86 host can differ bit for bit from the same value computed on an NPU or GPU.

Backend and Kernel Selection

Once the graph is fused, each operation still needs a concrete implementation, and the search space is enormous. A single GPU matrix multiplication admits thousands of valid tile configurations. XLA:GPU decides per HLO instruction between linked libraries and generated PTX, and it sends fusions that include matmul or softmax through Triton. TensorRT times its eligible tactics at build time. NVIDIA notes that the winning tactic is not guaranteed to be the global fastest, and that engines built from the same network can differ when tactics have similar latencies. A configuration tuned for an A100 may perform poorly on an H100, and cross-hardware transfer remains an open problem.

What Are the Main Open-Source AI Compilers, and How Do They Differ in the Targets They Compile To?

The table compares where each compiler enters the stack and which targets it emits code for.

Compiler Input Emits code for Compilation mode Notes
Apache TVM Models from many frameworks, held as an IRModule (Relax + TensorIR) x86 and ARM via LLVM; CUDA C; OpenCL AOT and JIT Aims at “universal deployment”; schedules are essential for valid GPU code
XLA (OpenXLA) StableHLO from PyTorch, TensorFlow, JAX CPU and GPU via LLVM; TPUs AOT and JIT GPU kernels via LLVM and Triton emitters
TensorRT (NVIDIA) ONNX or network definition NVIDIA GPUs Offline, static engine for fixed shape and precision Layer precision chosen from FP32, FP16, BF16, FP8, INT8
IREE , LLVM CPU, VMVX interpreter, Vulkan SPIR-V, ROCm/HIP, CUDA, Metal , Distinct backends per hardware API
torch.compile PyTorch code traced to FX graphs Kernels generated by TorchInductor JIT with guards Unsupported code causes a graph break rather than a crash
Glow Neural network dataflow graph CPU via LLVM (x86, ARM64) AOT or JIT Two-phase IR with node lowering

MLIR itself is not a compiler for a single target. It is reusable infrastructure meant to lower the cost of building domain-specific compilers and connect existing ones across abstraction levels and hardware. MLIR-AIE is one such domain-specific compiler, compiling for AMD’s AI Engine dataflow array. The AOT versus JIT column reflects a trade-off. AOT spreads compilation cost over many runs but cannot adapt to variable input shapes, while JIT specialises on the fly at the cost of first-request latency spikes and extra GPU memory.

Why Does the Same Model Run at Different Speeds and Accuracies on Different Targets?

The same model behaves differently because runtimes differ in graph fusion, precision handling and kernel generation, and those differences show up in the numbers. Optimizing AI Inference Across the Deployment Stack reports that ResNet-152 on an NVIDIA Jetson AGX Orin ran in 2.28 ms under TensorRT and 285.5 ms under ONNX Runtime, a 125× latency spread on identical hardware. The authors do not read this as a good framework against a bad one. They read it as aggressive graph fusion with hardware-specific kernels against an ONNX graph executed with minimal optimisation on that particular hardware and software version. The spread depends on the model.

Accuracy varied across runtimes as well. ResNet-152 reached 76.6% top-1 under TensorRT and 72.0% under ONNX Runtime and JAX, a gap the authors attribute to precision handling, graph transformation and numerical accumulation order, not to the architecture. Energy can reverse the ranking: for Swin-T, TVM used 0.085 J per inference against TensorRT’s 0.108 J despite higher latency, because it drew less power. Which runtime is “fastest” therefore depends on whether your constraint is latency or energy.

The same mechanisms help explain why one checkpoint behaves differently in an iOS build and an Android build. Fusion can change accumulation order and amplify or dampen quantisation error. Constants folded on the build host can differ from on-device values. Tactic or kernel choice can change between builds. None of these is a bug to be fixed once. The validation budget therefore has to cover each target separately.

How Do ONNX Runtime and CoreML Differ in Operator Support and Kernel Fusion?

ONNX Runtime does not assume one execution provider runs the whole model. It converts the ONNX graph to an in-memory representation, runs provider-independent optimisations and then partitions the graph across the available execution providers (EPs). Each EP takes the maximal subgraphs it can handle, in priority order, and the default CPU provider picks up everything else. That last step is operator fallback: an operator the specialised provider cannot run executes on the default provider, which ensures the model still runs. Each claimed partition becomes a single fused operator through the provider’s Compile() method, and providers have to convert tensors to and from the standard representation at their subgraph boundaries.

The CoreML EP is one of those providers. It compiles the subgraph it captures into a CoreML-format model, which can take minutes for a complicated model unless a cache path is provided. Which CoreML model format it can create depends on the OS version. MLProgram requires Core ML 5 (iOS 15+ or macOS 12+), and NeuralNetwork requires Core ML 3 (iOS 13+ or macOS 10.15+). Compute units can be limited to CPU, CPU plus Neural Engine, CPU plus GPU, or all. The practical way to learn what CoreML did with a model is to profile it (next section). The compiler flags that shape ONNX and CoreML builds are covered separately, as is converting models with coremltools.

Format conversion is another source of divergence, separate from compilation. An Empirical Study of Challenges in Converting Deep Learning Models (2022) found minimal prediction error for ONNX but much larger and framework-dependent error for CoreML, and found ONNX models ran faster. CoreML versions of ResNet-18 and VGG-16 showed high misclassification rates compared with ONNX, while most converted models showed none. The authors suggest structural changes during conversion or numerical defects in coremltools as possible causes. Comparing the converted model’s outputs with the original’s on the build machine shows whether drift starts at conversion, before the runtime is blamed. For a full cross-platform case, see the write-up on real-time TTS inference across ONNX and CoreML.

How Does Compilation Work Alongside Quantisation and Mixed Precision?

Quantisation is a model-level choice of number format. Whether it pays depends on the compiler dispatching to native low-precision kernels. On accelerators with dedicated INT8 or INT4 tensor cores, quantisation can deliver 2–4× higher throughput, but on hardware without those units the runtime silently upcasts to FP16 or FP32 and the gain shrinks to whatever the smaller memory footprint saves, according to Optimizing AI Inference Across the Deployment Stack. The same paper warns that a 3× speedup measured in isolation can disappear in production when the compiler version, batch size or hardware support differs.

Compilers also need to understand quantised graphs. The QNN authors (2020) note that many deep learning compilers were designed mainly for FP32 and could not optimise pre-quantised INT8 models, so they added a quantisation dialect to TVM’s IR. With it, they measured speedups over optimised FP32 of 2.35× on Intel Xeon Cascade Lake, 2.15× on an NVIDIA T4, and 1.35× and 1.40× on Raspberry Pi 3 and Pi 4. The gain varied with the target even with the same compiler.

Mixed precision works the same way at layer level. TensorRT picks each layer’s precision for performance by default, and trtexec’s --layerPrecisions lets you pin specific layers, for example everything at FP16 except one layer at FP32. One trap is easy to miss: in INT8 mode without a calibration cache, trtexec sets random dynamic ranges, so the accuracy it reports is not meaningful. On the ONNX side, explicit Q/DQ quantisation and low-precision types depend on specific opset levels, so the export opset matters for a quantised graph.

How Does Compilation Relate to Distillation and Quantisation as Inference Optimisation Strategies?

Distillation, pruning and quantisation are model-level techniques, while fusion, layout and kernel autotuning are compiler-level ones. Distillation changes the architecture and therefore the graph, and architecture changes invalidate autotuned tile sizes and fused kernel configurations, so the model has to be re-profiled. That sets the order: fix the architecture (distilled or not), choose the precision against the target’s native units, then compile and validate per target, because compiling first and changing the model afterwards throws the tuning away. Choosing between the first two is its own decision, covered in distillation versus quantisation for multi-platform edge targets.

How Do I Inspect What the Compiler Produced Before Deploying?

TensorRT, XLA, torch.compile and ONNX Runtime’s CoreML EP can each show what they fused or where operators ran. This checklist maps the question to the tool:

What you need to know Toolchain How to see it
Which hardware each operator runs on ONNX Runtime CoreML EP ProfileComputePlan logs per-operator dispatch and estimated time
Which layers TensorRT fused TensorRT builder Fusion messages at kINFO log level; fused layers are named after both originals
What each engine layer corresponds to trtexec Build with --profilingVerbosity=detailed, add --dumpLayerInfo
Which tensors stayed unfused trtexec --markUnfusedTensorsAsDebugTensors marks unfused tensors as debug tensors
Why the ONNX parser rejects the model TensorRT + Polygraphy Run constant folding first; simplify unsupported operators with ONNX-GraphSurgeon
What XLA did at each pass XLA HLO dumps at pipeline start and end, or after passes matching --xla_dump_hlo_pass_re
Whether a bug follows the backend XLA Replay dumped HLO on a chosen backend with fake data or input snapshots
What Dynamo traced, why it recompiled and what Inductor fused torch.compile TORCH_LOGS with graph_code, recompiles, fusion, output_code

Two habits make these outputs predictive rather than forensic. First, read the partition and fusion report for each target from the same export before anyone benchmarks, because a fallback visible in the plan is cheaper to fix than one found in a latency regression. Second, record the toolchain version with the artefact: TensorRT’s timing cache, for example, is tied to the device, CUDA and TensorRT versions and builder settings. Locking the GPU clock during the build also makes tactic selection more deterministic. Keeping compiled artefacts tied to their compiler and target is the subject of model versioning for cross-platform GPU deployments, and the build switches themselves are covered under compilation flags for multi-platform edge inference.

The inspection tools tell you what the compiler did. They cannot tell you how a new chip will behave from measurements on an old one: the deployment-stack survey describes predicting H100 latency from A100 profiles as unsolved. That gap is why the per-target profile stays in the release process even when the export path is shared.

FAQ

Does XLA Use MLIR?

Yes. XLA takes its input as StableHLO, which it converts into an internal HLO dialect, and XLA:GPU lowers advanced fusions to TritonIR, an MLIR dialect, before Triton generates PTX.