MetalLinear returns wrong outputs for every batch row after the first (3D inputs)
System Info
Apple M4 Pro, 64 GiB, macOS 26 transformers main @ 8073e6dc torch 2.14.0 (native MPS), kernels 0.17.2
Who can help?
@SunMarc (quantization), @vasqu / @drbh (kernels)
Information
- [ ] The official example scripts
- [x] My own modified scripts
Tasks
- [ ] An officially supported task in the
examplesfolder (such as GLUE/SQuAD, ...) - [x] My own task or dataset (give details below)
Reproduction
Repro steps
- Load LFM2.5-230M with MetalConfig on MPS (M4 Pro, torch 2.14.0 native Metal kernel build)
- Perform a batched run.
- Observe that every row after the first comes out as garbage, and some rows have non-finite logits.
Standalone repro:
uv venv .venv --python 3.12
uv pip install --python .venv/bin/python torch==2.14.0 transformers==5.16.1 kernels==0.16.1
uv pip install --python .venv/bin/python torch==2.14.0 kernels "transformers @ git+https://github.com/huggingface/transformers@main"
.venv/bin/python repro.py
repro.py:
import torch
from transformers.integrations.metal_quantization import (
MetalLinear, _affine_quantize_tensor,
)
assert torch.backends.mps.is_available()
torch.manual_seed(42)
K, N, GROUP, BITS = 512, 256, 64, 8
w, s, b = _affine_quantize_tensor(torch.randn(N, K), GROUP, BITS)
layer = MetalLinear(K, N, bits=BITS, group_size=GROUP).to("mps")
with torch.no_grad():
layer.weight.copy_(w)
layer.scales.copy_(s)
layer.qbiases.copy_(b)
x = torch.randn(4, 3, K, device="mps", dtype=torch.bfloat16)
with torch.inference_mode():
actual = layer(x)
flat = layer(x.reshape(-1, K)).reshape(4, 3, N)
rows = torch.stack([layer(row) for row in x])
torch.mps.synchronize()
print("3D finite by batch:", torch.isfinite(actual).all(-1).all(-1).tolist())
print("flattened finite:", bool(torch.isfinite(flat).all()))
print("3D vs individual max abs error by batch:",
(actual.float() - rows.float()).abs().amax((1, 2)).tolist())
print("flattened vs individual max abs error:",
(flat.float() - rows.float()).abs().max().item())
torch.testing.assert_close(flat, rows, rtol=0.02, atol=0.125)
# Fails without the integration-side flatten/restore fix.
torch.testing.assert_close(actual, rows, rtol=0.02, atol=0.125)
Details:
MetalLinear.forward passes the raw N-D input to affine_qmm_t. When the input is 3D (batch, seq, hidden), the Metal kernel only computes batch element 0 correctly. Every later row is garbage, so batched generate() with MetalConfig silently corrupts every row except the first.
Batch size 1 is fine, unquantized BF16 are fine at every batch size, MLX / MLX-LM 0.32.2 / 0.31.3 comparison of the same model is fine.
This is the same bug as #47331, which went stale and was auto-closed without a fix. The kernel-side fix (kernels-community#1038) was closed by a bot and never merged. The bug is still present in latest main.
Expected behavior
Each row of a batched MetalLinear forward should equal that row run alone. At the model level, batched greedy generate() with MetalConfig should give each row the same text as batch size 1, as unquantized bf16 already does.
Proposed fix
MetalLinear.forward should flatten the input to 2D before affine_qmm_t and reshape the output afterwards. This is a two-line change and it does not depend on a kernel release. I can open a PR with the fix and regression tests (a mocked CPU test for shape handling, plus an MPS test that compares batched and per-row outputs for 4/8 bits, fp16/bf16 and with/without bias).
I have a fix that I could submit as a PR, but I did use coding agent assistance, and since I am a first-time contributor, I can't honestly check that checkbox on it, so it's going to wait until someone looks at the issue and oks opening the PR.
Hi! I'd like to take this one. I reproduced it on an Apple M2 (16 GB) with torch 2.14.1 on current main: with a (4, 3, 512) bf16 input, row 0 matches the per-row result but rows 1–3 are wrong (max abs error ≈ 5e3–1e4). Flattening to 2D before affine_qmm_t and reshaping afterwards gives an exact match (error 0.0), which agrees with the proposed fix in the description.
@francip, you mentioned you have a fix ready. Are you planning to open the PR, or is it OK if I do? @SunMarc / @vasqu, would you be OK with a PR that makes the MetalLinear.forward flatten/restore change plus a regression test?
Disclosure: I used an AI assistant (Claude Code) to help investigate and reproduce this. I'll review and validate any code I submit myself, per the contributing guidelines.
cc @isalia20 for MPS as well!
Hey ! For metal, I would actually advise you to have a look at the gguf integration we did. https://huggingface.co/blog/transformers-llama-cpp-quants. You will be able to load gguf on the hub in transformers without having to quantize again ! It requires support for this model with gguf but the PR should be rather simple @francip.
As for the metal kernels for metal config, I will take care of it and fix the kernels.
@SunMarc if GGUF works, and you are fixing the kernels for metal... well, there goes my chance to contribute to transformers. :-)
thanks for the quick look!
You can do the PR for the gguf support ! For the metal fix, it is a bit more complex as you need rights on the kernels-community project.
Heh, looks like LFM family is going through the plain nn.linear for GGUF format, so it needs proper config. (#49399)
Also, GGUF doesn't have kernel for torch 2.14... more fun.
That aside, #49398 is now up. The change is flattening MetalLinear.forward similarly to how GgufLinear.forward is flattening the inputs.
This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.
Please note that issues that do not follow the contributing guidelines are likely to be ignored.
@SunMarc did you have a chance to fix the kernels for this one?
I have the PR ready but not merged yet. Will try to push soon to get it finished. Sorry for the wait
An independent re-check of this issue against today's main, with the fix packaged for whoever can run the last step.
Where it stands
MetalLinear.forwardon currentmainis unchanged — it still hands the raw N-D input toaffine_qmm_t. I diffed the file: byte-identical to the version this was reported against, 308 lines.- #49398 (the flatten/restore PR) was closed unmerged, and the kernel-side fix is not in
mainyet — so batchedgenerate()withMetalConfigstill corrupts every row after the first, and the thread has since been flagged stale.
The fix — the same flatten/restore shape #49398 proposed, re-derived against current main: flatten leading dimensions to 2D before the kernel call, restore them on the output. For 2D inputs both reshapes are no-ops, so existing behaviour is unchanged. Patch and verification script: https://gist.github.com/1OF1Research/00c08569638eb94d3b3560d9abbd4e90
What I could and could not check — plainly: I have no Apple or Metal test hardware, so I have not run the kernel itself. Everything checkable without it has been checked: the patch applies cleanly to current main; on CPU, with the kernel replaced by a strict 2D stand-in computing the same math, the patched wrapper's shape handling is exact — the kernel receives precisely the flattened input with values untouched, 3D/4D and non-contiguous outputs are bit-identical to the flattened call and agree with per-row calls within this issue's own tolerances, 2D output is bit-identical to the unpatched layer, 36 of 36 checks. The fault's on-hardware behaviour rests on the reporter's repro and the independent M2 reproduction already in this thread.
The last step needs a Mac. The gist's verify_hf005.py is one command — python3 verify_hf005.py — that reproduces the fault on the installed transformers and then confirms the fix in the same run, and prints a summary to paste back here. With the hardware itself this can be taken that last step in minutes; if the numbers come out different, that output is the evidence to bring back.
Follow-up: the cloud run was tried — the wall is now measured, not assumed.
The verification package above needed Apple hardware, which I don't have. GitHub Actions offers macOS runners on Apple Silicon, so I built the run there: a public repo holding the same verify_hf005.py (byte-identical to the gist's file), wired to a workflow anyone can re-dispatch — https://github.com/1OF1Research/hf005-metal-verify
What the runs found, from the job logs:
macos-14: the platform cancelled both dispatches within seconds, no runner assigned.macos-15andmacos-26-arm64: the jobs ran end to end — torch 2.15.0 installed, transformers frommain, the probe executed. Buttorch.backends.mps.is_available()is False on both: GitHub's macOS runners are virtualized, and torch itself reports "Skipping device Apple Paravirtual device that does not support Metal 2.0". The Metal device MPS needs is not exposed inside the runner, so the kernel cannot run there. Logs: macos-15 run, macos-26 run.
So the Actions door is real but stops at the hypervisor: everything up to the Metal call itself now runs in public, on Apple Silicon, in about two minutes — and the one remaining step is unchanged: python3 verify_hf005.py on a physical Mac, where MPS is present. If GitHub ever exposes a Metal-capable device to these runners, the same workflow completes the verification untouched.
Follow-up 2: the wall fell — the verification has now run on the Metal kernel itself, in the cloud.
The earlier cloud runs stopped before the Metal call because they rode torch 2.15.0. That refusal turned out to be one gate of three, and each is now measured rather than assumed:
- MPS gate: on GitHub's macOS runners, torch 2.15.0 (and 2.9.1) refuses the virtualized GPU — "does not support Metal 2.0" — but torch 2.8.0 and every torch from 2.10.0 to 2.14.0 initialize MPS and execute real ops there. Probed exhaustively (availability flag plus an actual tensor op) on both runner images: macos-15 matrix, macos-26 matrix.
- Kernel gate: transformers loads
kernels-community/mlx-quantization-metal-kernelsatversion=1, whose published build variants span only torch 2.10–2.14. So the torch 2.8.0 run — MPS willing — stopped in the resolver, with the variant list in its error: run. - OS gate: the torch 2.13 and 2.14 variants require macOS 26.0 or later, which the macos-15 image (15.8.2) cannot satisfy: run.
The pairing where all three gates open at once: a macos-26 runner (Apple M1 (Virtual), macOS 26.7.2) with torch 2.14.0, kernels 0.18.3, transformers 5.23.0 — 5.23.0's metal_quantization.py is byte-identical to current main, so the code under test is exactly the code in this thread. The probe reads mps available: True, and the script ran end to end. Full public log: run 43672907425.
Its verdict:
- Stage 1, installed transformers as-is — FAULT PRESENT at both widths. 3D vs per-row max abs error, by batch row: 8-bit
[0.0, 5030.7, 9003.8, 10203.6], 4-bit[0.0, 3337.0, 4505.9, 6869.9]— row 0 exact, rows 1–3 wrong at the magnitude already reported in this thread, while the flattened call agrees with the per-row reference at exactly 0.0. - Stage 2, the flatten/restore fix applied in-process — FIX CONFIRMED at both widths: every row finite, max abs error 0.0 everywhere.
fault present on installed transformers: yes, bits [8, 4] flatten/restore fix confirmed on this hardware: yes
Honest naming, as in the earlier posts: this ran on a GitHub-hosted cloud runner — a virtualized Apple M1, not a physical Mac and not my own hardware. What changed is that the Metal kernel itself executed there, which was the walled step: the fault reproduced on the real kernel path and the fix held on it. The gist now carries the full results file (ON-HARDWARE-RESULTS.md), and the workflow stays in the repo for anyone to re-dispatch.
What would prove this wrong: run verify_hf005.py on any physical Mac and get different stage numbers — the script prints a summary block built for exactly that comparison.