Repository navigation
Description
We run long agent conversations on Apple Silicon (Qwen3.8-27B through MTPLX). Normally the KV cache is one buffer that grows with every turn. Resuming a stored conversation, forking it or returning to an earlier turn then copies the whole history into a new buffer. To avoid that copy, we keep the cache as a chain of linked segments, one per turn: a new turn only adds a segment and refers to the existing ones. On a 50K-token conversation this lowers the peak memory of a follow-up turn by 2 to 5 GB.
To attend over such a cache, each segment is attended separately and the results are merged:
lse = logaddexp(lse_1, lse_2)
out = exp(lse_1 - lse) * out_1 + exp(lse_2 - lse) * out_2
This merge is exact, but it needs the logsumexp (lse) of each segment's attention. mx.fast.scaled_dot_product_attention returns only the output, so today the only way to get the lse is to compute attention by hand, which builds the full score matrix and is many times slower (see below).
Measurements (M5 Pro)
Head dim 128, 32 query heads, 8 KV heads, fp16:
| query x key length | current SDPA (output only) | proposed function (output + lse) | by hand (q @ k.T, softmax, @ v) | by hand, extra memory (fused: under 32 MB) |
|---|---|---|---|---|
| 512 x 4096 | 1.57 ms | 1.51 ms | 9.84 ms | 0.6 GB |
| 2048 x 16384 | 20.50 ms | 20.33 ms | 153.49 ms | 10 GB |
| 4096 x 32768 | 81.08 ms | 80.87 ms | 647.05 ms | 40 GB |
The fused kernels already compute the lse (since #4563, for the VJP). Returning it costs no measurable time.
Proposal
A separate function, so the existing one does not change:
mx.fast.scaled_dot_product_attention_with_lse(q, k, v, *, scale, mask=None, sinks=None) -> (out, lse)
- For fp16 and bf16 inputs, both
outandlseare float32. A caller who merges would otherwise get each piece rounded to 16 bits, and then round again after the merge. In our tests that leaves 23 to 28% of bf16 elements different from the correctly rounded result, against 0.9 to 2.6% with float32 output. Cast with.astypeif you want the input type. - Kernel change: one function constant that lets the existing kernels store their float32 result unrounded. No new kernel instantiations. The existing
scaled_dot_product_attentionis not affected: its output is exactly the same as on main. - Where the fused kernel cannot produce the lse (short queries, CPU, under
grad), the function falls back to the unfused computation, also in float32.
Merging partial attention results with the lse is also useful for a shared prompt prefix (cascade attention) and for chunked prefill of a long context. Other frameworks, like FlashAttention and vLLM, return the lse for these uses.
Related
#3594 proposed using the lse in the fused path for chunked forward passes and was closed because the lse is mostly used in training. This request is for inference, for the merge above.
Branch with the function and tests: jvmenen/mlx@main...sdpa-return-lse
Would a PR along these lines be welcome?
Activity
zcbenz commentedon Oct 23, 2026
This looks like a suspicious approach, I don't think we would support it.
jvmenen commentedon Oct 23, 2026
Thanks for looking at this. I think my motivation got in the way of the actual request, so let me restate it without our cache layout.
The request is only this: let the fused SDPA return the logsumexp it already computes. With the output and the lse of two attention calls over disjoint key ranges, the caller can combine them into exactly the result of one call over all keys:
This works however the keys are split or stored. Today the only way to get the lse in MLX is to compute attention by hand, which is 8 to 9 times slower because it materialises the full score matrix.
The fused kernels already produce the lse for the VJP (#4563), and the change leaves scaled_dot_product_attention untouched. If a separate function isn't the shape you want, a return_lse flag or an internal-only hook would work for us too. Would you be open to reconsidering it on that basis?
zcbenz commentedon Oct 23, 2026
Adding a
return_lseflag looks good to me since it is also other libraries like cuDNN does. But this still feels like an unusual API request, are there existing arts showing logsumexp being useful except for trainings?jvmenen commentedon Oct 24, 2026
Yes, a few examples, all inference:
sdpa_vector_2passsplits the keys into blocks, each block writes its max and sum of exponentials, and a second pass merges them. That is the same merge, done internally;return_lsewould let a caller do it across calls.flash_attn_with_kvcachehas areturn_softmax_lseoption.return_softmax_lse=True, and merges the two with the lse.return_lse=Trueandmerge_state_in_place.zcbenz commentedon Oct 25, 2026
Thanks for the examples, I'm reopening this issue.
foreverflying commentedon Nov 9, 2026
I've been waiting for this feature for a while. Currently AI did this patch for me, but my code has to depend on this modified local mlx lib. I wish this propose could be considered seriously and become an official feature sooner. Thanks!
Nawazz-ish commentedon Nov 20, 2026
Hi @zcbenz I have implemented the agreed return_lse flag in my branch. It returns (out, lse), with float32 outputs for half inputs. Empty rows return -inf for LSE and 0 for output. Works on both Metal and CUDA. The full test suite passes on Metal, and SDPA tests pass on CUDA. what remains is that there's no fused CUDA path for half inputs and a masked-graph edge case.
I can't open a PR due to the contributor limit. Could you please accept one from my branch, or open it yourself?