Skip to content

perf(models): fused single-launch xIELU Metal kernel for Apertus - #414

Merged
inureyes merged 2 commits into
mainfrom
perf/issue-409-fused-xielu
Jun 24, 2026
Merged

inureyes merged 2 commits into
mainfrom
perf/issue-409-fused-xielu

Conversation

@inureyes

@inureyes inureyes commented Jun 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Fuse the Apertus xIELU activation into a single Metal kernel (fused_xielu) to cut the per-token launch/epilogue overhead of the ~11-op elementwise apertus_xielu graph. On the Apertus-8B decode path the elementwise activation is about 352 tiny dispatches per token (11 ops x 32 layers) over the same small MLP intermediate buffer. This is the one remaining meaningful Apertus decode lever flagged as a follow-up by #269 (PR #399); the bulk of the original #269 gap was already recovered by #290, leaving Apertus near parity.

The result is byte-identical to the elementwise path and a repeatable +2.7% decode improvement on M1 Ultra, so it carries no parity cost.

What changed

src/lib/mlxcel-core/cpp/mlx_cxx_kernels.cpp: new fused_xielu plus its xielu_fused Metal kernel. Every intermediate is held in the input dtype (bf16 for the native Apertus path) and each sub-expression is one arithmetic op per statement, so the kernel rounds exactly where the elementwise reference rounds (one MLX op == one round) and the Metal compiler cannot contract a multiply and add into a single FMA. Metal's JIT metal_math has no expm1 and the metal_kernel preamble does not include MLX's expm1f.h, so the kernel header reproduces MLX's expm1f verbatim to match mlx::core::expm1 bit-for-bit. Non-Metal back-ends use an equivalent elementwise fallback, so the path is safe everywhere.

src/lib/mlxcel-core/cpp/mlx_cxx_bridge.h and src/lib/mlxcel-core/src/lib.rs: declare the fused_xielu FFI entry.

src/models/apertus.rs: route MLP::forward through mlxcel_core::fused_xielu when MLXCEL_FUSED_XIELU is set (read once, cached in a OnceLock, default-off), mirroring the fused decode-MoE rollout in #268. Adds the fused_xielu_matches_elementwise_bit_for_bit unit test asserting bit-for-bit equality across the full activation domain.

NOTICE: attribute MLX's expm1f device routine (Apple, MIT) and the embedded Norbert Juffa BSD-2-Clause routine it carries.

docs/environment-variables.md: document MLXCEL_FUSED_XIELU in the hardware and kernel diagnostic table alongside the other fused-kernel flags (MLXCEL_FUSED_MOE, MLXCEL_FUSED_QK_NORM).

Before/after (validation)

Decode, Apple M1 Ultra, models/apertus-8b-instruct-2509-4bit, interleaved A/B (each pair flag-off then flag-on back-to-back to control thermal drift), best-of-3, --temp 0 --no-chat-template, 100 tokens:

pair flag off (tok/s) flag on (tok/s)
1 83.25 85.70
2 83.44 85.61
3 83.80 86.08

Median 83.44 -> 85.70 tok/s, a repeatable +2.7% (all three pairs agree, ~2.2-2.3 tok/s, no overlap). This is in the range of the prior AsType reduction campaign (about +2.6%) but achieved with one clean kernel and zero parity cost.

Parity (byte-identical)

Greedy temp-0 decode is byte-identical between the elementwise and fused paths:

  • Prompt "The history of the Roman Empire began" (n=50): diff empty (byte-identical).
  • Prompt "In 1969, the Apollo program" (n=60): diff empty (byte-identical).
  • cargo test --release -p mlxcel apertus: fused_xielu_matches_elementwise_bit_for_bit passes (bit-for-bit over positive, the x>0 boundary, near-zero negatives straddling eps, and large negatives that saturate expm1), and the existing flag-off apertus_greedy_parity_matches_mlx_lm is unchanged.

Bit-for-bit (rather than jitter-class) required keeping every intermediate in bf16 with one op per statement, and reproducing MLX's exact expm1f. A first prototype using a single fused float expression and exp(c)-1 was only jitter-class (near-tie token flips), which the per-op rounding and exact expm1f eliminated.

No regression

  • The kernel is Apertus-only; with the flag off the Apertus MLP path is unchanged.
  • The change to mlx_cxx_kernels.cpp is purely additive; the BitNet (bitlinear_matmul) and fused-MoE kernels in the same translation unit were re-smoke-tested and produce correct output.
  • cargo fmt -p mlxcel -p mlxcel-core --check clean.

Default state and recommendation

Shipped default-off, matching the fused decode-MoE rollout (#268). Because the path is byte-identical, Apertus-only, and falls back cleanly on non-Metal back-ends, the risk of enabling it by default is essentially zero. Recommendation: enable MLXCEL_FUSED_XIELU by default for Apertus. Left default-off here so the default-on flip is an explicit maintainer decision, consistent with #268. MLXCEL_FUSED_XIELU is documented in docs/environment-variables.md (hardware and kernel diagnostic table).

Test plan

  • cargo build --release --features metal,accelerate --bin mlxcel --bin mlxcel-bench-decode
  • cargo test --release -p mlxcel apertus (fused parity unit test + existing greedy parity)
  • Greedy temp-0 byte-identical decode on two prompts (elementwise vs fused)
  • Interleaved A/B decode bench, best-of-3 (flag off vs on)
  • BitNet and fused-MoE smoke tests (same translation unit)
  • cargo fmt -p mlxcel -p mlxcel-core --check

Closes #409

apertus_xielu issues ~11 elementwise MLX ops (square, multiply_scalar, full, minimum, expm1, subtract, where, add, ...) per layer per token. On the Apertus-8B decode path that is ~352 tiny dispatches per token (11 ops x 32 layers), all over the same small MLP intermediate buffer.

Add a fused Metal kernel `fused_xielu` (mlx_cxx_kernels.cpp, wired through the cxx bridge header and lib.rs) that computes the whole xIELU activation in one launch, gated by MLXCEL_FUSED_XIELU (default-off, single read cached in a OnceLock) on the Apertus MLP forward, mirroring the fused decode-MoE rollout (#268). The kernel keeps every intermediate in the input dtype (bf16 for the native Apertus path) and uses one arithmetic op per statement, so each sub-expression rounds exactly where the elementwise reference rounds (one MLX op == one round) and the Metal compiler cannot contract a multiply and add into a single FMA. Metal's JIT metal_math has no expm1 and the metal_kernel preamble does not pull in MLX's expm1f.h, so the kernel header reproduces MLX's expm1f verbatim (Norbert Juffa's BSD-2-Clause routine carried in MLX, attributed in NOTICE) to match mlx::core::expm1 bit-for-bit. Non-Metal back-ends fall back to an equivalent elementwise graph, so the flag is safe everywhere.

Parity: greedy temp-0 decode is byte-identical between the elementwise and fused paths on two prompts, and a new unit test (fused_xielu_matches_elementwise_bit_for_bit) asserts bit-for-bit equality across the full activation domain (positive, the x>0 boundary, near-zero negatives straddling eps, large negatives that saturate expm1).

Decode (Apple M1 Ultra, apertus-8b-instruct-2509-4bit, interleaved A/B, best-of-3, temp 0, --no-chat-template, 100 tokens): flag off 83.25/83.44/83.80 tok/s vs flag on 85.70/85.61/86.08 tok/s, a repeatable +2.7% with no parity cost. The kernel is Apertus-only; other models and the flag-off Apertus path are unchanged, and the BitNet and fused-MoE kernels in the same translation unit were re-smoke-tested.
@inureyes inureyes added type:performance Performance improvements area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:macos macOS (Apple Silicon) specific priority:low Low priority status:review Under review labels Jun 24, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Fuse Apertus xIELU into a single Metal kernel (fused_xielu) behind default-off MLXCEL_FUSED_XIELU, byte-identical to the elementwise apertus_xielu, for a repeatable +2.7% decode win. Closes #409.

Verification

1. Parity (byte-identical claim) — confirmed.

  • The xielu_fused kernel computes the same formula and operation order as apertus_xielu: pos = alpha_p*x^2, neg = (expm1(min(x,eps)) - x)*alpha_n, where(x>0, pos, neg) + beta*x (the shared beta*x factored outside the select, matching the reference). Both branches are evaluated for every element in both paths.
  • Every intermediate is held in the input dtype (bf16 for native Apertus), one arithmetic op per statement, so each sub-expression rounds where the elementwise reference rounds and the compiler cannot FMA-contract a mul+add. Scalars are materialized in-dtype in both paths (multiply_scalar -> full_f32(.., a_dtype) vs kernel (T)scalar), so rounding matches.
  • The inlined expm1f is a verbatim copy of MLX's mlx/backend/metal/kernels/expm1f.h (only metal:: qualifiers added). Checked against the pinned MLX copy in the build tree: all polynomial constants (1.97350979e-4f ... 4.99999970e-1f), the 1.442695f/12582912.f range reduction, and the j==0/j==1/a==0/abs(a-1)>88 branch cutoffs match. The reference mlx::core::expm1 on bf16 routes through this same AOT routine, so the negative branch matches bit-for-bit.
  • The unit test fused_xielu_matches_elementwise_bit_for_bit is meaningful: it spans a dense range plus the x>0 boundary, near-zero negatives straddling eps, and large negatives that saturate expm1. Inputs outside the tested range cannot diverge: the positive branch is a pure polynomial (identical ops), and the negative branch uses the verbatim expm1f, so large |x| is provably identical. (Only nan/inf could differ via min/where nan semantics, which is irrelevant to healthy bf16 decode.)

2. Flag gating — confirmed. fused_xielu_enabled() reads MLXCEL_FUSED_XIELU once into a OnceLock; default-off costs one atomic load per token and leaves the elementwise path byte-for-byte unchanged.

3. Non-Metal fallback — confirmed. xielu_elementwise mirrors apertus_xielu op-for-op with the scalar materialized in the array dtype, guarded by !metal::is_available() so CUDA-only / Metal-not-built backends take the equivalent elementwise graph. FFI signature (const MlxArray& -> std::unique_ptr<MlxArray>, scalars by value) is correct; the result is freshly owned, no lifetime/ownership hazard across cxx.

4. TU safety — confirmed. The change to mlx_cxx_kernels.cpp is a single additive insertion (+182/-0); the bitlinear_matmul and fused-MoE kernels in the same TU are untouched.

5. NOTICE / attribution — confirmed. The new NOTICE entry attributes MLX's expm1f (Apple, MIT) and carries the embedded Norbert Juffa BSD-2-Clause text verbatim; the kernel carries an inline derivation note (upstream repo URL, copyright holders, licenses, NOTICE pointer) at the reproduced routine, satisfying the repo's third-party attribution convention.

6. Conventions — confirmed. No shared function modified (no // Used by: update needed). No AI attribution and no em dashes in the diff or PR body. Closes #409 present.

Findings

  • All stated requirements implemented
  • No placeholder/mock code
  • Integrated into the Apertus MLP::forward code flow (gated)
  • Project conventions followed (metal::is_available() dispatch matches the existing bitlinear/fused-MoE/SSM kernels)
  • No unintended structural changes
  • Parity test meaningful and passing; real-model greedy decode byte-identical

Observations (no fix required)

  • LOW (out of scope): On a macOS Metal build, MLXCEL_DEVICE=cpu selects the CPU default device while metal::is_available() still returns true, so fused_xielu (with the flag on) would still dispatch the Metal kernel. This is the identical guard used by every other fused kernel (bitlinear_matmul, fused-MoE, SSM); it is a pre-existing project-wide pattern, not a regression introduced here, and the realistic non-Metal (CUDA-only) path is handled correctly. A dispatch-guard change, if wanted, belongs in a separate PR touching all kernels uniformly.

Add the MLXCEL_FUSED_XIELU entry to the hardware and kernel diagnostic
table alongside MLXCEL_FUSED_MOE and MLXCEL_FUSED_QK_NORM. Covers what
the flag does (routes Apertus MLP activation through the fused
single-launch Metal xIELU kernel), default (off, presence-based), scope
(Apertus only; non-Metal back-ends fall back to an equivalent elementwise
graph), byte-identical guarantee, and the measured +2.7% decode gain on
M1 Ultra.
@inureyes

Copy link
Copy Markdown
Member Author

PR finalization

One change added: docs/environment-variables.md now has a MLXCEL_FUSED_XIELU entry in the hardware and kernel diagnostic table, placed after MLXCEL_FUSED_QK_NORM alongside the other fused-kernel flags. The entry documents the flag's scope (Apertus only), default (off, presence-based), byte-identical guarantee, non-Metal fallback behavior, and the measured +2.7% decode gain on M1 Ultra.

The PR body was updated to reference the new doc entry in both the "What changed" section and the "Default state and recommendation" paragraph.

Checks:

  • No em dashes in any changed file or commit message (full diff scanned).
  • No AI attribution in any git output (commit, PR body, this comment).
  • No Rust files were touched, so no fmt or clippy run needed.
  • Test coverage: fused_xielu_matches_elementwise_bit_for_bit in apertus.rs covers the parity claim across a dense bf16 range and the edge cases; no gaps found.

Branch is pushed and clean.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 24, 2026
@inureyes
inureyes merged commit 5ef7df6 into main Jun 24, 2026
4 checks passed
@inureyes
inureyes deleted the perf/issue-409-fused-xielu branch June 24, 2026 00:54
inureyes added a commit that referenced this pull request Jun 24, 2026
…417)

Flip MLXCEL_FUSED_XIELU to default-on with `0`/`false`/`off`/`no` as the
case-insensitive opt-out, mirroring the MLXCEL_FUSED_MOE default-on
convention (#282). #409 (PR #414) shipped the fused single-launch Metal
xIELU kernel for the Apertus MLP activation default-off, explicitly
pending M5 Max validation; this completes that follow-up.

M5 Max (Apple M5 Max, 128GB), Apertus-8B-Instruct-2509-4bit,
mlxcel-bench-decode, 12 interleaved off/on rounds of 256-token greedy
decode:

  off (elementwise): 112.0 tok/s
  on  (fused):       114.2 tok/s
  delta: +1.9% mean (+2.05% median), 11/12 paired wins, paired t ~ 8.9

Greedy temp-0 decode is byte-identical between the two paths on M5 Max
(end-to-end sha256 match over a full generation, plus the committed
bit-for-bit unit test over the full activation domain). With the
documented M1 Ultra result (+2.7%), the fused path is a byte-identical,
positive-throughput, no-regression win on both validated Apple Silicon
generations.

Apertus-only; non-Metal back-ends keep the equivalent elementwise
fallback. Set MLXCEL_FUSED_XIELU=0 to force the elementwise path.

Adds fused_xielu_enabled_from() as a pure, unit-tested opt-out decision
and updates docs/environment-variables.md.
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…lup#414)

* perf(models): fused single-launch xIELU Metal kernel for Apertus

apertus_xielu issues ~11 elementwise MLX ops (square, multiply_scalar, full, minimum, expm1, subtract, where, add, ...) per layer per token. On the Apertus-8B decode path that is ~352 tiny dispatches per token (11 ops x 32 layers), all over the same small MLP intermediate buffer.

Add a fused Metal kernel `fused_xielu` (mlx_cxx_kernels.cpp, wired through the cxx bridge header and lib.rs) that computes the whole xIELU activation in one launch, gated by MLXCEL_FUSED_XIELU (default-off, single read cached in a OnceLock) on the Apertus MLP forward, mirroring the fused decode-MoE rollout (lablup#268). The kernel keeps every intermediate in the input dtype (bf16 for the native Apertus path) and uses one arithmetic op per statement, so each sub-expression rounds exactly where the elementwise reference rounds (one MLX op == one round) and the Metal compiler cannot contract a multiply and add into a single FMA. Metal's JIT metal_math has no expm1 and the metal_kernel preamble does not pull in MLX's expm1f.h, so the kernel header reproduces MLX's expm1f verbatim (Norbert Juffa's BSD-2-Clause routine carried in MLX, attributed in NOTICE) to match mlx::core::expm1 bit-for-bit. Non-Metal back-ends fall back to an equivalent elementwise graph, so the flag is safe everywhere.

Parity: greedy temp-0 decode is byte-identical between the elementwise and fused paths on two prompts, and a new unit test (fused_xielu_matches_elementwise_bit_for_bit) asserts bit-for-bit equality across the full activation domain (positive, the x>0 boundary, near-zero negatives straddling eps, large negatives that saturate expm1).

Decode (Apple M1 Ultra, apertus-8b-instruct-2509-4bit, interleaved A/B, best-of-3, temp 0, --no-chat-template, 100 tokens): flag off 83.25/83.44/83.80 tok/s vs flag on 85.70/85.61/86.08 tok/s, a repeatable +2.7% with no parity cost. The kernel is Apertus-only; other models and the flag-off Apertus path are unchanged, and the BitNet and fused-MoE kernels in the same translation unit were re-smoke-tested.

* docs: document MLXCEL_FUSED_XIELU in environment-variables.md

Add the MLXCEL_FUSED_XIELU entry to the hardware and kernel diagnostic
table alongside MLXCEL_FUSED_MOE and MLXCEL_FUSED_QK_NORM. Covers what
the flag does (routes Apertus MLP activation through the fused
single-launch Metal xIELU kernel), default (off, presence-based), scope
(Apertus only; non-Metal back-ends fall back to an equivalent elementwise
graph), byte-identical guarantee, and the measured +2.7% decode gain on
M1 Ultra.
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…ablup#417)

Flip MLXCEL_FUSED_XIELU to default-on with `0`/`false`/`off`/`no` as the
case-insensitive opt-out, mirroring the MLXCEL_FUSED_MOE default-on
convention (lablup#282). lablup#409 (PR lablup#414) shipped the fused single-launch Metal
xIELU kernel for the Apertus MLP activation default-off, explicitly
pending M5 Max validation; this completes that follow-up.

M5 Max (Apple M5 Max, 128GB), Apertus-8B-Instruct-2509-4bit,
mlxcel-bench-decode, 12 interleaved off/on rounds of 256-token greedy
decode:

  off (elementwise): 112.0 tok/s
  on  (fused):       114.2 tok/s
  delta: +1.9% mean (+2.05% median), 11/12 paired wins, paired t ~ 8.9

Greedy temp-0 decode is byte-identical between the two paths on M5 Max
(end-to-end sha256 match over a full generation, plus the committed
bit-for-bit unit test over the full activation domain). With the
documented M1 Ultra result (+2.7%), the fused path is a byte-identical,
positive-throughput, no-regression win on both validated Apple Silicon
generations.

Apertus-only; non-Metal back-ends keep the equivalent elementwise
fallback. Set MLXCEL_FUSED_XIELU=0 to force the elementwise path.

Adds fused_xielu_enabled_from() as a pure, unit-tested opt-out decision
and updates docs/environment-variables.md.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata platform:macos macOS (Apple Silicon) specific priority:low Low priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(models): fused/compiled xIELU activation for Apertus decode

1 participant