Skip to content

[ExecuTorch][WebGPU] Add optimized SDPA op#20851

Open
JCNTH wants to merge 1 commit into
gh/JCNTH/26/basefrom
gh/JCNTH/26/head
Open

[ExecuTorch][WebGPU] Add optimized SDPA op#20851
JCNTH wants to merge 1 commit into
gh/JCNTH/26/basefrom
gh/JCNTH/26/head

Conversation

@JCNTH

@JCNTH JCNTH commented Jul 10, 2026

Copy link
Copy Markdown

Stack from ghstack (oldest at bottom):

Adds a non-causal fused scaled-dot-product-attention kernel to the WebGPU backend, enabling the attention blocks of vision encoders (Florence-2 DaViT / SigLIP, SAM2) and non-causal cross-attention (BART) to run end-to-end on GPU.

Problem — the delegate had no kernel for et_vk.sdpa.default, the plain non-causal attention softmax(q @ kᵀ * scale + attn_mask) @ v that the et_vk source transform plugs into every vision-encoder attention block. Without it the attention layers broke the graph. This is distinct from the causal KV-cache sdpa_with_kv_cache: no cache, an optional additive mask, and it must handle asymmetric sequence lengths (S_q != S_kv, e.g. a Hiera pooled query or cross-attention).

Solution

  • Before: no non-causal fused-attention kernel — vision-encoder attention blocks could not lower into the delegate.
  • After: et_vk_sdpa_impl chains three compute dispatches over [B, H, S, D] (DSHB) row-major tensors — et_vk_sdpa_qk.wgsl computes the scaled Q·Kᵀ scores plus an optional additive mask, the reused sdpa_softmax.wgsl does the row-wise softmax, and et_vk_sdpa_av.wgsl computes softmax · V into the output.

Implementation

  • QK phase (et_vk_sdpa_qk.wgsl): one GPU thread per (b, h, s) row of the [B, H, S_q, S_kv] attention-weight buffer; q/k are bound as array<vec4<f32>> over D, and the thread loops over c (key positions) and d4 (D/4) accumulating dot(q4, k4), then multiplies by scale and adds mask[...] when has_mask. Row count B*H*S_q stays well under the 1D dispatch limit for any ViT.
  • Softmax phase: reuses the existing sdpa_softmax.wgsl (one workgroup per row, hardcoded @workgroup_size(64,1,1)) dispatched on a near-square 2D workgroup grid past the 65535 ceiling; the shader recovers the flat row index from @builtin(num_workgroups), so no override constant is needed.
  • AV phase (et_vk_sdpa_av.wgsl): one thread per (b, h, s, d4) computing a vec4<f32> of four output elements; v/out are bound as array<vec4<f32>> over D and the thread contracts over c scalar (S_kv is not guaranteed % 4 == 0), accumulating sm[...] * v4.
  • Two fp32 scratch buffers (attn, softmax, each B*H*S_q*S_kv) are allocated via graph.create_scratch_buffer; scale defaults to 1/sqrt(D) when the arg is None or takes the Double value; the three uniforms are compact structs (QkParams/AvParams 32 bytes, SoftmaxParams 16 bytes).
  • Uses the shared runtime helpers: utils::make_compute_pipeline, utils::make_uniform, utils::check_vec4_aligned (guards D % 4 == 0), utils::clamp_workgroup_size + utils::compute_1d_workgroup_count (QK / AV grids), utils::compute_2d_workgroup_count (softmax grid), and utils::make_optional_binding (a 4-byte dummy satisfies the mask binding when absent; the shader never reads it under has_mask == 0).
  • Mirrors Vulkan backends/vulkan/runtime/graph/ops/impl/SDPA.cpp SDPAMode::FUSED (general non-cache SDPA, [B, H, S, D] DSHB layout, optional additive attn_mask, optional scale, unpadded fp32 attention weights).

Constraints — fp32 only (bails on q/out byte mismatch); non-causal (causality is expressed as a baked additive mask input, not a code path); D % 4 == 0 for the vec4 QK/AV kernels (every model in scope uses D=64 or 128); q rank ≥ 3; k.dims == v.dims, q/k/v share H and D and all leading batch dims, and out.dims == q.dims; asymmetric S_q != S_kv is supported (reduces bit-identically to self-attention when equal); a supplied mask must be [B, H, S_q, S_kv] fp32.

Co-authored-with: Claude Code.

Differential Revision: D110836679

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jul 10, 2026

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/20851

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (1 Unrelated Failure)

As of commit 0313e86 with merge base aceeb40 (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@github-actions

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

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

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants