Creating a New Tokamax Op: A Step-by-Step Guide

Open In Colab

When you write a custom accelerator kernel in JAX (for example, using Pallas), turning that raw kernel function into a production-ready operator usually requires a lot of extra plumbing:

  • Validating input shapes, dtypes, and target hardware.
  • Managing kernel hyperparameters (such as block/tile sizes).
  • Choosing sensible default heuristics per input shape.
  • Sweeping over a search space of configurations (autotuning) and caching the fastest config.
  • Accurately benchmarking on-device execution time without Python dispatch overhead.

Tokamax solves this with a single base class: tokamax.Op (defined in tokamax/_src/ops/op.py).

In this guide, we will take the Pallas TPU Matrix Multiplication (matmul) example from the JAX Pallas TPU Quickstart & Matmul Guide and walk through how easy it is to:

  1. Wrap the kernel as a Tokamax Op.
  2. Make its block sizes configurable with default heuristics.
  3. Define an autotuning search space to automatically find the fastest block sizes.
  4. Benchmark and compare configurations using Tokamax's built-in benchmarking tools.
# Install dependencies if they are not already available in the runtime environment.
try:
  import jax
  import jax.numpy as jnp
  import tokamax
except ImportError:
  %pip install -q jax jaxlib tokamax
  import jax
  import jax.numpy as jnp
  import tokamax

Setup and Imports

from typing import ClassVar
import jax
from jax.experimental import pallas as pl
from jax.experimental.pallas import tpu as pltpu
import jax.numpy as jnp
import numpy as np
import pydantic
import tokamax

print(f"JAX backend: {jax.default_backend()}")
print(f"Devices: {jax.devices()}")
JAX backend: tpu
Devices: [TpuDevice(id=0, process_index=0, coords=(0,0,0), core_on_chip=0), TpuDevice(id=1, process_index=0, coords=(0,0,0), core_on_chip=1)]

1. The Starting Point: A Pallas TPU Matmul Kernel

Let's start with the pipelined block matrix multiplication kernel from the JAX Pallas TPU tutorial (linked from the Pallas TPU Quickstart).

To multiply an (m, k) matrix x with a (k, n) matrix y, the kernel divides the work into blocks of size (bm, bk) and (bk, bn), pipelining memory transfers between HBM and VMEM while accumulating each (bm, bn) output block over a 3D grid (m // bm, n // bn, k // bk):

def matmul_kernel(x_ref, y_ref, z_ref):
  # Zero-initialize the output accumulator on the first reduction step (k == 0).
  @pl.when(pl.program_id(2) == 0)
  def _():
    z_ref[...] = jnp.zeros_like(z_ref)

  # Accumulate the block matrix product in VMEM.
  z_ref[...] += x_ref[...] @ y_ref[...]


def matmul(
    x: jax.Array,
    y: jax.Array,
    *,
    bm: int = 128,
    bk: int = 128,
    bn: int = 128,
) -> jax.Array:
  m, k = x.shape
  _, n = y.shape
  return pl.pallas_call(
      matmul_kernel,
      out_shape=jax.ShapeDtypeStruct((m, n), x.dtype),
      in_specs=[
          pl.BlockSpec((bm, bk), lambda i, j, k: (i, k)),
          pl.BlockSpec((bk, bn), lambda i, j, k: (k, j)),
      ],
      out_specs=pl.BlockSpec((bm, bn), lambda i, j, k: (i, j)),
      grid=(m // bm, n // bn, k // bk),
      compiler_params=pltpu.CompilerParams(
          dimension_semantics=("parallel", "parallel", "arbitrary")
      ),
  )(x, y)

Let's verify that our standalone Pallas matmul function produces the same result as standard JAX matrix multiplication (x @ y):

m, k, n = 4096, 4096, 4096
k1, k2 = jax.random.split(jax.random.key(0), 2)
x = jax.random.normal(k1, (m, k), dtype=jnp.float32)
y = jax.random.normal(k2, (k, n), dtype=jnp.float32)

np.testing.assert_allclose(x @ y, matmul(x, y), atol=1e-3, rtol=1e-3)
print("Standalone Pallas matmul matches x @ y!")
Standalone Pallas matmul matches x @ y!

2. Wrapping the Kernel as a Basic Tokamax Op

To turn matmul into a Tokamax operator, we subclass tokamax.Op (defined in tokamax/_src/ops/op.py).

At a minimum, an Op only needs to implement _fwd, which executes the forward pass. Let's look at the key methods you can define on an Op:

  • _fwd(self, x: jax.Array, y: jax.Array, *, return_residuals: bool, config) (required): Runs the computation and returns a 2-tuple (output, residuals). When you don't need custom intermediate residuals for a custom backward pass (vjp), simply return (output, None). > Tip: Always include type annotations (like x: jax.Array, y: jax.Array) on _fwd arguments—Tokamax uses them to automatically serialize input shapes and dtypes into StableHLO metadata for profiling and autotuning.
  • bind(self, x: jax.Array, y: jax.Array, *, return_residuals: bool = False) -> tokamax.BoundArguments (optional): Validates and canonicalizes the caller's arguments before execution, returning super().bind(...).
  • supported_on(self, device: jax.Device) -> bool (optional): Declares which hardware platforms the op supports (for example, device.platform == "tpu").

Here is our first Tokamax Op wrapper:

class SimpleMatmul(tokamax.Op):
  """A minimal Tokamax Op wrapping our Pallas TPU matmul kernel."""

  def bind(
      self,
      x: jax.Array,
      y: jax.Array,
      *,
      return_residuals: bool = False,
  ) -> tokamax.BoundArguments:
    if x.ndim != 2 or y.ndim != 2:
      raise ValueError(f"Inputs must be 2D matrices, got {x.shape} and {y.shape}.")
    if x.shape[1] != y.shape[0]:
      raise ValueError(f"Inner dimensions must match, got {x.shape} and {y.shape}.")
    if x.dtype != y.dtype:
      raise ValueError(f"Input dtypes must match, got {x.dtype} and {y.dtype}.")
    return super().bind(x, y, return_residuals=return_residuals)

  def _fwd(
      self,
      x: jax.Array,
      y: jax.Array,
      *,
      return_residuals: bool = False,
      config,
  ) -> tuple[jax.Array, None]:
    del return_residuals, config
    return matmul(x, y), None

  def supported_on(self, device: jax.Device) -> bool:
    return device.platform == "tpu"

Instances of tokamax.Op are callable just like regular JAX functions:

simple_matmul = SimpleMatmul()

out = simple_matmul(x, y)
np.testing.assert_allclose(out, x @ y, atol=1e-3, rtol=1e-3)
print("SimpleMatmul output shape:", out.shape)
SimpleMatmul output shape: (4096, 4096)

3. Making the Op Configurable (Config & Heuristics)

In our matmul function, the block sizes bm, bk, and bn are crucial performance knobs:

  • Small blocks (such as the naive default 128x128x128) have low arithmetic intensity—the TPU Matrix Multiply Unit (MXU) spends most of its time stalled waiting on HBM-to-VMEM memory transfers.
  • Larger blocks (such as 512x512x512) dramatically increase data reuse in VMEM and hide DMA transfer latency via pipelining. However, if the blocks exceed available VMEM, kernel compilation will fail.

Tokamax makes kernel hyperparameters first-class citizens through Op Configs:

  1. Define a Config class: Create a frozen dataclass (@pydantic.dataclasses.dataclass(frozen=True)) holding the tuning parameters (bm, bk, bn).
  2. Set config_cls: Assign config_cls = MatmulConfig on your Op class and use config.bm, config.bk, config.bn inside _fwd.
  3. Implement _get_heuristics_config(self, ba: tokamax.BoundArguments) -> MatmulConfig: When a user calls op(x, y) without specifying a config (and when no autotuned config is cached), Tokamax automatically invokes _get_heuristics_config with the BoundArguments object ba. We can inspect ba.arguments["x"] and ba.arguments["y"] to choose the largest block sizes that divide (m, k, n) while fitting within a double-buffered TPU VMEM budget.

Note that you only need to provide _get_heuristics_config(). Op.__call__ will automatically invoke it when you call ConfigurableMatmul()(x, y). This way as long as you provide the function it will always be used to compute a config for your kernel.

@pydantic.dataclasses.dataclass(frozen=True)
class MatmulConfig:
  """Block size hyperparameters for our Pallas TPU matmul kernel."""

  bm: int = 128
  bk: int = 128
  bn: int = 128


class ConfigurableMatmul(SimpleMatmul):
  """A Tokamax Matmul Op with configurable block sizes and default heuristics."""

  config_cls: ClassVar[type[MatmulConfig]] = MatmulConfig

  def _get_heuristics_config(self, ba: tokamax.BoundArguments) -> MatmulConfig:
    """Selects large block sizes that divide (m, k, n) and fit in TPU VMEM."""
    x, y = ba.arguments["x"], ba.arguments["y"]
    m, k = x.shape
    _, n = y.shape
    itemsize = jnp.dtype(x.dtype).itemsize

    # Pick the largest power-of-two block sizes from (512, 256, 128) that
    # evenly divide each matrix dimension.
    bm = next((b for b in (512, 256, 128) if m >= b and m % b == 0), 128)
    bk = next((b for b in (512, 256, 128) if k >= b and k % b == 0), 128)
    bn = next((b for b in (512, 256, 128) if n >= b and n % b == 0), 128)

    # Double-buffered pipelining holds 2 copies of x (bm, bk), y (bk, bn),
    # and z (bm, bn) in VMEM. Shrink the largest block until we fit in 8 MiB.
    vmem_limit_bytes = 8 * 1024 * 1024
    while 2 * (bm * bk + bk * bn + bm * bn) * itemsize > vmem_limit_bytes:
      if bk >= bm and bk >= bn and bk > 128:
        bk //= 2
      elif bn >= bm and bn > 128:
        bn //= 2
      elif bm > 128:
        bm //= 2
      else:
        break

    return MatmulConfig(bm=bm, bk=bk, bn=bn)

  # Op.__call__ will call `_fwd` with `config=self._get_heuristics_config(ba)`
  # when no config is specified and there is no autotuned config cached.
  def _fwd(
      self,
      x: jax.Array,
      y: jax.Array,
      *,
      return_residuals: bool = False,
      config: MatmulConfig,
  ) -> tuple[jax.Array, None]:
    del return_residuals
    return matmul(x, y, bm=config.bm, bk=config.bk, bn=config.bn), None

Heuristic Config vs. Default Config: How Big is the Runtime Difference?

Let's compare calling ConfigurableMatmul() (which automatically uses _get_heuristics_config to pick 512x512x512 blocks) against the naive default MatmulConfig(bm=128, bk=128, bn=128):

# 1. Naive default config (bm=128, bk=128, bn=128)
default_cfg_op = ConfigurableMatmul(config=MatmulConfig())
default_bench = default_cfg_op.bind(x, y).benchmark()

# 2. Heuristic config: automatically uses `_get_heuristics_config`
heuristic_op = ConfigurableMatmul()
heuristic_ba = heuristic_op.bind(x, y)
np.testing.assert_allclose(heuristic_op(x, y), x @ y, atol=1e-3, rtol=1e-3)
heuristic_bench = heuristic_ba.benchmark()

default_ms = default_bench.median_evaluation_time_ms
heuristic_ms = heuristic_bench.median_evaluation_time_ms
speedup = default_ms / heuristic_ms

print(f"Default config   {default_cfg_op.config}: {default_ms:.3f} ms")
print(f"Heuristic config {heuristic_ba.heuristics_config}: {heuristic_ms:.3f} ms")
print(f"Speedup from _get_heuristics_config: {speedup:.1f}x faster!")
Default config   MatmulConfig(bm=128, bk=128, bn=128): 17.578 ms
Heuristic config MatmulConfig(bm=512, bk=512, bn=512): 0.605 ms
Speedup from _get_heuristics_config: 29.1x faster!

4. Building an Autotuning Search Space

A good heuristic already gave us an order-of-magnitude speedup over the naive 128x128x128 config! However, the single fastest (bm, bk, bn) combination can still depend on the exact matrix aspect ratios (m, k, n) and TPU generation—for example, asymmetric tiles with a 1024 dimension may outperform square 512x512x512 tiles.

With tokamax.Op, building an autotuning search space requires overriding just one method:

  • _get_autotuning_configs(self, ba: tokamax.BoundArguments) -> set[MatmulConfig]: Inspects the bound arguments in ba.arguments and returns a set of candidate MatmulConfig instances to benchmark. (Tokamax automatically includes ba.heuristics_config in ba.autotuning_configs as well.)
class PallasMatmul(ConfigurableMatmul):
  """A Tokamax Matmul Op with a block-size autotuning search space."""

  def _get_autotuning_configs(self, ba: tokamax.BoundArguments) -> set[MatmulConfig]:
    """Generates candidate (bm, bk, bn) configurations for the input shapes."""
    x, y = ba.arguments["x"], ba.arguments["y"]
    m, k = x.shape
    _, n = y.shape
    itemsize = jnp.dtype(x.dtype).itemsize
    vmem_limit_bytes = 12 * 1024 * 1024

    candidate_blocks = (128, 256, 512, 1024)
    return {
        MatmulConfig(bm=bm, bk=bk, bn=bn)
        for bm in candidate_blocks
        for bk in candidate_blocks
        for bn in candidate_blocks
        if m % bm == 0
        and k % bk == 0
        and n % bn == 0
        and 2 * (bm * bk + bk * bn + bm * bn) * itemsize <= vmem_limit_bytes
    }


matmul_op = PallasMatmul()
ba = matmul_op.bind(x, y)
print(f"Search space contains {len(ba.autotuning_configs)} candidate configs.")
Search space contains 60 candidate configs.

Running the Autotuner

Tokamax gives you two convenient ways to autotune your op:

Option A: Autotune directly via BoundArguments.autotune()

Calling ba.autotune() compiles candidate configs in parallel, benchmarks each one on the device, caches the results in memory for (m, k, n), and returns an AutotuningData dictionary mapping each MatmulConfig to its BenchmarkData:

autotune_data = ba.autotune()

print(f"Fastest config: {autotune_data.fastest_config}\n")
print("Top 5 fastest configs:")
ranked_configs = sorted(
    autotune_data.prune_errors().items(),
    key=lambda item: item[1].median_evaluation_time_ms,
)
for cfg, bench in ranked_configs[:5]:
  print(f"  {cfg} -> {bench.median_evaluation_time_ms:.3f} ms")

print("\nSlowest config:")
slowest_cfg, slowest_bench = ranked_configs[-1]
print(f"  {slowest_cfg} -> {slowest_bench.median_evaluation_time_ms:.3f} ms")
Fastest config: MatmulConfig(bm=1024, bk=256, bn=1024)

Top 5 fastest configs:
  MatmulConfig(bm=1024, bk=256, bn=1024) -> 0.337 ms
  MatmulConfig(bm=512, bk=512, bn=1024) -> 0.386 ms
  MatmulConfig(bm=1024, bk=512, bn=512) -> 0.386 ms
  MatmulConfig(bm=512, bk=1024, bn=512) -> 0.424 ms
  MatmulConfig(bm=256, bk=1024, bn=1024) -> 0.466 ms

Slowest config:
  MatmulConfig(bm=128, bk=128, bn=128) -> 17.582 ms

Because ba.autotune() caches the result by default (cache_results=True), subsequent calls to matmul_op(x, y) with this shape will automatically pick autotune_data.fastest_config!

# Resolves to the cached fastest config automatically:
print("Resolved default config after autotuning:", ba.default_config)

Option B: Function-level autotuning with tokamax.autotune()

What if your custom Op is called inside a larger JAX function or model? Because tokamax.Op embeds its call metadata into the lowered StableHLO graph, tokamax.autotune(fn, *args) automatically discovers every Tokamax Op inside fn, tunes each unique shape, and returns an AutotuningResult context manager:

def f(x: jax.Array, y: jax.Array) -> jax.Array:
  return jax.nn.relu(matmul_op(x, y))


# Autotune all Tokamax ops inside `f`
autotune_result = tokamax.autotune(f, x, y, ignore_cache=True)

# Use `autotune_result` as a context manager to apply the best config(s)
with autotune_result:
  out_tuned = f(x, y)

# You can also serialize and reload `AutotuningResult` as JSON for later reuse:
serialized_json = autotune_result.dumps()
reloaded_result = tokamax.AutotuningResult.loads(serialized_json)
print("Reloaded AutotuningResult device:", reloaded_result.device_kind)
Autotuning: 100%|██████████| 1/1 [00:11<00:00, 11.80s/ op calls, Total microbenchmarks=60]
Reloaded AutotuningResult device: TPU7x

5. Benchmarking Your Op

Measuring accelerator kernel performance with Python's timeit can be inaccurate because host dispatch overhead often masks true kernel execution time. Tokamax includes built-in benchmarking tools that use hardware-level profiling (hermetic_xprof on TPU by default) to measure pure on-device execution time, along with compilation time and peak memory usage.

Quick Benchmarking via BoundArguments.benchmark()

Any bound op call op.bind(*args) can be benchmarked directly with .benchmark(), which returns a tokamax.BenchmarkData object:

bench_data = matmul_op.bind(x, y).benchmark()

print(f"Median evaluation time : {bench_data.median_evaluation_time_ms:.3f} ms")
print(f"All evaluation times   : {[round(t, 3) for t in bench_data.evaluation_times_ms]} ms")
print(f"Lowering time          : {bench_data.lower_time_ms:.1f} ms")
print(f"Compile time           : {bench_data.compile_time_ms:.1f} ms")
print(f"Peak memory            : {bench_data.peak_memory_mb:.1f} MB")
Median evaluation time : 0.339 ms
All evaluation times   : [0.339, 0.337, 0.339, 0.337, 0.339] ms
Lowering time          : 8.6 ms
Compile time           : 199.3 ms
Peak memory            : 201.3 MB

Comparing Implementations with tokamax.standardize_function and tokamax.benchmark

To compare our PallasMatmul op across different configurations we can use tokamax.standardize_function and tokamax.benchmark:

  • tokamax.standardize_function(fn, *args, kwargs=..., mode=...) normalizes any callable and its inputs (and can even randomly initialize abstract jax.ShapeDtypeStruct inputs automatically).
  • tokamax.benchmark(f_std, std_args, iterations=...) compiles and profiles the standardized function over the requested number of iterations.
# `standardize_function` accepts concrete arrays or abstract ShapeDtypeStructs:
x_spec = jax.ShapeDtypeStruct((4096, 4096), jnp.float32)
y_spec = jax.ShapeDtypeStruct((4096, 4096), jnp.float32)
total_flops = 2 * x_spec.shape[0] * x_spec.shape[1] * y_spec.shape[1]

implementations = {
    "PallasMatmul (128x128x128)": PallasMatmul(
        config=MatmulConfig(bm=128, bk=128, bn=128)
    ),
    "PallasMatmul (heuristic)": PallasMatmul(config=ba.heuristics_config),
    "PallasMatmul (autotuned)": PallasMatmul(config=autotune_data.fastest_config),
}

print(f"{'Implementation':28s} | {'Median Time (ms)':>16s} | {'Throughput (TFLOP/s)':>20s}")
print("-" * 70)
for name, fn in implementations.items():
  f_std, std_args = tokamax.standardize_function(fn, x_spec, y_spec)
  bench = tokamax.benchmark(f_std, std_args, iterations=5)
  median_ms = bench.median_evaluation_time_ms
  tflops_per_sec = (total_flops / (median_ms * 1e-3)) / 1e12
  print(f"{name:28s} | {median_ms:16.3f} | {tflops_per_sec:20.2f}")
Implementation               | Median Time (ms) | Throughput (TFLOP/s)
----------------------------------------------------------------------
PallasMatmul (128x128x128)   |           17.577 |                 7.82
PallasMatmul (heuristic)     |            0.602 |               228.30
PallasMatmul (autotuned)     |            0.340 |               404.23

Summary Cheat Sheet

Wrapping any custom kernel as a Tokamax Op (tokamax/_src/ops/op.py) boils down to a few clean methods:

Component Purpose
config_cls = MyConfig Attaches a frozen @pydantic.dataclasses.dataclass(frozen=True) of tunable kernel hyperparameters to the Op.
_fwd(self, ..., *, return_residuals=False, config=None) (Required) Executes the kernel and returns (output, residuals).
bind(self, ..., *, return_residuals=False) (Optional) Validates and canonicalizes inputs, returning super().bind(...).
_get_heuristics_config(self, ba) (Optional) Returns a default Config based on the input shapes/dtypes in ba.arguments.
_get_autotuning_configs(self, ba) (Optional) Returns a set[Config] defining the autotuning search space for ba.arguments.
supported_on(self, device) (Optional) Checks whether the op is supported on device.

Once wrapped, you immediately get:

  • Binding inspection: ba = my_op.bind(*args) (ba.heuristics_config, ba.autotuning_configs, ba.default_config)
  • Autotuning: ba.autotune() or tokamax.autotune(fn, *args)
  • Benchmarking: ba.benchmark() or tokamax.benchmark(*tokamax.standardize_function(fn, *args))