Metadata-Version: 2.5
Name: metaljax
Version: 0.12.0
Summary: Experimental Metal backend for JAX on Apple silicon: a native PJRT plugin executing StableHLO on the GPU through a vendored MLX runtime
Project-URL: Repository, https://github.com/eterevsky/metaljax
Project-URL: Issues, https://github.com/eterevsky/metaljax/issues
Author-email: Oleg Eterevsky <oleg@eterevsky.com>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: apple-silicon,gpu,jax,metal,mlx,pjrt
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: GPU
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: MacOS
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.12
Requires-Dist: jax<0.12.1,>=0.12.0
Requires-Dist: jaxlib<0.12.1,>=0.12.0
Requires-Dist: ml-dtypes
Requires-Dist: numpy
Description-Content-Type: text/markdown

# metaljax — a Metal backend for JAX


metaljax lets unmodified JAX code run on Apple-silicon GPUs:

```console
$ JAX_PLATFORMS=metal python -c \
    "import jax.numpy as jnp; a = jnp.array([1, 2, 3]); print(2 * a, (2*a).device)"
[2 4 6] MetalDevice(id=0)
```

From JAX's point of view it is a regular PJRT backend: `jax.devices()`
reports a `METAL` device, and `jit`, `grad`, `vmap`, `lax.scan`,
`jax.random` (threefry), optax training loops, etc. all work. Under the
hood a native plugin lowers the compiled StableHLO programs onto
[MLX](https://github.com/ml-explore/mlx) arrays, which execute on the GPU
via Metal. The wheel carries its own patched MLX runtime, so nothing else
needs installing.

**Status**: beta; **0.12.0** is the first final release of the jax 0.12
line (see *What's new in 0.12.0*). Twenty real models — LLM decode
(dense, MoE, quantized), a vision encoder, diffusion, LoRA and
full-parameter training — run end-to-end through unmodified JAX code, and
are re-measured on the binary of every final release (the table under
*Benchmarks*, the ledgers [`models.md`](models.md) and
[`STATUS.md`](STATUS.md); test counts and performance per release and per
alpha in [`PROGRESS.md`](PROGRESS.md)). At 0.12.0, training steps beat
PyTorch's MPS backend on both training rows; decode trails the
Metal-native inference stacks (mlx-lm, llama.cpp) by 1.1–1.9×, except
model row 10 (DeepSeek-V2-Lite), which this release decodes about 2×
slower than 0.11.9 did (see *Known costs in 0.12.0*). Every
final release is gated by the pinned JAX test suite, a whole-model
correctness sweep against the CPU backend, and the model battery (0.12.0,
on jax 0.12.0.1: 99.58 % of the suite passing, 106/106); an alpha is checked
with a subset of that gate (see [`PROGRESS.md`](PROGRESS.md)). Coverage gaps remain —
unsupported constructs are declined at compile time, naming the op. If a
Metal backend ever lands upstream in the JAX ecosystem, this package will
be deprecated in its favor.

## What's new in 0.12.0

The first release for jax 0.12: it requires jax/jaxlib 0.12.0.x (tested
against 0.12.0.1) and no longer supports jax 0.11. It follows the alpha
0.12.0a1 and went through the full release gate. **Version numbers follow
jax's first three parts**: metaljax 0.12.0 is built and tested against jax
0.12.0.x, although jax itself is at 0.12.0.1. A fourth part (0.12.0.1,
0.12.0.2, …) counts metaljax's own releases on the same jax line and is
unrelated to jax's fourth part.

Measured by the release gate on this release's binary (`07ccf7b6`; macOS
27.2.1 on an M5 Max, 2026-11-26): the pinned jax 0.12.0.1 suite 29,582
passed / 126 failed (99.58 %; 0.11.9 on jax 0.11.2: 99.53 %), every
failure on the list of expected ones; `tests/` 5,930 passed / 140 xfailed
/ 0 failed; texmo correctness 106/106; texmo speed 1.18× the anchor sweep
and 1.03× 0.11.9's release sweep; on the model rows (the table under
*Benchmarks*), 19 of 20 rows decode or step within 3 % of 0.11.9 or
faster (rows 6 and 16 take about 12 % less time, row 8 10 % less, within
its own run-to-run spread), and row 10 about 2× slower (see *Known costs
in 0.12.0*). The alpha's numbers are in
[`PROGRESS.md`](PROGRESS.md).

**macOS 26.5 or newer; the release gate ran on macOS 27.2.1.** The wheel
is tagged `macosx_26_0_arm64`, so pip installs it only on macOS 26 and
later. The bundled MLX libraries declare macOS 26.5.2 as their minimum;
the plugin library itself declares 27.2, the macOS SDK it was built with
(as did the alpha's plugin, which ran on macOS 26.6.2). The `macosx_14_0` tag the wheels carried through 0.11.9 was wrong since
0.11.5: the plugins of 0.11.5, 0.11.6 and 0.11.9 already declare macOS
26.5 or later. The development machine (M5 Max, 128 GiB) moved from macOS
26.6.2 to 27.2.1 (26B131) on 2026-11-25, before the release gate: the
gate, and every 0.12.0 number in this README, ran on macOS 27.2.1. On
macOS 26 the release was checked once, without the gate: on 2026-11-27 a
wheel with this release's plugin, MLX runtime and loader was installed on
a Mac mini (M4, 32 GiB, macOS 26.6.2, Python 3.13) and ran this
repository's `tests/`: 5,891 passed, the same 140 expected failures as on
the M5, and 23 skipped (20 need a C compiler that machine lacks, 3 need
16–26 GB of device memory). Two of the passes are from a second run: the
first time, with the desktop session's other programs holding most of the
32 GiB, the memory governor refused them with `RESOURCE_EXHAUSTED` (see
*Known limitations*). The jax suite, texmo and the model rows did not run
on macOS 26. The 0.11.9 numbers this README compares with were measured
on macOS 26.6.2.

**jax 0.12**

- **The plugin is built against jax 0.12.0.1's own XLA** (PJRT C API
  0.116, StableHLO/VHLO 1.22).
- **MoE decode through `lax.ragged_dot` keeps its fast path.** jax 0.12
  spells the group starts differently and the recognizer missed it: model
  row 10 (DeepSeek-V2-Lite, in the table under *Benchmarks*) fell to a
  dense chain at ~1948 ms/token. Both
  spellings match now.
- **Explicit-axis meshes** (the default of jax 0.12's `jax.make_mesh`) no
  longer push argmax/argmin, sort, scatter, pooling selects and the
  generated scan kernels off their fast paths (argmax had become
  2.4–3.5× slower).
- **New jax 0.12 surface that works:** the layout API (`Format`/`Layout`,
  `device_put` into a Format, compile-option layouts; any dense
  permutation layout, tiled layouts decline by name); `jnp.int1` /
  `jnp.uint1` buffers (as on XLA:CPU, a program argument of these types
  holds at most one element); `bitcast_convert` of every f8/f6/f4 type,
  bit-exact including NaN payloads (and f8 host transfers ~25× faster);
  `jax.nn.scaled_dot_general` with mxfp8/mxfp4.
- **Host callbacks run through jax's own lowering rules**
  (`pure_callback`, `io_callback`, `jax.debug.*`, checkify), with jax's own
  messages. They need the CPU backend listed (`JAX_PLATFORMS=metal,cpu`):
  with metal alone they raise jax's own "failed to find a local CPU
  device" error, as on any accelerator (checkify's runtime errors work
  either way). A callback now gets owned, read-only copies of its
  arguments: one that kept its argument used to read recycled memory
  (`debug.callback(saved.append, x)` over 3 calls gave `[7, 7, 7]`).

**The vendored MLX moves to v0.32.4** (our fork, 32 fix branches; the
series and its notes are in `notes/patches/`):

- **Cold first calls back near 0.11.9's.** MLX v0.32.1 gave its complex
  type implicit conversions to vectors in a header that every Metal source
  MLX compiles at run time includes, and each compile took about twice as
  long: 0.12.0a1's first calls were 1.6–2.1× slower than 0.11.9's when the
  OS's cache of compiled Metal code was cold. Our fork makes those
  conversions explicit (fix branch 32); what remains is in *Known costs in
  0.12.0*.
- **Fixed: two fused kernels sharing one name ("MLX bug #8").** MLX named
  a fused kernel by a hash of its constants' texts written back to back
  with no separator (and of its input wiring, likewise), so two different
  fused graphs could get the same name and the second ran
  the first one's kernel and constants: silent wrong values (a
  scatter-add could drop elements; two of jax's sparse tests failed on
  it). Stock MLX has the bug too (`notes/mlx-fusion-bug8-2026-11.md`).
- **Also fixed with it:** `cummax` / `cummin` dropping NaN; misaligned and
  non-contiguous views (a widening bitcast of a byte slice at a misaligned
  offset read the wrong address); FFT out-of-bounds writes that corrupted
  other FFTs in the program, and FFTs of 2^20–2^24 points (INTERNAL or
  wrong values; above 2^24 a clean error); sorts of rows longer than
  ~2.09M elements; 32-bit index overflow past 2^31 elements; convolutions
  with more than 32,767 output channels or filters wider than 32,768
  taps; complex divide and power at extreme magnitudes; f16 int4
  quantized matmuls returning NaN where CPU gives 0; complex `0 ** 0.0`
  (was 0). Details: `notes/gap-vs-jax-0.12.0.1-2026-11-11.md` §3 and
  `notes/mlx-vendoring-plan.md` §7.

**Correctness fixes in the plugin**

- **Complex64 `tan` / `tanh`**: both components within 3 ULP of the
  correctly rounded value (XLA:CPU 4–5); the small component used to be off
  by up to 8.7e8 ULP, and exactly 0 from |Im z| (tan) or |Re z| (tanh)
  ≈ 8.6. The complex exp inside `sinh` / `cosh` no longer overflows to inf
  for |Re z| in (88.7, 89.4).
- **Generated scan kernels match XLA:CPU bit for bit** (silent wrong
  values before; NaN sign/payload and the zero a max/min tie returns
  follow the plugin's non-kernel path, the documented exceptions): integer and/or/xor/not ran as logical ops (a u32
  xor-carry scan answered `[1, 1, 1, 1]`), signed wrapping, max/min NaN
  propagation, bf16/f16 rounding of dots and accumulators, and view and
  index cases that read the wrong rows. Integer `x / 0`, `x % 0` and
  `INT_MIN / -1` match XLA:CPU inside and outside the kernels.
- **Outputs own their storage**, as on XLA:CPU: an output could share
  memory with a live argument (`jit(reshape)(x)` returned x's pointer), two
  outputs could overlap, and `device_put(..., may_alias=False)` returned the
  same storage. Donation deletes only the donors XLA:CPU consumes (one
  known exception: a donor that `np.asarray` has read is deleted, where CPU
  keeps it).
- **A failed evaluation no longer corrupts the next one** (its command
  buffer stayed open; a later cache clear could free buffers it used, and
  outputs came back at relative error 1.0).
- **Threads**: a thread entering the plugin for the first time while
  another evaluated could segfault or fail with INTERNAL "There is no
  Stream(gpu, N) in current thread".
- **Errors**: `compiled.as_text()` on a program holding a float6 constant
  killed the process (in XLA's exporter; XLA:CPU too) and now returns None;
  Metal's buffer cap met by a compile or an argument conversion, and MLX
  allocation failures that survive the recovery steps, are
  `RESOURCE_EXHAUSTED` (were INTERNAL). Since the alpha, a refusal by
  Metal (its buffer cap, an allocation, a command queue or a shared event
  it will not make) is `RESOURCE_EXHAUSTED` at every entry point: a host
  transfer, a host read, a device copy, a compile, a thread's first use of
  the plugin and a program's first call raise it as `JaxRuntimeError`, a
  steady jit call as `ValueError` (jax's dispatch raises that for any
  failed execute). Before, these were a bare `RuntimeError` or
  `ValueError` with MLX's own text (a compile on a fresh thread:
  INTERNAL), and a refused transfer leaked its staging block.

**Memory**

- **Host transfers stage through the plugin's own pool.** Through the
  alpha a transfer's staging block (which becomes the device array's
  storage) came from malloc, and macOS's allocator keeps freed blocks of
  2 MiB to 4 GiB cached inside the process, where the memory governor
  counted them but could not give them back: near a memory line it
  refused work that fit (under a budget 2,560 MB above the process's
  starting footprint, after a 2 GB array was put and deleted, the next
  2 GB put was refused). Blocks of 2 MiB or more now come from the
  plugin's own pool, which the governor counts and empties at its hard
  line; the pool also unmaps a block unused for 10 s, and everything on
  the system's memory-pressure notification. `METALJAX_STAGE_POOL_MB`
  (4096) bounds what it keeps; `0` turns it off (malloc as before). Its
  costs are under *Known costs in 0.12.0*.
- **The memory governor reads free memory correctly on macOS 27.** From
  macOS 27 the kernel counter the governor read for free pages covers the
  global free queue only; the per-CPU free queues and, on chips with
  memory tagging such as the M5, four kinds of free tag-storage pages are
  counted elsewhere. The governor therefore saw the machine 0.4–1.9 GB
  fuller than it was, and refused or paced work that much early (the
  plugin's own ingest test failed three checks on macOS 27.2.1). It now
  adds the kernel's free terms; on macOS 26 it reads as before.
  `METALJAX_MEM_FREE_SYSCTLS` replaces the list of counters, for a kernel
  that splits its free count differently. Not yet run on a Mac without
  memory tagging on macOS 27 (the M1–M4 list is inferred); on macOS 26
  it ran this repository's tests once, on an M4 (above).

**Faster, or newly compiling**

- **Pooling without a size cap.** `lax.reduce_window` (max / average
  pooling and their gradients) refused to compile once output × window
  elements passed 2e8 — a ResNet stem 3×3/2 max pool on 112×112×64 past
  batch 110. Such programs now compile (tested to batch 8192) and match
  XLA:CPU. Below the old cap, compiled and warm: stem max-pool JVP 96.0 →
  2.75 ms, its gradient 97.9 → 7.4 ms, a small CNN training step 11.5 →
  4.3 ms. Negative window padding works.
- **`jnp.linalg.solve` / `inv` 4–35× faster**: every LU except a 1×1 f32 / c64
  matrix runs on the host (Accelerate), at n = 100 9.5 → 0.34 ms, at n = 1000 104 → 3.0 ms, and
  solve / inv / slogdet inside `jax.shard_map` no longer raise TypeError. A
  single small solve stays 8–180× slower than XLA:CPU (the GPU round trip).
- **`jnp.argmax` / `argmin`** take 0.58–0.95× of their time before the MLX
  update: MLX's arg reductions now apply XLA's NaN rule themselves (the
  first NaN wins), so the plugin's extra pass over the data is gone.
- **Host → device transfers** of dense or row-contiguous arrays are
  memcpys: a 4 MB f32 `device_put` 2328 → 137 µs. The
  memory governor now reads the
  machine's page counts live, so a fast load no longer runs hundreds of
  megabytes past its limits (processes sharing one ceiling can still pass
  it by one allowance each, about 0.2 GB for two).

**Known costs in 0.12.0.** The first five are what the release gate
found or what changed since the alpha; the rest were measured for the
alpha and no later change touched them. Unless a bullet says "not
measured" or names another comparison, each cost was measured against the
build before its change:

- **model row 10 (DeepSeek-V2-Lite through MaxText) decodes about 2×
  slower than in 0.11.9**, a regression: 42.3 and 40.8 ms/token in the
  gate's two complete runs, against 20.3 at 0.11.9. The cause is known: jax 0.12
  inlines `lax.scan` bodies into the program, XLA then moves their
  constants out of the loop, and the plugin's constant folding stops at
  the loop boundary, so MaxText's rotary-embedding table (40 MiB, built
  from `jnp.arange`) is rebuilt in every layer loop on every call: 220
  more kernel launches and about 19.5 ms more GPU time per decode step. A
  fix is drafted (not yet reviewed, nor measured on this row); it is not
  in this release, and treating this regression is planned shortly after
  it. Other
  programs whose scan bodies compute large tables from constants may pay
  the same way (not measured). The row's checkpoint load also peaks
  higher than at 0.11.9 (91–107 GiB on this 128 GiB machine, against
  83–87 GiB), and the benchmark harness's own memory guard (not the
  plugin) stopped 4 of its 6 runs in the gate during the load: the cell in
  the table got a number in 2 of 3 runs, its variant with the random-key
  split moved out of the timed loop in none of 3;
- **on macOS 27, the first run of a program after the plugin binary
  changes is slower**, in the steady state too, not only at its first
  call: in the gate, model row 15 decoded at 347.0 ms/token on its first
  run and 266.0 on a second run at the end of the gate, about an hour
  later, row 21 at 154.4 and 141.9, row 8 at 24.6 and 21.2 (the table has
  the second readings; 0.11.9: 265.5, 142.6 and 23.5). The first release candidate's gate showed the same on the
  same three rows. The cause is not established; the system's caches of
  compiled GPU code are the likely place. Measure twice after installing
  or upgrading;
- **peak memory of the two MaxText model rows grew**: row 15 peaked at
  64 and 80 GiB in the gate's two runs, against 53 GiB at 0.11.9, and
  row 10 at 91–107 GiB against 83–87 (the other big-memory rows, 3, 7, 8,
  9, 12, 17 and 21, are within 2 GiB of 0.11.9). Measured on macOS
  26.6.2, most of row 15's extra memory, and what row 10 holds while it
  decodes, is the loader's own freed host arrays, kept by macOS's
  allocator (see *Known limitations*); the staging pool adds to it,
  because its blocks do not reuse what the loader freed (row 15 held about
  12 GiB more with the pool than without it);
- the staging pool (new since the alpha): a working set of host transfers
  put and deleted over and over that is larger than the pool's 4096 MB
  cap re-maps its blocks (six 1 GB arrays put and deleted per round: 91.9
  → 160.6 ms, 1.75×; at parity with `METALJAX_STAGE_POOL_MB=8192`), and a
  put of a pooled size more than 10 s after its block was last used maps
  a fresh block (about +33 ms per GB on that put);
- first calls and cold start: in the release gate, a process's first
  calls took longer than in 0.11.9's gate: model row 18's (LoRA) first
  training step 6.89 s against 5.44 s (+27 %), row 2's warm-up (compile
  and first calls) 7.37 against 6.07 s (+21 %), row 4's 3.44 against
  2.66 s, and texmo's first
  calls 1.108× as long in geometric mean over 223 configurations. These
  compare two gates on different macOS versions (27.2.1 against 26.6.2),
  so the OS's share is not separated. Measured before the gate, on macOS
  26.6.2 against the 0.11.9 plugin in fresh processes with every compile
  forced cold (the case where a process's GPU kernels are not in the OS's
  cache of compiled Metal code, for instance the first run after
  installing or upgrading): each library compiles about 11 ms slower than
  on 0.11.9's MLX, which added about +0.6 s (9.5 %) to row 18's first
  step, +0.64 s (10 %) to row 2's first call and 1.034× to texmo's first
  calls (over 51 configurations); warm, there was no difference;
- signed integer `//` and `%`: 1.30–1.38× in a chain (MLX's
  `floor_divide` now floors; the plugin restores XLA's truncation); fused
  integer divide / remainder index math 1.16–1.37× (the `x / 0` rules);
- one of the 223 configurations of texmo's speed sweep
  (`bits.4.oh+bp|rnn.32.gelu-rnn.16.gelu-split.add(dense.16.gelu-rmsnorm, pass)`:
  two recurrent layers and a residual dense + RMSNorm branch; fp32, batch
  32, length 256) takes 6 % longer per step than in 0.11.9's release sweep
  in the release gate (1.01 against 0.95 ms; 7 % in both sweeps of the
  alpha; 0.11.9's sweep ran on jax 0.11.2 and macOS 26.6.2); the sweep as
  a whole is 1.03× faster than 0.11.9's;
- max-pool gradients / JVPs with a window dimension past 64: 1.03–1.11×
  (on the new MLX the window copy also replaces NaNs, to keep 0.11.9's
  rule that a NaN never wins the pick); a global 112×112 pool varies
  between processes on every build and read 1.07–1.19× in one battery,
  0.72–0.74× in another; peak memory unchanged;
- pooling: float sums over windows of more than 64 elements add in a
  different order (f32 within 3.5e-7 of XLA:CPU, 1.1e-6 on 31×31; 16-bit
  sums and products differ from 0.11.9's bits within the f16 tolerance); a
  max-pool gradient past 2e8 window elements with a window dimension over
  64 runs op by op in slabs, outside the compiled graph; past
  the old size cap, the memory governor does not count a compiled pooling
  fold's temporary (about 1.5× its inputs), and two such shapes run slower
  than XLA:CPU (a VGG 2×2/2 forward 1.9×, a global 7×7 average-pool
  gradient 7.8×);
- complex `tanh` inside a compiled loop body or fused chain: 1.3–4× (the
  new kernel does not fuse; 4× at 1e7 elements per step), and on its own
  1.0–1.2× up to 1e6 elements, 1.03–1.88× at 1e7; complex `sinh` /
  `cosh` 1.19× at 1e7 elements; complex `tan` got 3–5× faster;
- host callbacks: about twice the per-call overhead (16.5 → 32 µs; XLA:CPU
  17), and large operands pay one copy, as on XLA:CPU (16 MiB: 20 → 326 µs;
  CPU 318);
- copies the no-alias contract requires, as XLA:CPU makes them: a view of
  a live argument returned as an output (texmo's eager chunk feed: ~210 µs
  per 16 MB feed, +8 to +30 % of the feed); `device_put` into
  `pinned_host`, or with `may_alias=False`, copies (~200 GB/s warm). A
  view of an argument whose donation jax found unusable is now a copy, as
  on XLA:CPU (more memory for that pattern). Not measured: the first
  donation of a `device_put` buffer copies once;
- bf16 recurrent scan kernels: +1.5–2.5 % on about half of the bf16
  recurrent rows of texmo's sweeps (the exact accumulation); a few unusual
  scan-body spellings that ran wrong inside a generated kernel now run
  correctly outside it, 1.4–23× slower (none in texmo's loops);
- in a multi-threaded process, other threads' executes and transfers wait
  while a program compiles (not measured);
- host linear algebra: `eigh` of many small matrices 1.004–1.014× (the
  shared host path); a host linalg call inside a loop body costs one round
  trip (~0.4 ms) per step; the triangular solve's new direct BLAS path rounds
  differently from XLA:CPU for some flag combinations (8 of 64 complex64
  cases, worst 2.6e-7 relative);
- a failing execute +74 µs (+13.6 %: its command buffer is now committed
  and waited for); donated identities (LoRA-shaped) up to ~1.3 %; a
  3,000-piece `unravel_pytree` +1.9 % (median);
- after a reduce that now folds away as on XLA:CPU (for instance one whose
  result has as many elements as its operand), `max(0, ·)`,
  `clip(·, 0, 1)` and `y * (y > 0)` can differ from XLA:CPU at a signed
  zero where 0.11.9 matched it (23 of 20,236 test programs compared bit
  for bit with XLA:CPU; the fold's own output matches XLA:CPU);
- artifacts exported with this version that use `lu_solve` do not run on
  an older plugin.

**What the release gate ran, what it did not, and what is deferred**

- Ran, on this release's binary, on macOS 27.2.1: this repository's
  `tests/`, the plugin's two contract suites (`execute_test.py`,
  `ingest_test.py`), the plugin's C++ tests (8 of 8 passed; bazel took
  four of the results from its cache, from an earlier run with identical
  inputs, rather than running them again), the pinned jax 0.12.0.1 test suite, texmo's
  whole-model correctness sweep (106 configurations) and its
  223-configuration performance sweep, all 20 rows of the model table
  (ten of them also on the CPU backend, six of those with the generated
  tokens compared one by one), the big-memory rows that check for a clean
  out-of-memory error instead of a machine crash, and the buffer tests at
  Metal's real resource limit. On the project owner's instruction the
  gate ran in order of risk (the test suites and the main model rows
  first, then the big-memory rows from the least to the most memory, then
  the real-limit tests, and last the second runs of rows 8, 15 and 21),
  where the release procedure starts with the real-limit tests.
- Not run: row 20 (left the suite at 0.11.9, see *Benchmarks*); the other
  frameworks' cells of the comparison (mlx-lm, llama.cpp, torch-MPS),
  which are from earlier runs; the release gate on macOS 26 (only this
  repository's `tests/` ran there, on an M4). Not part of
  the release gate: texmo's bf16 speed sweep, the `jax.export` harness
  sweep and the model-sized Metal command-buffer canaries.
- Deferred past 0.12.0, judged minor. The upstream jax tests known to
  touch them fail as expected or skip on Metal: the user XLA transform
  fails 4 `xla_transform_test` ids, on the expected-failure list; the
  duplicate-index set fails one `state_test` case once `hypothesis` is
  installed (the gate's venv lacks it, so the file is listed as a
  collection error, as on CPU); the compilation cache, QR with pivoting
  and `spsolve` tests skip on Metal (the compilation-cache tests also end
  in teardown errors, which are on the expected-failure list). The items:
  `x.at[idx].set(v)` with duplicate indices picks a different winner from
  call to call (XLA:CPU: the last); the persistent compilation cache
  (`jax_compilation_cache_dir`) silently does nothing; no lowering for QR
  with column pivoting or `sparse.linalg.spsolve`; `dynamic_slice` /
  `dynamic_update_slice` with a uint32 start ≥ 2^31 use row 0 (CPU: the
  last row); `jax.scipy.linalg.sqrtm` ~1000× slower than CPU; registering
  a user XLA transform (HLO pass) raises; under jit, `(x + 1) > x` on a
  signed integer at its maximum folds to True;
  `x * mask.astype(jnp.float32)` gives NaN where the mask hides an inf/NaN
  (XLA:CPU's simplifier turns it into a select, so CPU gives 0 under jit;
  write `jnp.where(mask, x, 0)`); max-pool gradients / JVPs over windows
  that hold a NaN do not always equal XLA:CPU's (since 0.11.9 they moved
  closer to it overall; one case moved away: with a window dimension past
  64, the JVP of a window that starts with a -inf, holds a NaN and holds
  nothing above -inf is 0, where 0.11.9 and XLA:CPU return a tangent of
  the window).

## What's new in 0.11.9

- **Training loops no longer hold many steps' worth of memory at once.** A
  counted loop (a `lax.scan` over training steps) used to decide how much
  work to queue ahead of the GPU by op count alone, and MLX allocates every
  intermediate when work is queued — so a 10k-weight recurrent LM's
  256-step training chunk briefly held 5 GB for a 0.3 GB working set and
  died with `RESOURCE_EXHAUSTED` on a busy 32 GB machine. Loops now measure
  what each queued step holds and keep at most `METALJAX_LOOP_INFLIGHT_MB`
  (1 GB) in flight, waiting on the oldest step so the GPU stays busy: that
  chunk now peaks at 1.1 GB and runs ~17 % faster (the old cadence drained
  the GPU at every sync), and texmo's own multi-model training loop peaks
  at 4.9 GB instead of 8.5.
- **The memory governor gives back its own cache before it gives up.**
  Past a hard line it now waits for in-flight GPU work to finish and clears
  MLX's buffer cache, at the start of the stall and on every tick of it,
  instead of once and rate-limited; a refusal now says how much of what the
  process holds is live arrays and how much is cache.
  Details: [`notes/loop-inflight-window-2026-09.md`](notes/loop-inflight-window-2026-09.md).

## What's new in 0.11.8

- **jax 0.11.2.** The pinned release (and its test suite) moved from jax
  0.11.0 to 0.11.2; the plugin keeps working with 0.11.0/0.11.1. Moving
  surfaced a **silent-wrongness bug fixed in this release**: floating-point
  `lax.rem` / `jnp.fmod` was inexact on every earlier release (up to 1 ULP of
  the dividend in f32, large errors in bf16, and overflow to inf in f16); it
  is now bit-exact against the CPU backend. Also new: `int2`/`uint2` (and
  sub-byte integer conversions now saturate like jax-CPU), and
  `with_layout_constraint` is accepted. Note jax 0.11.2 itself refuses
  bf16/f16 linear algebra at trace time. The plugin now builds against
  jax 0.11.2's own XLA commit (PJRT C API 0.115, StableHLO/VHLO 1.20, so
  jaxlib no longer downgrades programs to an older VHLO for it); jaxlib
  0.11.0 still loads it. Details: `notes/jax-0.11.2-pin.md`.
- **Integer shifts, popcnt and clz match XLA bit for bit** (a
  silent-wrongness fix): `lax.shift_right_arithmetic` on unsigned integers
  ran as a logical shift, negative or very large shift amounts escaped the
  saturation guard into Metal's mod-width shift, and the emulated
  2/4-bit integers shifted and counted their 8-bit storage. All are now
  exact against the CPU backend.
- **Precision default.** `METALJAX_MATMUL_PRECISION=high` is now the
  shipped default: f32 GEMM/attention stay **off** the M5's neural
  accelerators (exact, the pinned ~1e-6-vs-f64 class), while bf16/f16 and
  quantized matmuls use them — what mlx-lm and torch-MPS do. `highest`
  pins the pre-accelerator arch for every dtype; `default` is MLX's own
  (accelerator f32, ~8e-4). f32 is never silently degraded.
- **Decode and MoE work.** A ragged decode form for the MoE expert
  dispatch (a direct `gather_mm` over sorted expert ids); stacked sibling
  packs (several stacked per-layer dots reading one activation become one
  `gather_mm` over their `[L, K, N]` views concatenated on the free axis);
  projection packs (sibling decode projections over one activation become
  one dot over concatenated weights); the rotate-half rope as one fused
  kernel over a reversed pair view; submit-ahead pipelining of dynamic
  `while` loops; the KV cache written in place; chunk boundaries donating
  their carries; loop-position specialization (one compiled body per chunk
  with the loop position folded into its dynamic slice starts, now on by
  default). In the vendored MLX fork: empty command buffers skipped in
  `gpu::finalize`, and a transient-only byte cadence (opt-in, off by
  default).
- **Recognizer coverage**: a fused gated-delta-net decode step; the norm
  recognizer covers keras-hub's Qwen3.5/gemma4 and flax-NNX spellings;
  fused attention on the keras MoE rows (sinks, chained masks) and on
  multi-span GQA decode.
- **keras-hub's Gemma4 int4 models are numerically broken upstream.** The
  Gemma4 decoder block's "HOTFIX" multiplies activations by the raw
  unpacked int4 codes, scale unapplied, so every backend decoded one
  repeated token; every row-13 cell through 0.11.7 was timing that broken
  graph. The benchmark harness now routes the int4 FFN through the
  quantized layers and gathers embedding rows before unpacking
  (`scripts/model_bench/int4_fix.py`). Write-up:
  [`notes/keras-hub-gemma4-int4-hotfix-issue.md`](notes/keras-hub-gemma4-int4-hotfix-issue.md).
- **Two msl_scan silent-wrongness fixes**: a value that is one scalar per
  lane is not a register vector (it was broadcast over a whole row of the
  buffer), and only the proven induction variable is a loop counter —
  every other scalar carry is now classified by what the body does with it
  (invariant carries pass through; stepped ones become kernel state).
  Both are described in `CLAUDE.md` and in their commits; no shipped
  number or token stream moved.
- **New comparator targets** in the ledgers: mlx-lm on a local bf16
  Mixtral 8×7B conversion (row 12), mlx-lm's own 4-bit quantization of
  gemma4-E2B (row 13), and a torch-MPS full AdamW train step at MaxText's
  defaults (row 19).

## Install

```bash
pip install metaljax
```

This installs 0.12.0, which requires jax 0.12.0.x. To stay on jax 0.11,
run `pip install "metaljax==0.11.9"`; its `jax<0.12` requirement moves
jax, and with it jaxlib, back to 0.11.x.

Requirements: Apple-silicon Mac, macOS 26.5 or newer, Python 3.12+, jax
0.12.0.x (installed automatically). No `mlx` install is needed — the
wheel bundles its own — and if you do have the public `mlx`, the two
coexist. Then select the backend per program:

```bash
JAX_PLATFORMS=metal python -c "import jax; print(jax.devices())"
```

CPU remains the default backend when `JAX_PLATFORMS` is unset, so
installing metaljax does not change existing workflows. metaljax ships as
a wheel only: the plugin is built against a pinned XLA workspace with
bazel, which is not something an sdist can compile at install time.

## How it works

```
jax.jit(f)(x)
  │  StableHLO (serialized portable artifact)
  ▼
libmetal_pjrt_native.dylib    ── the plugin: an xla::PjRtClient, with
  │  plugin-native/metal/        XLA's pjrt_c_api_wrapper_impl making the
  │                              PJRT C API around it. No Python, no GIL.
  │  compile: parse + lower StableHLO to a tape, decide what to fuse
  │  execute: replay the tape on device buffers
  ▼
plugin-native/runtime/        ── the executor: op emitters, MSL kernel
  │                              codegen, control flow, host LAPACK
  ▼
libmlx_metaljax.dylib         ── our vendored, privately install-named
                                 MLX: lazy Metal arrays, unified memory
```

- The plugin is self-contained: LLVM/MLIR/StableHLO/absl are linked in and
  private, and exactly three symbols are exported (`GetPjrtApi`, a
  callback bridge and a garbage-collector hook), so it coexists with
  TensorFlow-class carriers in one process.
- Registration happens through the `jax_plugins` namespace package
  (`src/jax_plugins/metal/`), at **priority −1**: CPU stays the default
  backend unless you opt in via `JAX_PLATFORMS`. That module also bridges
  jax's host callbacks (`jax.debug.print`, `pure_callback`, `io_callback`):
  it emits them through jax's own lowering rules, the executables own the
  callables (as on CPU), and the plugin calls back through one C function
  pointer.
- Python appears nowhere on the execute path.
- Before the first program runs, the plugin lowers what it can into fused
  forms: quantized matmuls, mixture-of-expert dispatches, softmax
  attention, norms, rope, sibling projection and per-layer stack packs,
  and — for recurrent scan bodies — generated Metal kernels. Each
  recognizer has an off switch (see *Environment variables*), and each is
  checked against the literal graph by the differential suites.

## Requirements

- Apple-silicon Mac (developed on an M5 Max with 128 GiB, macOS 27.2.1,
  Xcode 27.2, where the 0.12.0 release gate ran; macOS 26.6.2 ran the
  alpha and the development builds of 0.12.0 but not its release gate,
  and a Mac mini M4 on macOS 26.6.2 ran this repository's tests from the
  wheel — any arm64 Mac on macOS 26.5 or newer with a recent Xcode should
  work).
- [uv](https://docs.astral.sh/uv/) (only for creating the venv).
- Python **3.12+** (the development venv below uses 3.14) and jax/jaxlib
  **0.12.0.x** (tested against 0.12.0.1,
  the pinned release, whose XLA commit the plugin is built against).

## Developing from source

```bash
git clone https://github.com/eterevsky/metaljax && cd metaljax
uv venv --python 3.14 .venv
uv pip install -p .venv/bin/python jax numpy pytest
uv pip install -p .venv/bin/python -e .
./scripts/vendor_mlx.sh                        # build + stage the MLX runtime
cd plugin-native && bazel build //metal:libmetal_pjrt_native.dylib && cd ..
cp plugin-native/bazel-bin/metal/libmetal_pjrt_native.dylib src/metaljax/lib/
```

(The first bazel build is ~7 minutes; after that it is seconds. An
editable install loads the dylib out of `src/metaljax/lib/`, and
`METALJAX_PLUGIN_PATH` overrides it with any build you want to measure.)

Verify:

```bash
JAX_PLATFORMS=metal .venv/bin/python -c "import jax; print(jax.devices())"
```

should print `[MetalDevice(id=0)]`.

## Running the tests

The pytest suite runs everything through the real plugin — `jax.jit` on
the Metal device, or `compile_and_load` for hand-written StableHLO — and
compares against the JAX CPU backend:

```bash
.venv/bin/python -m pytest tests/ -q
```

Current suite: about 6,000 tests (6,070 at 0.12.0: 5,930 passed and 140
expected failures; the counts per release and alpha are in
[`PROGRESS.md`](PROGRESS.md)) across
elementwise/transcendental ops,
shapes and broadcasting, `dot_general`/einsum, reductions and cumulative
ops, control flow (`while`/`cond`/`scan`), gather/scatter, sorting,
convolutions, linalg, complex, RNG, sub-byte and bf16/f16 dtypes, the
quantized-matmul / MoE / attention recognizers, the generated scan
kernels, donation, buffer pointers, concurrency and the Metal
command-buffer canaries.

The plugin has its own differential suites, which compare it against
jax-CPU expression by expression and on whole models:

```bash
.venv/bin/python plugin-native/execute_test.py     # vs jax-CPU
.venv/bin/python plugin-native/ingest_test.py      # host->device transfer path
.venv/bin/python plugin-native/texmo_gate.py       # whole-model training
cd plugin-native && bazel test //...               # C++ unit tests
```

End-to-end smoke test (device buffers, compile, execute, PJRT events):

```bash
JAX_PLATFORMS=metal .venv/bin/python -c "
import jax, jax.numpy as jnp
g = jax.jit(jax.grad(lambda x: jnp.sum(jnp.tanh(x) ** 2)))(jnp.arange(4.0))
print(g, g.device)"
```

## Coverage and known gaps

On the 0.12.0 release (jax 0.12.0.1, the pin of the 0.12 line), the test
suite of the pinned jax release executed 29,708 tests with **99.58 %
passing** — 29,582 passed / 126 failed (plus 7,097 skipped and 35 error
nodes), measured 2026-11-26 on the release binary. Every failure and
error is on the list of expected ones
(`notes/data/pinned-0.12.0.1-failures.txt`, each entry with its class and
reason); two tests on that list now pass (the sparse tests the MLX fused-
kernel-name fix cured; the list still names them). The failures concentrate in
`export_harnesses_multi_platform_test` (44), `lobpcg_test` (27),
`x64_context_test` (13 — the f64 policy below), `lax_test` (9),
`api_test` (5), `export_test` (5), `shape_poly_test` (4) and
`xla_transform_test` (4). (0.11.9, on jax 0.11.2: 28,679 passed / 135
failed, 99.53 %.) Every remaining failure has been individually examined
and classified with evidence (`notes/jax-test-suite-2026-07.md`, and the
list above for the 0.12 pin); they fall into three groups:

**Intentional (platform constraints, will not change):**

- **No float64.** Metal GPUs have no f64 ALUs. A program that mentions
  an f64 value fails at compile time (`UNIMPLEMENTED: metaljax-native:
  element type f64`) rather than run silently in f32. That includes
  creating an f64 array with `jnp.array` and passing one through a
  jitted function unchanged; there is no downcast switch. Keep
  `jax_enable_x64` off. Same policy for complex128. (`jax.device_put` of
  an f64 NumPy array is accepted: with x64 off jax converts it to f32
  itself, as on every backend; under x64 the Metal array is labelled
  float64 but holds f32 values — 1e300 reads back as inf — and no program
  can consume it.)
- **One physical device.** `pmap`/`shard_map`/collectives **work on a
  single device** (replica groups of size 1); actual multi-device
  sharding has no hardware to run on.
- **Denormals flush to zero** on the GPU (hardware behavior); tests
  asserting subnormal outputs (e.g. `jnp.spacing`) differ from CPU.
- **NaN sign and payload** do not survive float arithmetic, float
  conversions or a float select (GPU behavior): every NaN such an op
  produces or passes through comes back as the canonical +NaN (0x7FC00000
  in f32, the matching quiet NaN in f16/bf16/f8). Moves keep the bits —
  host transfers, copies, identities, donation, layouts and the host
  callback bridge are bit-exact, signalling NaNs included — so a NaN that
  only travels arrives unchanged. Tests asserting a -NaN or a payload after
  compute differ from CPU.
- **Complex special values at inf/NaN poles** for a handful of
  transcendentals (log/trig/hyperbolic family) follow MLX's kernel
  semantics rather than C99. Finite inputs match CPU; full C99 pole
  behavior would need per-element branches in hot paths (policy: not
  worth the slowdown). `sqrt`/`rsqrt`/`exp`/`expm1`/`abs`/`sign`
  are rebuilt for C99 special values (their remaining accuracy gaps are
  listed in `notes/complex-tan-2026-11.md`); `tan`/`tanh` are computed in
  XLA:CPU's own formulation, as one Metal kernel with its own expm1 and
  sin/cos (the GPU's real cos/sin are 2-3 ULP, and tanh's 4cos^2(Im z)
  denominator doubles that wherever |Re z| is small), so both components
  stay within 3 ULP of the correctly rounded value across the plane
  (XLA:CPU 4-5; MLX's kernel lost the small one once |Re|, resp. |Im|,
  passed ~2) and the special values are XLA:CPU's. The kernel does not fuse
  with its neighbours: complex tanh inside a compiled loop body or a fused
  chain costs 1.3-4x the old lowering, growing with array size (4x at 1e7
  elements per step); complex tan got 3-5x faster. The cost table is in
  the notes.

**Remaining audited gaps** (every one re-examined during the 0.11.0
parity campaign and approved as-is; each carries evidence in
`notes/jax-test-suite-2026-07.md`):

- *Ordered-effect residue*: `buffer_callback` is rejected by a jax-side
  platform allowlist (`buffer_callback.py` hard-codes cpu/cuda/rocm/oneapi)
  and hands the callback XLA-runtime buffer objects a plugin cannot make —
  not reachable from a plugin. (`emit_python_callback`, jax's other
  allowlisted entry point, is answered for metal by the loader since 0.12.0,
  so `pure_callback`/`io_callback`/`debug.*`/checkify run jax's own
  lowering rules and hand the callback what CPU does: CPU `jax.Array`s,
  an empty mesh, jax's result checks. That needs the CPU backend listed,
  e.g. `JAX_PLATFORMS=metal,cpu`; with metal alone `pure_callback`,
  `io_callback` and `debug.*` raise jax's own "failed to find a local CPU
  device" error, as on any accelerator (checkify's runtime check needs no
  CPU device and runs). Divergences: an AOT `Compiled` object called from
  its own callback runs re-entrantly on CPU and raises on metal. And, from
  jax's cache key rather than the plugin: a jit calling itself from its own
  callback computes when the outer call runs under `default_device(metal)`
  (the inner call, under the callback's `default_device(cpu)`, is a second
  executable, as on any accelerator), while with the outer call under
  `default_device(cpu)` jax raises "Recursively calling jit".)
- *`testSincInfinities`, FD-reference gradient corners*: fail on the
  CPU backend too, or the test's finite-difference reference is
  numerically meaningless in f32 (documented with numbers).
- *Better-than-reference cases*: shape-polymorphic `jnp.insert` /
  `jnp.nonzero` — the harness asserts `NotImplementedError` because
  jax's CPU path cannot lower them; ours can, and values match CPU on
  concrete shapes. We fail these tests by succeeding.
- *`test_dce_sink_prevents_xla_dce`*: needs optimized-HLO text
  retrieval (`PJRT_Executable_OptimizedProgram`), a debugging surface
  we have not implemented.

**Supported** (each verified against the CPU backend): sorting
(`sort`/`argsort`/`top_k`/`approx_top_k`/`median`/`percentile`/
`unique`, key-value and **multi-key lexicographic** sorts —
`jnp.lexsort`, `unique(axis=)`, set operations — IEEE total-order NaN
handling, complex lexicographic order); convolutions (1/2/3-D float,
integer — exact, and complex; strided, dilated, grouped, transposed,
and their gradients); the full scatter family (windowed,
out-of-bounds-dropping, arbitrary elementwise bodies); general
`reduce`/`reduce_window` bodies and pooling with gradients
(`select_and_scatter`, `select_and_gather_add`); complex64 end-to-end
(arithmetic, FFT, linalg); linear algebra via LAPACK semantics on the
host (QR, eigh, eig, SVD, LU, Cholesky, triangular_solve, Schur,
Hessenberg — CPU-bound in every backend, free on unified memory; since
jax 0.11.2, jax refuses bfloat16/float16 inputs to these at trace time on
every backend); single-device `pmap`/`shard_map` with the full collective set;
`rng_bit_generator` (Philox and ThreeFry, **bit-exact vs CPU**, so the
`rbg`/`unsafe_rbg` PRNG implementations work); int4/uint4 and all
float8 dtypes (emulated: exact values in wider storage, grid-quantized
converts, 4-bit wraparound); host callbacks (`jax.debug.print`,
`pure_callback`, `io_callback`, checkify — the callback sees what it sees
on CPU, CPU `jax.Array`s it may keep); shape-polymorphic `jax.export` of
all of the above except the callbacks (which `jax.export` refuses on
every backend); `popcnt`/`count_leading_zeros`; sparse (BCOO/BCSR)
workloads.

Unsupported constructs fail loudly at compile time with the op named —
nothing silently falls back to CPU or returns wrong dtypes.

## Using metaljax from another project

Add `metaljax` to your dependencies (it declares `jax` itself; the bound
below keeps you on the jax 0.12.0 line, and admits metaljax's own
releases on it, 0.12.0.1 and later):

```toml
[project]
dependencies = ["metaljax>=0.12.0,<0.12.1"]
```

and set `JAX_PLATFORMS=metal,cpu` (or
`jax.config.update("jax_platforms", "metal,cpu")` before first use):
metal is the default device, and host callbacks have the CPU device jax
places their arguments on. `JAX_PLATFORMS=metal` alone works for
everything else, but there host callbacks (`jax.debug.print`,
`jax.debug.callback`, `pure_callback`, `io_callback`) raise jax's own
"failed to find a local CPU device" error, as they do on any accelerator
listed without cpu. (checkify's runtime errors place nothing on a device,
so they work either way.)

To develop against a local checkout instead, use a path source:

```toml
[tool.uv.sources]
metaljax = { path = "../metaljax", editable = true }
```

(with an editable install, build the plugin once in the checkout — see
*Developing from source* above).

## Environment variables

The knobs worth knowing. More flags, including the recognizer A/B
switches and the debug-only ones, are described with their categories in
[`notes/env-flags.md`](notes/env-flags.md) (that list predates 0.12.0 and
is not complete).

| Variable | Default | Meaning |
|---|---|---|
| `JAX_PLATFORMS` | *(unset)* | Set to `metal,cpu` (or `metal`) to select the backend; unset keeps CPU default. Host callbacks need `cpu` listed. |
| `METALJAX_PLUGIN_PATH` | *(auto)* | Override the path to `libmetal_pjrt_native.dylib` — how a measurement pins one specific build. |
| `METALJAX_MATMUL_PRECISION` | `high` | Which MLX kernels the M5's GEMM / attention / quantized matmul may use. `high`: f32 stays off the neural accelerators (exact, ~1e-6 vs f64) while bf16/f16 and quantized matmuls use them. `highest`: the pre-accelerator arch pin, no accelerator kernels for any dtype. `default`: MLX's own default (accelerator f32, ~8e-4). |
| `METALJAX_MEM_GOVERNOR` | `1` | The memory governor: under host-memory pressure the plugin paces ingest, sweeps the page cache and trims its buffer pool rather than letting the machine wire itself to death, and raises a clean `RESOURCE_EXHAUSTED` if that is not enough. `0` disables it. |
| `METALJAX_MEM_BUDGET_MB` | ¾ of RAM | The governor's hard line on **this process's** footprint; past it a transfer or a program is refused. |
| `METALJAX_MEM_SYS_MB` | ¾ of RAM | The governor's hard line on the **machine's** unreclaimable memory (wired + anonymous + compressor). Big checkpoint restores may need this raised (see *Known limitations*). |
| `METALJAX_MEM_FREE_FLOOR_MB` | 1/16 of RAM | The soft line: the free list below which a load is paced and the page cache swept. |
| `METALJAX_MEM_FREE_SYSCTLS` | *(unset)* | Comma-separated sysctl names that replace the governor's built-in list of free-page counters (`vm.page_free_count` alone through macOS 26; from macOS 27 also the per-CPU free queues and, on chips with memory tagging, the free tag-storage counters). For a kernel that splits its free count differently. |
| `METALJAX_STAGE_POOL_MB` | `4096` | How much the host-transfer staging pool may keep of blocks whose arrays have died, for reuse by the next transfer. `0` turns the pool off (staging from malloc, as before 0.12.0). |
| `METALJAX_COMPILE_BYTES_MB` | `65536` | Memory ceiling on a single fused trace (the op-count budget is `METALJAX_TRACE_BUDGET`). Over it, the program / while body / unrolled loop / chunked replay runs op by op instead. `0` disables the gate. |
| `METALJAX_TRACE_BUDGET` | `20000` | Max ops in one fused trace. |
| `METALJAX_EAGER_FLUSH_MB` | `1024` | Safety net for programs that run op by op: after this much estimated result data with no sync point, the engine settles what is live so the pending graph stays bounded. `0` disables it. |
| `METALJAX_INGEST_CLEAR_MB` | `8192` | Reclamation cadence of the host→device transfer path, in megabytes ingested — a model load reaches no other sync point. `0` disables it. |
| `METALJAX_CHUNK_MAX` | `16` | Max loop iterations replayed per compiled chunk. |
| `METALJAX_LOOP_INFLIGHT_MB` | `1024` | How many bytes of submitted-but-unfinished loop iterations may be in flight before the host waits for the oldest. Bounds the memory of training loops whose host side runs ahead of the GPU; `0` restores the op-count cadence alone. |
| `METALJAX_LOOP_SPECIALIZE` | `1` | Compile a counted loop's body once per chunk with the loop position folded into its dynamic slice starts (bit-identical, fewer dispatches). `0` replays one generic body. |
| `METALJAX_PROJ_PACK` | `auto` | Sibling decode projections over one activation packed into one dot over concatenated weights (`_MB` caps the device memory the packs may hold). `0` declines every group, `all` packs every eligible member. |
| `METALJAX_STACKED_PACK` | `auto` | The same for stacked per-layer dots reading one activation: one `gather_mm` over their concatenated views (`METALJAX_STACKED_RELAYOUT_MB` caps it). `0` declines, `all` packs everything. |
| `METALJAX_QMM_SCALES` | `auto` | Width of a quantized matmul's repacked scale/bias tables. `auto` keeps the model's own width when the folded bias is exactly representable and widens to f32 otherwise; `source` always keeps the narrow width; `f32` never narrows. |
| `METALJAX_QMM` / `_SDPA` / `_MOE` / `_ROPE_VIEW` / `_KV_INPLACE` / `_RECOGNIZE` | `1` | Recognizer switches: `0` runs the literal graph instead of the fused form (`_RECOGNIZE=0` turns off all of them). Diagnostic A/B arms — the fused forms are the measured path. |
| `METALJAX_DEBUG` | *(unset)* | `1` narrates every compile, loop, pack and recognizer decision on stderr. |

## Repository layout

```
CLAUDE.md                  project decisions/status (kept current)
models.md                  the 21-row model ledger (per-release columns)
STATUS.md                  current model cells + cross-framework comparators
PROGRESS.md                test counts + performance per release and alpha
pyproject.toml             python package + jax_plugins entry point
plugin-native/             THE ENGINE (bazel workspace)
  metal/                   the PJRT plugin: xla::PjRtClient, StableHLO
                           ingest, lowering, the recognizers and packs
  runtime/                 the executor: op emitters, MSL kernel codegen,
                           control flow, host LAPACK, memory governor
  third_party/mlx/         our vendored MLX, linked privately
  execute_test.py          differential suite vs jax-CPU
  texmo_gate.py            whole-model training gate vs jax-CPU
src/jax_plugins/metal/     backend registration (priority -1) + the
                           host-callback registry the plugin calls into
src/metaljax/              __version__, and lib/ where the plugin dylib
                           and the vendored MLX runtime land
tests/                     pytest suite (Metal vs CPU, through PJRT)
notes/                     investigation notes, env-flags, gate records
scripts/                   benchmark, gate & release drivers
  model_bench/             the 21-row model battery + its manifest
  vendor_mlx.sh            build + stage the vendored MLX runtime
  build_native_wheel.sh    build + verify the release wheel
```

## Benchmarks

### Real models

Twenty models through unmodified JAX code, all measured 2026-11-26 by the
release gate on this release's binary (`frozen-0120rc2-07ccf7b6`, jax
0.12.0.1, macOS 27.2.1, M5 Max with 128 GiB), one GPU process at a time
with a cool-down between rows. The 0.11.9 column is that release's gate
(2026-09-27/28, jax 0.11.2, the MaxText rows 10, 14, 15 and 19 on jax
0.11.0, macOS 26.6.2). Every cell was timed through `np.asarray`
(`jax.block_until_ready` is a no-op on this backend). **goal** is the best
non-metaljax cell for that row at the **same precision and workload** —
same checkpoint, prompt window, generated token count, batch, resolution
and encoder set; custom kernels are fair game, different quantization is
not. The goal cells come from earlier runs; this gate did not re-measure
them. Provenance, per-row protocols, memory footprints, jax-CPU cells and
every caveat live in [`STATUS.md`](STATUS.md) and [`models.md`](models.md).

Metric: LLM rows = warm decode ms/token; vision = forward ms; diffusion =
ms/diffusion-step; training = ms/step. Lower is better; ratio < 1 means
metaljax is ahead.

| # | model | metric | **metaljax 0.12.0** | 0.11.9 | goal (framework) | ratio |
|---|---|---|---:|---:|---:|---:|
| 1 | gemma4-31B bf16 | ms/tok | **126.3** | 123.2 | 111.2 llama.cpp | 1.14× |
| 2 | gemma4-12B bf16 | ms/tok | **57.9** | 58.1 | 44.2 llama.cpp | 1.31× |
| 3 | gemma4-26B-A4B bf16 (MoE) | ms/tok | **31.5** | 31.2 | 16.9 llama.cpp | 1.86× |
| 4 | gemma4-E2B bf16 | ms/tok | **16.9** | 16.9 | 10.5 mlx-lm | 1.61× |
| 5 | Qwen3-8B bf16 | ms/tok | **36.1** | 36.2 | 29.6 llama.cpp | 1.22× |
| 6 | Llama-3.1-8B bf16 | ms/tok | **34.5** | 39.2 | 29.2 llama.cpp | 1.18× |
| 7 | gpt-oss-20b (native MXFP4) | ms/tok | **13.0** | 13.2 | 8.8 mlx-lm | 1.48× |
| 8 | Qwen3.6-35B-A3B (MoE) | ms/tok | **21.2** ¹ | 23.5 | 13.7 mlx-lm | 1.55× |
| 9 | R1-Distill-32B bf16 | ms/tok | **204.0** | 198.3 | 114.9 llama.cpp | 1.78× |
| 10 | DeepSeek-V2-Lite (maxtext) | ms/tok | **42.3** ² | 20.3 | 10.5 mlx-lm | 4.03× |
| 11 | Qwen3-0.6B (keras-hub) | ms/tok | **5.1** | 5.1 | 3.2 mlx-lm | 1.59× |
| 12 | Mixtral 8×7B bf16 | ms/tok | **69.2** | 70.5 | 53.5 mlx-lm | 1.29× |
| 13 | gemma4-E2B keras-int4 | ms/tok | **5.8** | 6.0 | 4.5 mlx-lm 4-bit | 1.29× |
| 14 | Qwen3-0.6B qwix-int8 | ms/tok | **25.6** | 26.3 | — | — |
| 15 | Qwen3-8B qwix-int8 | ms/tok | **266.0** ¹ | 265.5 | — | — |
| 16 | SigLIP 2 (b1 forward) | ms | **36.8** | 41.7 | 29.8 torch-MPS | 1.23× |
| 17 | SD 3.5 Large @512² | ms/step | **454.4** | 457.2 | 553 torch-MPS | **0.82×** |
| 17 | SD 3.5 Large @1024² | ms/step | **2089** | 2103 | 3078 torch-MPS | **0.68×** |
| 18 | LoRA gemma4-E2B train | ms/step | **116.5** | 115.1 | 135.6 torch-MPS | **0.86×** |
| 19 | Qwen3-0.6B maxtext train | ms/step | **369.5** | 362.6 | 818 torch-MPS | **0.45×** |
| 21 | Qwen3.8-27B bf16 | ms/tok | **141.9** ¹ | 142.6 | 98.2 llama.cpp | 1.45× |

¹ The second run of the row in the gate. Its first run, the first with
the new plugin binary, read slower: row 8 24.6, row 15 347.0, row 21
154.4 ms/token (see *Known costs in 0.12.0*).
² The first of the row's two complete runs in the gate; the second read
40.8 ms/token. Unlike rows 8, 15 and 21, this row showed no slow first
run in the first release candidate's gate, so the first, less favourable
reading stands. This release decodes row 10 about 2× slower than 0.11.9
did; the cause and the coming fix are under *Known costs in 0.12.0*.

Reading the table: metaljax is ahead of PyTorch-MPS on every training and
diffusion row, and behind the dedicated Metal inference stacks on decode —
mlx-lm runs on the same Metal library underneath, so that band is the
optimization target, and llama.cpp's hand-written kernels lead even
mlx-lm on bf16. Rows without a goal cell have no like-for-like
non-metaljax implementation (rows 14/15 are qwix-quantized JAX models).
Several rows do not run on the JAX CPU backend at all at these sizes;
where they do, the CPU cells (jax 0.12.0.1's, from the same gate) are in
`STATUS.md` (e.g. row 19: 2001 vs 369.5 ms/step, row 16: 341.1 vs 36.8 ms,
row 2: 313.8 (CPU in f32) vs 57.9 ms/token).
Row 20 (Qwen3-235B-A22B 3-bit, 45.2 ms/tok at 0.11.8) left the suite at
0.11.9: it needs ~104 GB of a 128 GB machine, more than a desktop session
leaves free (`STATUS.md` fn 21).

Correctness for these rows is gated the same night: greedy token streams
are compared against the jax-CPU backend, and every divergence is
accounted for (at the 0.12.0 gate: gemma4-E2B parts from CPU at token
51, as at 0.11.9's gate, where that divergence was certified benign as a
1-bf16-ULP logit tie of the accepted accumulation-order class; the other
five CPU-comparable rows agree exactly over 64 tokens).

### Training and recurrent workloads

The acceptance workload, texmo, is a 106-config language-model training suite
(dense, GRU/LSTM-family and linear-RNN cells, from tens of weights to
several million) plus a 223-config performance sweep. At the 0.12.0
release (jax 0.12.0.1; every release's and alpha's results are in
[`PROGRESS.md`](PROGRESS.md)):
**106/106 correct** — one jitted training chunk per config executed on
both backends from identical inputs, every output leaf compared against
jax-CPU at a 1-ULP sensitivity-scaled tolerance — and the perf sweep is
**1.18× faster** than the standing anchor over 223 matched configs (141
configs improved >5 %, one regressed >5 %) and 1.03× faster than
0.11.9's release sweep.

How it gets there: pure programs and counted-loop (`scan`/`fori_loop`)
bodies are traced once into a fused Metal graph and replayed; small
statically-counted loops are unrolled into the enclosing trace, so a whole
recurrent-model training step (forward scan + backward + AdamW) becomes a
single graph replay. On top of that, recurrent scan bodies that
pattern-match as elementwise/matvec cells (rnn/gru/mgru/lrnn/rglru family
— forward *and* the AD-generated backward loop) compile to a single
generated persistent Metal kernel: the whole scan is one kernel launch,
with state in registers (small cells), register-block lanes (small block
matvecs, in-lane reductions and narrow rectangular readouts), or one
threadgroup per batch element with the feature dim as the thread axis
(full-width cells like `gru.256`, including rectangular fused-gate dots).
Very wide cells (`gru.1024`-class) deliberately stay on the compiled-graph
path, where batched matmul wins. Weight-gradient accumulations are handled
by loop fission: the kernel stacks per-step operands and the einsum runs
as one batched matmul after it.

### openxla/xla benchmark suite

The single-device benchmarks from
[xla/tools/benchmarks](https://github.com/openxla/xla/tree/main/xla/tools/benchmarks)
(HLO converted to StableHLO with `xla-translate`, run via
`scripts/run_stablehlo_bench.py`; ms per call, identical seeded inputs,
outputs cross-checked against the CPU results). **These cells were
measured on the 0.11.6 binary and have not been re-run since** — they are
kept for the cross-device comparison, not as current-release numbers:

| benchmark | jax CPU (M5 Max) | metaljax (0.11.6) | RTX 4090 |
|---|---:|---:|---:|
| gemma3_1b_flax_call | 84.6 | 35.3² | 4.0 |
| gemma3_4b_flax_call | 586.5 | 68.8² | 11.2 |
| gemma3_12b_flax_call | 2178.3 | 153.1² | —¹ |
| gemma2_2b_keras_jax | 156.9³ | 2.7³ | 10.9 |
| gemma4_2b_bf16 | 505.8³ | 2.8³ | 2.5 |
| maxtext 2.5B train step | 101066 | 11606⁴ | —¹ |

¹ exceeds the 4090's 24 GB VRAM; the M5's 128 GB unified memory runs
gemma3_12b (23.5 GB of bf16 weights) where the discrete GPU cannot.
² the imported modules contain one plain `stablehlo.dot` (the logits
matmul), which the native plugin declines by design (jax never emits
it); measured with that one op rewritten to the equivalent
`dot_general`, validated end-to-end against CPU references from the
pristine modules.
³ VACUOUS under the suite's seeded inputs: both are generate-loop
programs whose while-loop runs zero iterations, so no forward pass
executes on any backend — the cells measure loop-condition + state-copy
overhead only. Kept for completeness.
⁴ compiled whole-graph; ~9× CPU.

Correctness vs CPU on identical inputs: the gemma3 family diverges
≤3.8 % in bf16 KV-cache tensors (a few bf16 ULPs across 26+ layers) —
the 4090 shows the same divergence class vs CPU (≤4.2 %), so that's
cross-backend bf16 numerics, not a backend bug. maxtext NaN placement
matches CPU exactly on all 11 NaN-carrying outputs.

## Known limitations

Three platform constraints are permanent (detailed under *Coverage and
known gaps* above): no float64 or complex128 (programs that use them
fail at compile time), one physical device
(single-device `pmap`/`shard_map`/collectives work; real multi-device
sharding has no hardware), and denormals flushing to zero on the GPU.

Performance and operational, not correctness:

- **Decode trails the dedicated Metal inference stacks** by 1.1–1.9× on
  the model table above (row 10 by 4.0× in this release, see *Known costs
  in 0.12.0*); **prefill and model load trail by more** (about 5× and
  20–30× when last measured, 2026-08; not re-measured for 0.12.0). Decode
  is the optimized path.
- **The memory governor can refuse work that would still fit.** It is
  there so that a program that outgrows the machine gets a clean
  `RESOURCE_EXHAUSTED` instead of freezing macOS: as memory runs short it
  paces host → device transfers, drops the page cache a load leaves
  behind and trims the plugin's buffer caches, then waits up to 5 s at a
  hard line, and refuses only if that is not enough. Its hard lines are ¾
  of RAM for this process's footprint (`METALJAX_MEM_BUDGET_MB`) and ¾ of
  RAM for everything the machine has claimed, wired, anonymous and
  compressed, whoever holds it (`METALJAX_MEM_SYS_MB`).
  Because the second line counts other applications, memory that could
  still be paged out, and the freed blocks the system allocator keeps
  cached (next item), the governor can refuse a load that would have
  fitted, or that would merely have run slowly: in a synthetic test on
  macOS 27.2.1 it refused at 57 GiB of live GPU buffers with 24 GiB
  free, 25 GiB of the memory it counted being the allocator's stale
  cache. Raise the two lines, or set `METALJAX_MEM_GOVERNOR=0` to turn
  the governor off (and lose its protection). Large checkpoint restores
  can need the machine line raised: row 10 (DeepSeek-V2-Lite) runs at
  `METALJAX_MEM_SYS_MB=107520` on a 128 GB machine; under the default the
  governor refuses it cleanly and the run does not start.
  `METALJAX_MEM_FREE_SYSCTLS` replaces the kernel counters it reads for
  free memory (see *What's new in 0.12.0*). The memory management is
  being reworked to refuse as rarely as possible. Details:
  [`notes/no-panic-governor.md`](notes/no-panic-governor.md).
- **macOS's allocator keeps the large blocks a model loader frees.** A
  checkpoint loader typically reads each tensor into a host array,
  converts it, hands it to `jax.device_put` and drops it. macOS's
  allocator caches freed large blocks inside the process, where they
  count as the process's memory, for the system and for the governor. On
  macOS 26.6.2 they stayed while the model decoded (46–47 GiB on the
  MaxText rows 10 and 15); on macOS 27.2.1 the system takes them back by
  itself, in three batches about 13–18, 25–30 and 37–42 s after the free
  (46 GiB in a synthetic test). Setting `MallocLargeCache=0` in the
  environment when the process starts turns that cache off. Measured on
  macOS 26.6.2: row 15 then held 18 GiB after its load (its parameters
  are 15.3 GiB) instead of 62–64 GiB, and peaked at 50–52 instead of
  74–76 GiB; row 10 held 30–31 GiB instead of 77–78 while it decoded, and
  peaked at 78 instead of 93 GiB. Not measured on macOS 27.
- **macOS 27.2.1 froze twice in our synthetic tests right after a process
  freed tens of GiB of large malloc blocks at once.** In about 32 runs
  that freed 46 GiB of 1 GiB blocks, the machine stopped responding twice
  and restarted on a kernel watchdog panic: once about 13 s after the
  free, in a run that then filled GPU buffers through the plugin with the
  memory governor off, and once at the free itself, in plain Python and
  NumPy with no GPU and no plugin. 18–66 GiB of memory were free at the
  time, so neither was an out-of-memory. Model loaders free host memory
  in this way; the release gate's big model rows, whose loaders free tens
  of GiB, did not meet it. Whether `MallocLargeCache=0` avoids it is not
  known.
- **A big quantized model pays a one-time pack wave.** Row 20
  (Qwen3-235B-A22B 3-bit), last run at 0.11.8, spent ~58 minutes packing
  quantized weights at a ~103 GB peak before steady decode (45.2 ms/token
  at the 0.11.8 gate). The pack is once per process, not per step.
- **keras-hub's Gemma4 int4/int8 quantization is broken upstream** (still
  present as of 2026-09-19): the decoder block's "HOTFIX" multiplies by
  unscaled codes, producing a numerically broken model on *every*
  backend. Our benchmark harness works around it
  (`scripts/model_bench/int4_fix.py`); a user's own quantized Gemma4 will
  be wrong until keras-hub fixes it.
- **Scan bodies that don't fit the kernel-codegen patterns** (gather/
  scatter in the loop, non-affine indexing, bodies exceeding the trace or
  binding budgets) fall back to per-timestep compiled-graph replay, which
  pays per-step dispatch.
- **Buffer donation is honoured** (`donate_argnums` invalidates the
  donated inputs, matching other backends), but MLX cannot write outputs
  into the donated memory in place — the win is prompt buffer release
  rather than CUDA-style aliasing.

## License / provenance

Experimental personal project; builds against public JAX/OpenXLA (PJRT
header vendored from openxla/xla) and Apple's MLX. Apache-2.0.
