Skip to content
class

ScaledDotProductAttentionBackward

ScaledDotProductAttentionBackward

Python wrappers

Public Python APIs implemented by this engine symbol.

Autograd node for scaled dot-product attention with optional additive mask and post-softmax causal constraint.

Implements the canonical SDPA operation from Vaswani et al. (2017), Attn(Q,K,V)=softmax ⁣(QK⊤dk+M)V\text{Attn}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V, where Q,K,VQ, K, V are query / key / value projections shaped (..., L, D) and MM is an additive mask (-inf at disallowed positions, 0 elsewhere). The node saves three edges {Q, K, V} and a fourth Storage slot saved_weights_ holding the pre-multiplication attention weight matrix W=softmax(QK⊤⋅s)W = \text{softmax}(QK^\top \cdot s), where s = scale_.

On the MLX (GPU) path the fused mlx::core::fast::scaled_dot_product_attention kernel does not return WW — instead it returns a {1}-shape placeholder. apply() detects saved_weights_.shape().size() == 1 and re-computes W=softmax(QK⊤⋅s)W = \text{softmax}(QK^\top \cdot s) from the saved Q,KQ, K before back-propagating. On the Accelerate (CPU) path the kernel returns the genuine weight matrix and the recompute branch is skipped.

Math

Aij=s⋅(Qi⋅Kj),Pij=exp⁡(Aij+Mij)∑kexp⁡(Aik+Mik),yi=∑jPij Vj A_{ij} = s \cdot (Q_i \cdot K_j), \quad P_{ij} = \frac{\exp(A_{ij} + M_{ij})}{\sum_k \exp(A_{ik} + M_{ik})}, \quad y_i = \sum_j P_{ij}\, V_j

Gradients flow back through the softmax Jacobian ∂P/∂A=diag(P)−PP⊤\partial P / \partial A = \mathrm{diag}(P) - P P^\top (per row), giving

∂L∂Q=s⋅(ΔA) K,∂L∂K=s⋅(ΔA)⊤Q,∂L∂V=P⊤ ∂L∂y \frac{\partial \mathcal{L}}{\partial Q} = s \cdot (\Delta A)\, K,\quad \frac{\partial \mathcal{L}}{\partial K} = s \cdot (\Delta A)^\top Q,\quad \frac{\partial \mathcal{L}}{\partial V} = P^\top\, \frac{\partial \mathcal{L}}{\partial y}

where ΔAij=Pij(∂L/∂yi⋅Vj⊤−∑kPik(∂L/∂yi⋅Vk⊤))\Delta A_{ij} = P_{ij}\bigl(\partial \mathcal{L}/\partial y_i \cdot V_j^\top - \sum_k P_{ik} (\partial \mathcal{L}/\partial y_i \cdot V_k^\top)\bigr).

References

Vaswani et al., "Attention Is All You Need" (NeurIPS 2017).

Attributes

schema_v1OpSchema
Op schema (name "scaled_dot_product_attention", version 1, AmpPolicy::ForceFP32, autograd-aware). AMP forces the kernel to FP32 because the softmax-exp accumulation is numerically unstable at half precision.
scale_double
Dot-product scale factor s (typically 1/dk1/\sqrt{d_k}) multiplied into QK⊤QK^\top before the softmax. Default: 1.0.
orig_q_shape_Shape
Original (unflattened) shape of Q recorded at forward; used by apply() to restore leading batch dims on the gradient tensor.
orig_k_shape_Shape
Original shape of K.
orig_v_shape_Shape
Original shape of V.
saved_weights_Storage
Attention weight matrix W. Genuine on the CPU path; on the GPU path this is a {1}-shape placeholder and the backward recomputes W from the saved Q, K and scale_.

Notes

The mask is additive: callers must already have converted boolean "where to mask" patterns into floats containing -inf where the position should be excluded and 0 elsewhere (see lucid.nn.modules.attention._to_additive_mask). Causal masking is implemented engine-side when is_causal=true by adding an upper-triangular -inf matrix before the softmax, so the caller does not need to materialise the mask in Python.

Static methods

1
static

forward

→TensorImplPtr
int forward(const int & q, const int & k, const int & v, const int & attn_mask_or_null, double scale, bool is_causal)

Run the SDPA forward and return the output tensor.

Dispatches to IBackend::sdpa_forward after validating that the leading batch dims of q, k and v agree, that q.shape[-1] == k.shape[-1] (the dot-product key dim d_k), and that k.shape[-2] == v.shape[-2] (the source-sequence length L_k). On the autograd-recording path this also attaches a new ScaledDotProductAttentionBackward node with saved_weights_ populated.

Parameters

qTensorImplPtr
Query tensor of shape (..., L_q, d_k) with at least 2 dimensions. All leading "batch" dims must broadcast with the corresponding dims of k and v.
kTensorImplPtr
Key tensor of shape (..., L_k, d_k); the last dim must equal q.shape[-1].
vTensorImplPtr
Value tensor of shape (..., L_k, d_v); the penultimate dim must equal k.shape[-2].
attn_mask_or_nullTensorImplPtr
Optional additive mask broadcastable to (..., L_q, L_k). Pass nullptr to omit (no additive term is materialised).
scaledouble
Multiplicative factor applied to Q @ K^T before the softmax. Typically 1/dk1/\sqrt{d_k}.
is_causalbool
If true, an upper-triangular -inf mask is added engine-side, restricting position i to attend only to positions j <= i.

Returns

TensorImplPtr

Attention output of shape (..., L_q, d_v).

Raises

ErrorBuilder
If any input is null, devices or dtypes disagree, rank is less than 2, or the shape contracts above are violated.

Methods

3
fn

apply

→std::vector<Storage>
int apply(int grad_out)

Compute gradients with respect to Q, K, V and the additive mask from the upstream gradient of the output.

Reconstructs the saved weight matrix on the GPU path (where saved_weights_ is a {1}-shape placeholder) by recomputing W=softmax(QK⊤⋅s)W = \text{softmax}(QK^\top \cdot s), then dispatches to IBackend::sdpa_backward for the input gradients.

Because the scores are S=QK⊤s+MS = QK^\top s + M, the mask gradient is exactly the score gradient: ∂L/∂M=∂L/∂S\partial\mathcal{L}/\partial M = \partial\mathcal{L}/\partial S. Both backends already form that quantity to produce dQ and dK, so it is returned rather than discarded, then reduced from the full score shape back to orig_mask_shape_. A Bool keep-mask is not differentiable and gets no edge.

Parameters

grad_outStorage
Upstream gradient ∂L/∂y\partial \mathcal{L}/\partial y shaped like the SDPA output (..., L_q, d_v).

Returns

std::vector<Storage>

Four Storage objects in edge order {dQ, dK, dV, dM}, reshaped back to orig_q_shape_ / orig_k_shape_ / orig_v_shape_ / orig_mask_shape_. dM is empty when no differentiable mask was supplied; the engine discards it because that edge is null.

fn

apply_for_graph

→std::vector<TensorImplPtr>
int apply_for_graph(const int & grad_out)

Graph-recording backward for create_graph=True.

The fused backward returns Storages, so a second derivative through attention — a gradient penalty, the double-backward form of a JVP — had nothing to differentiate. This writes the closed form out in recording ops, recomputing the weights from the saved Q and K under the same mask the forward used.

Parameters

grad_outconst TensorImplPtr&
Upstream gradient, possibly carrying its own grad_fn.

Returns

std::vector<TensorImplPtr>

{dQ, dK, dV, dM}; dM is null unless the additive mask is a differentiable input.

fn

release_own_saved

void release_own_saved()