Skip to content

Return the logsumexp from fused SDPA, for merging attention over KV chunks #4693

Open

Description

@jvmenen

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 out and lse are 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 .astype if 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_attention is 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

  1. zcbenz commented on Oct 23, 2026

    @zcbenz
    Member

    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.

    This looks like a suspicious approach, I don't think we would support it.

  2. jvmenen commented on Oct 23, 2026

    @jvmenen
    ContributorAuthor

    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:

    lse = logaddexp(lse_1, lse_2)
    out = exp(lse_1 - lse) * out_1 + exp(lse_2 - lse) * out_2
    

    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?

  3. zcbenz commented on Oct 23, 2026

    @zcbenz
    Member

    Adding a return_lse flag 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?

  4. jvmenen commented on Oct 24, 2026

    @jvmenen
    ContributorAuthor

    Yes, a few examples, all inference:

  5. zcbenz commented on Oct 25, 2026

    @zcbenz
    Member

    Thanks for the examples, I'm reopening this issue.

  6. reopened this on Oct 25, 2026
  7. foreverflying commented on Nov 9, 2026

    @foreverflying

    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!

  8. Nawazz-ish commented on Nov 20, 2026

    @Nawazz-ish

    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?

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions