Skip to content

feat(core): add MLXCEL_METAL4_ATTENTION as a kill switch for the M5 NA route - #1196

Merged
inureyes merged 1 commit into
mainfrom
feat/issue-1065-metal4-attention-switch
Aug 17, 2026
Merged

inureyes merged 1 commit into
mainfrom
feat/issue-1065-metal4-attention-switch

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

MLXCEL_METAL4_ATTENTION=0 forces the M5 neural-accelerator fused attention route off on hardware that has it, so the ordinary SDPA path runs instead.

This is one of #1065's acceptance criteria, landed on its own because it is the criterion that unblocks the others: that issue's suggested investigation is "determine whether MLX selects a reduced-precision NAX kernel", and without a switch the only way to test it is to patch should_use_metal4_attention and rebuild. The M5 investigation on #1182 did exactly that, by hand, and reverted afterwards. The next person to need it will not know that happened.

Behaviour

Off-switch only. The hardware test still gates the route, so:

host variable route
NA-capable (has_neural_accelerator && macos_supports_na) unset on
NA-capable 0 / false / no / off off
not NA-capable anything, including unset off

A stray value on an M1 is inert rather than routing it into an M5 kernel. Read once per process, matching MLXCEL_GDN_CHAIN_PARITY, MLXCEL_SSM_CUDA_KERNEL and the other kill switches in this tree.

A drift the switch exposed

There were two copies of the hardware test. layers::should_use_metal4_attention had one, and lib.rs's causal-attention dispatch carried its own inline hw.has_neural_accelerator && hw.macos_supports_na before calling layers::metal4_causal_attention. Adding the switch to only the first would have disabled the route in one place and left it running in the other.

For a diagnostic whose entire value is a clean A/B, a half-applied switch is worse than no switch: it produces a run that looks like the route is off and is not, and the resulting "the NA route is not the cause" conclusion would be wrong and hard to catch. lib.rs now calls the shared predicate.

What this does not do

It does not diagnose #1065. It makes the diagnosis a one-command A/B instead of a patch-and-rebuild, on a machine this session does not have.

Test plan

Apple M1 Ultra 128 GB (no neural accelerator), macOS 26.6.1, branched from main at ffde948e.

  • cargo test -p mlxcel-core metal4_attention_switch: 1 passed. The test asserts the off-switch property that can be checked from any host: without the hardware the predicate is false regardless of the variable. On NA hardware it returns early rather than pinning an answer to one machine's ambient environment.
  • cargo clippy --workspace --all-targets --features metal,accelerate -- -D warnings: clean.
  • cargo fmt --check: clean.

Not verified: the switch's effect is unobservable on this host, because the route it disables never engages here. Confirming that MLXCEL_METAL4_ATTENTION=0 actually changes numerics needs an M5-class machine, which is the same machine #1065 needs anyway. Suggested check there: run the four tests #1065 names with and without the variable and report whether the failures move.

Refs #1065

@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:macos macOS (Apple Silicon) specific labels Aug 16, 2026
…A route

Issue #1065 asks for an environment override that disables the M5
neural-accelerator attention routing, so the hypothesis "this dispatch is
why the M5 disagrees numerically" can be tested by A/B rather than by
reading code. There was none, and the M5 investigation on #1182 had to
patch should_use_metal4_attention by hand and revert it afterwards. That
is how a diagnostic gets skipped on the next machine that needs it.

MLXCEL_METAL4_ATTENTION=0 now forces the route off. It is an off-switch
only: the hardware test still gates it, so the variable cannot route an
M1 into an M5 kernel and a stray value there is inert. Read once per
process, following the other MLXCEL_* kill switches.

Also unifies the two dispatch sites. lib.rs carried its own copy of
`hw.has_neural_accelerator && hw.macos_supports_na` rather than calling
the shared predicate, so the switch would have disabled the route in one
place and not the other. For a diagnostic whose whole value is a clean
A/B, a half-applied switch is worse than none.

Refs #1065
@inureyes
inureyes force-pushed the feat/issue-1065-metal4-attention-switch branch from f424291 to 365b9bc Compare August 17, 2026 01:55
@inureyes
inureyes merged commit 3395128 into main Aug 17, 2026
7 checks passed
@inureyes
inureyes deleted the feat/issue-1065-metal4-attention-switch branch August 17, 2026 01:57
@inureyes

Copy link
Copy Markdown
Member Author

The switch is in on an M5 Max (40 GPU cores, 128 GB, macOS 26.6.1, Xcode 26.5) and behaves correctly as a variable, but the test plan's open item is still open, and the obvious way to close it does not work.

The suggested check was to run the four tests #1065 names with and without the variable and report whether the failures move. Done, and they do not move: identical failures with MLXCEL_METAL4_ATTENTION unset, =1 and =0, byte-identical values in all three. Full cross including MLX_ENABLE_TF32 is on #1065.

That result says nothing about this switch, because those four tests never reach the route. It is consulted at lib.rs:3207, layers::metal4_attention and layers::metal4_causal_attention; the tests call attention_dispatch, chunked_causal_attention, chunked_query_attention, ffi_fast_scaled_dot_product_attention_causal and the MLA decode paths directly. Re-running test 1 with MLXCEL_LOG_NA_ATTENTION=all gives zero dispatch log lines with the switch on and zero with it off, which confirms it rather than inferring it.

So the "not verified" line in the test plan should stay, and the suggested check in it is worth amending: on this hardware it produces a clean-looking null result for the wrong reason. A real-checkpoint decode A/B, with MLXCEL_LOG_NA_ATTENTION used to prove the route actually engages in the on arm, is the check that can close it. Running that now and will report here.

Separately, this switch did its job for #1065 even though it turned out not to be the cause: the four-arm cross is what ruled the route out as a suspect, and before #1196 that would have needed a patch and a rebuild.

@inureyes

Copy link
Copy Markdown
Member Author

Verified on M5 Max: the switch works, and the route it disables is not costing anything measurable

Apple M5 Max, 40 GPU cores, 128 GB, macOS 26.6.1, Xcode 26.5, main at 33951285. Three real checkpoints.

The switch does what it says

MLXCEL_LOG_NA_ATTENTION=all, counting dispatch log lines over a 32-token generation:

checkpoint route on MLXCEL_METAL4_ATTENTION=0
llama-3.2-1b-4bit 528 0
gemma-3-4b-it-4bit 1122 0
qwen2.5-7b-instruct-4bit 924 0

The route engages on all three and the switch takes it to zero on all three. That closes the test plan's open item on this hardware, including the drift this PR fixed: a switch applied to only one of the two hardware tests would have left one of these non-zero.

Its effect, measured separately

96 tokens, --temp 0, arms alternated, two reps, no NA logging:

checkpoint on rep1 on rep2 off rep1 off rep2 generated text
llama-3.2-1b-4bit 519.44 522.69 523.26 521.16 identical
gemma-3-4b-it-4bit 177.41 178.37 178.08 178.97 identical
qwen2.5-7b-instruct-4bit 119.93 119.06 119.86 119.53 identical

Byte-identical output on all three, and throughput differences under 1% with the sign flipping between reps, so within noise. On these checkpoints the NA attention route neither changes what is generated nor pays for itself.

A trap worth writing down before someone hits it

My first pass measured route engagement and throughput in the same run and produced 360 tok/s with the route on against 577 with it off, a 60% gap that looks like a serious finding and is entirely an artifact: only the on arm emits log lines, 1820 of them, and MLXCEL_LOG_NA_ATTENTION=all costs roughly 40% of throughput by itself. The two measurements have to be separate runs. Discarded, and repeating it here so the number does not resurface as a quotable result.

A second one: qwen3-0.6b-4bit generates essentially empty output for a bare continuation prompt, so a byte-identity comparison on it passes without comparing anything. Checkpoints for this A/B need to be checked for non-empty output first.

Scope

This says the route is numerically invisible at temperature 0 for 96 tokens on three 4-bit checkpoints, which is a statement about argmax flips, not about per-op precision. It does not measure prefill-heavy or long-context shapes, and it does not touch #1065, whose cause turned out to be MLX_ENABLE_TF32. Details on that are in #1065 (comment).

@inureyes inureyes self-assigned this Aug 27, 2026
@inureyes inureyes added the status:done Completed label Sep 6, 2026
inureyes added a commit that referenced this pull request Oct 6, 2026
## Summary

#1065's title and "Hardware dependence" section are wrong: the failures are not M5-specific. The cause is MLX's default `MLX_ENABLE_TF32=1`, which runs f32 GEMMs with 10-bit mantissa inputs on CUDA Ampere+ (cuBLAS `CUBLAS_COMPUTE_32F_FAST_TF32`) and Apple GPU generation 17 (NAX). The M1 Ultra passed only because it has no TF32-class path. The main fix already landed: #1260 pins `MLX_ENABLE_TF32=0` in both lib test binaries, #1262/#1263 document it at the `verify-test-cuda` gate, #1196 added the attention kill switch (which does not affect these tests). This PR closes what remained:

- `mlxcel-core/src/tf32_pin_tests.rs`: an f32 GEMM (16x512x16, off MLX's gemv path) against an f64 host reference. Nothing in `mlxcel-core` went red on CUDA when the pin was lost, because the four tests #1065 named pass on CUDA even under TF32 (their shapes use gemv/SDPA, not cuBLAS).
- Ctor doc comments in `src/lib.rs` and `mlxcel-core/src/lib.rs` no longer say "Apple only".
- The two remaining chunked-SDPA assertions print the measured divergence (the two #1065 named already did).
- `docs/environment-variables.md`: new `MLX_ENABLE_TF32` row with the measured decode impact; the `MLXCEL_METAL4_ATTENTION` row no longer names the route as #1065's suspect.

Tolerances are unchanged. Shipped numerics stay on the MLX default, per the existing policy (unit tests verify full-f32 algorithm equivalence; TF32 output is not f32 evidence).

## Decision on production decode

GB10, greedy, 256 tokens, default vs `MLX_ENABLE_TF32=0`, arms alternated:

| checkpoint | weights | result |
|---|---|---|
| plamo-2-1b | f32 | 1 of 5 prompts diverges (after ~40 words), deterministic in both arms, 5/5 runs each; 38 tok/s both arms |
| llama-3.1-8b-bf16 | f16 | identical, 3 prompts x 2 runs |
| qwen2.5-0.5b-bf16 | bf16 | run-to-run variation in both arms alike, not attributable |
| qwen3-0.6b | 4-bit | run-to-run variation in both arms alike, not attributable |

TF32 changes greedy output only where dense f32 GEMMs exist, which in practice means f32 checkpoints. On CUDA, MLX sends unbiased single-row matmuls to a gemv kernel the setting does not reach, so prefill-sized GEMMs are the likely site; that split is read from MLX source, not measured. The default stays; the docs tell operators to set `MLX_ENABLE_TF32=0` for f32-exact output.

## Test plan

- [x] At origin/main `5211f58d`, CUDA, `--test-threads=1`: the 4 `mlxcel-core` tests from #1065 pass by default and under `MLX_ENABLE_TF32=1` (3 runs each). The 3 root-lib tests from the 2026-08-17 comment pass by default and fail 3/3 under `MLX_ENABLE_TF32=1` (deepseek_v2 2.70e-4, florence2 1.43e-4)
- [x] New sentinel: pass by default and with `=0`, fail 3/3 under `=1` (5.84e-3 vs 1e-4 bound)
- [x] After the change: `layers::tests::chunked_`, `mla::decode::decode_tests`, `tf32_pin_tests` all pass on CUDA
- [x] `cargo fmt --check`, `cargo clippy -p mlxcel-core --lib --tests --features cuda -- -D warnings`

## Not verified on this host

- The four tests on M5 Max, and the M1 Ultra nightly runner: no Metal hardware here. #1065's 2026-08-17 comment already showed all four pass on M5 under `MLX_ENABLE_TF32=0`, and #1260 reported the suite green on M5 with the pin.
- Sentinel failing under `MLX_ENABLE_TF32=1` on M5 (expected from the NAX dispatch, not run).
- M5 vs M1 decode quality on real checkpoints.

Closes #1065
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
Add an Anthropic Messages-compatible API surface to mlxcel-server so clients written against the Anthropic schema can use the server without a translation shim. Ported from upstream mlx-vlm `server/anthropic.py` (PR lablup#1196) plus the tool-result image-handling fix (PR lablup#1200).

New endpoints:

- `POST /v1/messages` (and `/messages` alias): create a message, synchronous or SSE streaming.
- `POST /v1/messages/count_tokens` (and `/messages/count_tokens` alias): prompt token count.

The request schema covers the Anthropic surface: top-level `system` (string or text-block array), `messages`, `max_tokens`, `stop_sequences`, `temperature`/`top_p`/`top_k`, function `tools` + `tool_choice`, and `thinking`. Content blocks support `text`, `image` (base64 and url), `tool_use`, and `tool_result`, including image content nested inside `tool_result` blocks so vision models consume tool-produced images. Streaming emits the Anthropic SSE sequence (`message_start`, `content_block_start`/`delta`/`stop`, `message_delta`, `message_stop`, `error`) with `usage` populated on both the non-streaming response and the streaming `message_delta`.

The implementation reuses the existing generation, chat-template, media, tool-call, and thinking-budget plumbing rather than duplicating the generation loop:

- `types/anthropic_request.rs`, `anthropic_response.rs`, `anthropic_stream.rs`: inbound/outbound Anthropic types and the typed SSE event enum.
- `anthropic_translator.rs`: Anthropic request to internal `ChatCompletionRequest` (system/messages/tools/tool_choice, image-in-tool-result), plus outbound content-block assembly, stop-reason mapping, and stop-sequence truncation, mirroring the Responses API translator.
- `streaming_anthropic.rs`: the SSE channel and the content-block index state machine.
- `routes/anthropic.rs`: thin handlers that call `prepare_chat_request_with_cache`, `build_generate_options`, the model provider, and the shared tool-call helpers. Both the message and count_tokens routes reject oversized tool arrays via the shared `MAX_TOOLS` bound to prevent template-rendering DoS.
- Route registration in `app.rs`; module wiring in `types/mod.rs`, `mod.rs`, `routes/mod.rs`.

User-facing API documentation is deferred to a follow-up; this change is the functional endpoint plus its unit tests. Verified with cargo fmt, cargo clippy (metal,accelerate, all-targets, -D warnings), and 44 new unit tests covering request translation, content-block assembly, stop-reason mapping, the tools DoS guard, and the streaming state machine.
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…A route (lablup#1196)

Issue lablup#1065 asks for an environment override that disables the M5
neural-accelerator attention routing, so the hypothesis "this dispatch is
why the M5 disagrees numerically" can be tested by A/B rather than by
reading code. There was none, and the M5 investigation on lablup#1182 had to
patch should_use_metal4_attention by hand and revert it afterwards. That
is how a diagnostic gets skipped on the next machine that needs it.

MLXCEL_METAL4_ATTENTION=0 now forces the route off. It is an off-switch
only: the hardware test still gates it, so the variable cannot route an
M1 into an M5 kernel and a stray value there is inert. Read once per
process, following the other MLXCEL_* kill switches.

Also unifies the two dispatch sites. lib.rs carried its own copy of
`hw.has_neural_accelerator && hw.macos_supports_na` rather than calling
the shared predicate, so the switch would have disabled the route in one
place and not the other. For a diagnostic whose whole value is a clean
A/B, a half-applied switch is worse than none.

Refs lablup#1065
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:macos macOS (Apple Silicon) specific priority:high High priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant