· · Engineering · 11 min read

From a UchenML model to native code through MLIR

A new, experimental way to compile UchenML models to native code with MLIR.

Overview

UchenML has one backend: hand-written SIMD kernels on Google Highway, specialized with C++ templates. It meets my original goal, cross-platform ML on CPUs of different architectures, but has a few shortcomings:

  • Limited platform reach. Without float SIMD (the Pico 2’s Cortex-M33), Highway’s scalar fallback emulates vectors and is hard to tune. There is no SME support for the M4+, and GPUs or other accelerators would take significant extra work.
  • Hard to extend. Every fused kernel is hand-written. ReLU is Clamp<0, FLT_MAX> and pays a useless Min, because dropping it means another variant.
  • Combinatorial explosion. Linear already compiles 8 times (clamp × vector tail × fp32/fp16); fusing tanh would multiply it and both convolutions again, bloating the binary.

MLIR flips this: describe each layer once and let a compiler generate the exact kernel for any target LLVM supports. It also opens a path to running models on GPUs and accelerators, at least in theory. So I am building a new, inference-only backend on it. This article covers my current approach: how the MLIR is generated, built and called.

The model

two_head is an early variant of my Dots model, kept in uchen-core as a benchmark: four 3×3 convolutions over a 64×64 board, two dense layers, then a policy head and a value head; 17,372,545 parameters. In the DSL, without the fp16 storage tags the Highway benchmarks add:

template <size_t S>
inline constexpr uchen::Model kTwoHeadTrunk =
    uchen::layers::ConvolutionModel<4, S, S> |
    uchen::layers::Conv2d<16, 3, 3, 1, 1> | uchen::layers::Relu |
    uchen::layers::Conv2d<32, 3, 3, 1, 1> | uchen::layers::Relu |
    uchen::layers::Conv2d<32, 3, 3, 1, 1> | uchen::layers::Relu |
    uchen::layers::Conv2d<32, 3, 3, 1, 1> | uchen::layers::Relu |
    uchen::layers::Reshape<uchen::Vector<32 * S * S>> |
    uchen::layers::Linear<128> | uchen::layers::Relu |
    uchen::layers::Linear<128> | uchen::layers::Relu;

template <size_t S>
inline constexpr auto kTwoHeadPolicyHead =
    uchen::layers::Linear<S * S> | uchen::layers::Logits;

inline constexpr auto kTwoHeadValueHead =
    uchen::layers::Linear<64> | uchen::layers::Relu | uchen::layers::Linear<1> |
    uchen::layers::Tanh;

template <size_t S>
inline constexpr uchen::Model kTwoHeadModel =
    kTwoHeadTrunk<S> | uchen::layers::Fork<2> |
    uchen::layers::Parallel(kTwoHeadPolicyHead<S>, kTwoHeadValueHead);

inline constexpr const auto& kTwoHead = kTwoHeadModel<64>;

As with the rest of Uchen, the goal is an extensible framework: layers that core Uchen does not support should be addable from outside it. I also plan an escape hatch, not implemented yet: a custom layer can supply a plain C++ implementation instead, so adding a layer does not require MLIR.

Generating MLIR

MLIR is the LLVM project’s framework for building compiler IRs. Every ML framework used to build its own compiler stack from scratch; MLIR makes that stack shared and reusable. A module mixes ops from dialects at different levels, from whole-tensor tosa.conv2d down to llvm, which maps one-to-one onto LLVM IR. A pipeline of passes lowers it level by level until only llvm is left, and Clang compiles that into an object file.

The UchenML generator emits the top level: TOSA, plus func, tensor and arith as glue. Uchen provides its own passes and transforms for speed and binary size; the user picks which go into the pipeline (details in a follow-up article). The result is an object file and a C header that link like any other library.

The biggest downside is LLVM. UchenML has so far worked with any C++20 compiler and standard library; the MLIR backend needs LLVM to build the model library, though the result links into a project built with any compiler.

Going from the model to MLIR module

First, the user sets up a generator: a small C++ executable that bridges their model and UchenML and prints the model’s MLIR. Its core, subject to change: forward_pass() turns the constexpr model into a runtime list of layers, MlirModuleBuilder::MLIRFromModel builds the module from it, and the generator prints the module to stdout:

// kTwoHead is the constexpr model above. forward_pass() turns its compile-time
// layer list into a runtime one: each layer's type, shapes and parameter count.
const auto tree = uchen::benchmarks::kTwoHead.forward_pass();

uchen::mlir_backend::MlirModuleBuilder builder{
    uchen::mlir_backend::AllEmitters};
if (absl::Status status = builder.MLIRFromModel(tree.pass(), "two_head");
    !status.ok()) {
  return status;
}
// Bazel captures stdout as two_head.mlir.
builder.mlir_module()->print(llvm::outs(),
                             mlir::OpPrintingFlags().printNameLocAsPrefix());

Each layer becomes a function <kind>_<index> (conv2d_0 in the snippet below) taking the previous output and the layer’s parameters as a flat 1-D tensor; the layer’s emitter fills in the body. Layer functions have internal linkage, so several models can link into one binary. A public function named after the model fetches each layer’s parameters and calls the layers in order, and the builder runs the verifier. For two_head, cut to the first layer:

func.func @two_head(%input: tensor<1x64x64x4xf32> {bufferization.writable = false},
                    %model_parameters: !llvm.ptr)
    -> (tensor<1x4096xf32>, tensor<1x1xf32>) attributes {llvm.emit_c_interface} {
  %conv2d_0_index = arith.constant 0 : i64
  %conv2d_0_count = arith.constant 1024 : i64
  %conv2d_0_parameters_view = call @uchen_mlir_layer_parameters(
      %model_parameters, %conv2d_0_index, %conv2d_0_count)
      : (!llvm.ptr, i64, i64) -> tensor<?xf32>
  %conv2d_0_parameters = tensor.cast %conv2d_0_parameters_view
      : tensor<?xf32> to tensor<1024xf32>
  %conv2d_0 = call @conv2d_0(%input, %conv2d_0_parameters)
      : (tensor<1x64x64x4xf32>, tensor<1024xf32>) -> tensor<1x64x64x16xf32>
  // ... conv2d_1 through fork_6 the same way
  return %fork_6#0, %fork_6#1 : tensor<1x4096xf32>, tensor<1x1xf32>
}

uchen_mlir_layer_parameters is a C++ hook returning a view into Uchen’s own parameter store, in the same layout Highway backend uses (bias first, then column-major weights for Linear, Winograd U for the 3×3 convs). bufferization.writable = false keeps bufferization from writing into the caller’s input.

Emitters

An emitter maps one Uchen layer type to MLIR ops. Emitters register in a LayerEmitters table keyed by type id; a layer without one fails at generation time. AllEmitters registers the built-in ones: convolution, element-wise, linear, multi-head, pooling, reshape and softmax.

An emitter can use any MLIR dialect. The built-in ones write TOSA, MLIR’s dialect of whole-tensor operators (tosa.matmul, tosa.conv2d, tosa.add, …). They currently build it through the MLIR C++ API; emitting MLIR text directly may come later. The Linear emitter:

// Flat parameters: `[O]` bias, then W stored `[I][O]` (column-major W).
absl::StatusOr<mlir::Value> EmitLinear(const ModelLinearLayer& layer,
                                       EmitContext& context, mlir::Value input,
                                       size_t offset) {
  const auto inputs = static_cast<int64_t>(layer.inputs());
  const auto outputs = static_cast<int64_t>(layer.outputs());
  absl::StatusOr<mlir::Value> row =
      context.Coerce(input, {1, 1, inputs}, "row");
  if (!row.ok()) {
    return row.status();
  }
  mlir::ImplicitLocOpBuilder& builder = context.builder();
  const mlir::Type element = context.element();
  const mlir::Value weights = context.Parameters(
      "weights", offset + layer.outputs(), {1, inputs, outputs});
  const mlir::Value bias = context.Parameters("bias", offset, {1, outputs});
  auto product = context.Named(
      mlir::tosa::MatMulOp::create(
          builder, mlir::RankedTensorType::get({1, 1, outputs}, element), *row,
          weights),
      "product");
  context.NameDefiningOp(product.getAZp(), "row_zp");
  context.NameDefiningOp(product.getBZp(), "weights_zp");
  mlir::Value output = context.Named(
      mlir::tosa::AddOp::create(
          builder, mlir::RankedTensorType::get({1, outputs}, element),
          context.Reshape(product, {1, outputs}, "product_2d"), bias),
      "linear");
  if (const auto& clamp = layer.clamp(); clamp.has_value()) {
    output = context.Clamp(output, clamp->min, clamp->max);
  }
  return output;
}

EmitContext holds the builder, element type and parameter argument; its helpers (Parameters, Reshape, Slice, Pad, Add) each emit one or two TOSA ops. Named attaches a name location, and the module prints with printNameLocAsPrefix, so results read %weights instead of %5, at no run-time cost.

Clamp special-cases ReLU: with an upper bound of FLT_MAX it emits just tosa.maximum(x, 0). A bounded clamp, such as ReLU6, stays tosa.clamp.

Convolutions take one of two paths. The general one emits tosa.conv2d plus a tosa.transpose, since Uchen stores im2col weights as HWIO and TOSA wants OHWI; lowering with prefer-conv2d-kernel-layout-hwcf=true transposes back, and the two transposes cancel. two_head never takes it (every conv is a Winograd 3×3); the 1×1 heads of the larger teacher model do.

The Winograd path spells out F(2×2, 3×3) in TOSA: pad the input, slice it into 16 taps (pixel (i, j) of every 4×4 tile), combine them with adds and subtracts into V = Bᵀ d B, multiply V by U with one batched tosa.matmul, and apply the output transform Aᵀ M A the same way. The transform matrices hold only 0 and ±1, so the transforms need no multiplies.

The Bazel build

The generated IR never enters the source tree: Bazel generates, lowers and compiles it like any other source, in the configuration of the binary that links it. LLVM runs only at build time; the end product contains none of it.

The targets

A model needs three things in BUILD: a generator, a generated_mlir_model call, and a dependency on the library it produces. Condensed into one package from uchen-mlir’s tools/ and benchmark/:

load("//tools:mlir.bzl", "generated_mlir_model")

# The constexpr model definitions.
cc_library(
    name = "benchmark_models",
    hdrs = ["model.h", "models.h"],
    deps = [
        "@uchen-core//uchen:convolution",
        "@uchen-core//uchen:runtime",
    ],
)

# The generator: prints the model's MLIR and writes its C header.
cc_binary(
    name = "model_mlir",
    srcs = ["model_mlir.cc"],
    deps = [
        ":benchmark_models",
        "//src/uchen/mlir_backend:all_emitters",
        "//src/uchen/mlir_backend:mlir_module_builder",
        "@abseil-cpp//absl/flags:parse",
    ],
)

# Runs the MLIR pipeline; `:two_head` is the cc_library to link.
generated_mlir_model(
    name = "two_head",
    generator = ":model_mlir",
)

# The end product: the model's object file plus two small runtime libraries.
cc_binary(
    name = "app",
    srcs = ["app.cc"],
    deps = [
        ":two_head",
        # Parameter and allocation hooks the generated code calls back into.
        "//src/uchen/mlir_backend:hooks",
        # memrefCopy, which lowered concatenations call.
        "@llvm-project//mlir:mlir_c_runner_utils",
    ],
)

:app contains no LLVM code. Its only @llvm-project dependency is MLIR’s small C runtime, for memrefCopy. That library does list llvm:Support, but in a static link the linker drops all of it: nm finds no llvm:: symbol in the benchmark binary.

This build graph produces two_head, a library with ready-to-use inference code. MLIR does not ship with the end product: the model is compiled ahead of time to optimized machine code, with no VM or interpreter.

What generated_mlir_model(name = "two_head") expands toThe genrule :two_head_tosa runs the model_mlir generator over the constexpr model and writes two_head.mlir and two_head.h. The mlir_cc_library :two_head_ir lowers two_head.mlir in three actions, MlirOpt with the pipeline and the transform schedule, MlirTranslate and MlirCompile with the target's clang, into an object file. The uchen_cc_library :two_head combines that object with two_head.h for C++ binaries and tests. The mlir_stepper :two_head_lowered opens the same lowering in the browser stepper.:two_head_irmlir_cc_librarylinkstwo_head.llvm.mlirtwo_head.ll (output group llvm_ir)source, pipeline, scheduletwo_head.o → CcInfobenchmark/models.hconstexpr model, uchen-core DSL//tools:model_mlirgenerator, exec config@llvm-projectMLIR + LLVM, built from source:two_head_tosagenrule: runs model_mlirtwo_head.mlirTOSAtwo_head.hC interface headerMlirOptmlir-opt --pass-pipeline=builtin.module(…)MlirTranslatemlir-translate --mlir-to-llvmirMlirCompilethe target's clang -x ir, with the binary's coptstools/mlir.bzl_passes: the pipelinetools/matmul_schedule.mlirtransform schedule//tools:mlir_opt+ uchen-unfuse-vector-fma:two_head_loweredmlir_stepper: opens the stepper:two_headuchen_cc_library: header + object//benchmark:modelscc_binary / cc_testBazel targetactionsource or output fileexec tool

The pipeline is a list in tools/mlir.bzl and the transform schedule a file, tools/matmul_schedule.mlir, passed to MlirOpt. Changing either reruns the lowering of every model and nothing else.

The toolchain

mlir-opt, mlir-translate and the generator are exec-configuration tools built from @llvm-project; the repository’s own mlir-opt adds one pass, uchen-unfuse-vector-fma. LLVM builds once and stays cached: 7 m 16 s (4,449 actions) from a cold cache on a 16-core M4 Max. After that, a pipeline or schedule change reruns only three lowering actions per model. It is possible that the final implementation will provide precompiled binaries.

The last action compiles the .ll with the target C++ toolchain through cc_common, so it gets the same flags as the rest of the build (-c opt, -march=native, sanitizers).

Only clang compiles LLVM IR, so the rule accepts clang, emscripten’s emcc and the Pico SDK’s clang, and fails at analysis otherwise. That clang must also accept IR from @llvm-project’s LLVM version.

Calling it from C++

The generated header declares the model’s C interface. For two_head:

// Generated by uchen-mlir: the C interface of `two_head`.
struct TwoHeadResults {
  StridedMemRefType<float, 2> slot_0;
  StridedMemRefType<float, 2> slot_1;

  template <typename F>
  void ForEachSlot(F&& f) const {
    f(slot_0);
    f(slot_1);
  }
};

extern "C" void _mlir_ciface_two_head(TwoHeadResults* results,
    StridedMemRefType<float, 4>* input, void* parameters);

StridedMemRefType is MLIR’s memref descriptor from CRunnerUtils.h: base pointer, aligned pointer, offset, sizes, strides. The header comes from the same module, so nobody writes the ABI by hand. One slot per output: policy logits and value. A call, from the benchmark fixtures:

size_t RunMlir(Results& results) {
  mlir_backend::ScopedArena arena(mlir_arena_);
  Generated(&results, &mlir_input_,
            mlir_backend::ParametersHandle(parameters_));
  return arena.used();
}

The generated code allocates intermediate and result buffers through two hook functions instead of malloc. ScopedArena serves them from a caller-provided buffer on the current thread and frees nothing until it goes out of scope, so inference stays off the heap. With static shapes, every run needs the same bytes. Results point into the arena and stay valid until the next run.

Unoptimized, it is slow

Without the transform schedule, the lowering produces plain loops: the emitted LLVM IR has no vector ops. Clang’s autovectorizer recovers the elementwise parts, but the matmuls stay scalar. The results are correct, within 1e-4 relative of Highway, and an order of magnitude slower:

ModelHighwayMLIR, no scheduleSlower
two_head1.85 ms31.9 ms17×
teacher3.44 ms46.4 ms13×

Forward-pass latency on an M4 Max (Apple clang 21, -O2 -march=native; MLIR/LLVM 21.1.8), median of 15 repetitions for MLIR and 240 for Highway.

What’s next

Plain loops are only the starting point. The next articles will focus on reducing the gap:

  • The transform schedule. Uchen’s transform schedule tiles and vectorizes the matmuls. It already brings two_head from 31.9 to 6.5 ms, still 3.5× behind Highway; the follow-up walks through it step by step.
  • Static memory. The generated code still allocates every intermediate buffer at run time, 194 per two_head pass, all through the arena. With static shapes, those could be planned at build time.
  • SME. MLIR’s arm_sme dialect is a route to the M4’s matrix units, which Highway cannot reach.

The MLIR code lives in a separate project. Highway remains UchenML’s backend until the MLIR one catches up, and wherever LLVM is unavailable. I will keep writing about MLIR as it matures.

My notes from building UchenML

C++ machine learning compiled into real products — plus the C++ and performance rabbit holes I fall into around it. Technical, irregular by design.

Double opt-in — I'll send a confirmation email first. Unsubscribe in one click.