Skip to content

Add scaled dot-product attention - #650

Open
seanmor5 wants to merge 1 commit into
mainfrom
sm-sdpa-attention
Open

seanmor5 wants to merge 1 commit into
mainfrom
sm-sdpa-attention

Conversation

@seanmor5

Copy link
Copy Markdown
Contributor

No description provided.

Adds `Axon.Layers.scaled_dot_product_attention/4` and the graph-level
`Axon.scaled_dot_product_attention/4`.

The functional kernel computes `softmax(Q · Kᵀ * scale + mask) · V` over
rank-4 inputs, and supports:

  * `:axes` - `:bshd` (default) or `:bhsd` input layouts
  * `:scale` - defaults to `1 / sqrt(head_dim)`
  * `:mask` - `:causal`, `{:causal, offset}`, `{:sliding_window, w}`,
    `{:sliding_window, w, offset}`, or a runtime boolean/float tensor
  * `:dropout_rate` - attention-probability dropout in `:train` mode
  * `:return_attention_weights`
  * grouped-query and multi-query attention, by repeating key/value
    heads to match the query

The graph layer wires a tensor mask in as an extra input and, when
dropout is enabled, adds a PRNG key state parameter so the key is
threaded across steps. Mask tensors and dropout keys are passed
positionally, which is why the kernel has 4-, 5- and 6-arity heads.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Comment thread lib/axon/layers.ex
maybe_attention_dropout(weights, dropout_key, opts[:dropout_rate], opts[:mode])

output = Nx.dot(weights, [3], [0, 1], value, [2], [0, 1])
output = from_bhsd(output, opts[:axes])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't we avoid transposes by using the correct reduce axes in dot directly?

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants