mlx icon indicating copy to clipboard operation
mlx copied to clipboard

mx.fast.scaled_dot_product_attention with sinks produces different results for S=1 vs S=N queries

Open machiabeli opened this issue 7 months ago • 2 comments

Bug: mx.fast.scaled_dot_product_attention with sinks produces different results for S=1 vs S=N queries on identical K/V

Summary

When sinks (per-head learnable biases in the softmax denominator) is passed to mx.fast.scaled_dot_product_attention, the output for the last query position differs depending on whether the query is part of a batch (S=N) or processed alone (S=1) against the same K/V. This causes greedy-decode divergence between cache-based autoregressive generation and full-sequence recomputation in DeepSeek-V4, which is the first model to use the sinks parameter.

Minimal description

Given identical Q (for one position), K, V, scale, and mask=None:

# Batch query (S=34): Q=[B, H, 34, D], K=V=[B, 1, 34, D]
out_batch = mx.fast.scaled_dot_product_attention(q_batch, k, v, scale=s, mask=None, sinks=sinks)
result_batch = out_batch[:, :, -1, :]  # last position

# Single query (S=1): Q=[B, H, 1, D], K=V=[B, 1, 34, D]
out_single = mx.fast.scaled_dot_product_attention(q_single, k, v, scale=s, mask=None, sinks=sinks)
result_single = out_single[:, :, 0, :]

# These should be numerically equivalent but differ
# When sinks=None, they ARE equivalent (verified bit-identical)

Impact

DeepSeek-V4 uses per-head attn_sink biases at every attention layer. During autoregressive generation with cache, each decode step calls SDPA with S=1. During a full-sequence forward (no cache), SDPA processes all S tokens at once. The numerical difference cascades through 43 transformer layers and flips token predictions at near-tied logit margins.

Concrete example on DeepSeek-V4-Flash-4bit (M3 Ultra 512GB, mlx 0.31.2):

  • Prompt: 'User: Output a JSON object with exactly one field called "verdict"...\n\nAssistant: '
  • No-cache (S=34 batch): produces ' ```json\n{\n "verdict' (tok 223 = ' ' at step 4)
  • With-cache (S=1 decode): produces ' ```json\n{\n "verdict' (tok 361 = ' ' at step 4)
  • With sinks=None patched: both paths produce identical tokens

Bisection evidence

Test NC vs WC match? What it rules out
RotatingKVCache + CompressedKVCache (default) DIVERGES at step 4 —
All KVCache (no RotatingKV, no compressor) MATCHES Cache implementation is not the cause
K/V at SDPA call site captured and diffed BIT-IDENTICAL (0.0e+00 across all 34 positions) Cache contents are correct
MLX determinism (same path run twice) BIT-IDENTICAL Not stochastic noise
Compressor promoted to fp32 weighted sum Still diverges Not compressor precision
sinks=None patched in V4Attention MATCHES Sinks is the cause

The "All KVCache fixes it" result is a red herring — it works because disabling CompressedKVCache also disables the compressor architecture, which reduces the number of layers that amplify the small SDPA-sinks divergence. The actual root cause is the sinks codepath in mx.fast.scaled_dot_product_attention.

Layer-by-layer cascade

With sinks enabled, the per-layer hidden-state divergence (max absolute diff, last position, bf16→fp32):

Layer  0: 4.88e-4   (seed — first SDPA with sinks)
Layer  1: 1.22e-3   (amplified through compressor softmax)
Layer  2: 5.86e-2   (50x cascade)
...
Layer 20: 4.56e-1
Layer 42: 6.21e+0   (saturated)

With sinks=None: all layers show 0.0e+00 divergence.

Environment

  • mlx 0.31.2
  • mlx-lm PR #1189 HEAD 7d20c1d (DeepSeek-V4 support)
  • mlx-community/DeepSeek-V4-Flash-4bit (also reproduced on bf16 by @anerjy)
  • M3 Ultra 512GB, macOS 26
  • Python 3.14

Suggested fix direction

The sinks parameter adds a per-head scalar to the softmax log-denominator. The numerical path for this addition may differ between the S=1 and S=N kernel dispatch shapes (e.g., different reduction tree, different intermediate precision). Ensuring the sinks contribution is computed at the same precision regardless of query count should fix the inconsistency.

Related

  • DeepSeek-V4 mlx-lm PR: https://github.com/ml-explore/mlx-lm/pull/1189
  • Original bug report by @anerjy on that PR (detailed bisection + minimal reproducer)

machiabeli avatar Apr 26 '26 08:04 machiabeli

Update — retracting the sinks-specific diagnosis after further verification.

I was not able to reproduce the S=1 vs S=N divergence with synthetic data using mx.fast.scaled_dot_product_attention with sinks in isolation (both paths produce bit-identical results at B=1, H=4, D=64, N=34).

What the sinks=None test actually showed is that removing sinks changes the softmax normalization enough that the NC and WC paths no longer disagree on the argmax — but this is because the logit margin increased, not because sinks has a precision bug. The underlying cache-vs-recompute divergence still exists; sinks just makes the margin narrow enough to flip.

I'm continuing the investigation on the actual model to isolate the real precision source. Will update when I have a standalone reproducer. Apologies for the premature filing — should have verified with synthetic data before opening.

machiabeli avatar Apr 26 '26 08:04 machiabeli

Closing — the sinks-specific diagnosis didn't reproduce with synthetic data. The underlying cache-vs-recompute divergence is real but the root cause is elsewhere (likely in how the full V4 attention pipeline accumulates bf16 precision differences across cache types). Continuing investigation on mlx-lm#1189.

machiabeli avatar Apr 26 '26 08:04 machiabeli