View source: R/ag_flash_attn.R
| ag_flash_attention | R Documentation |
Computes scaled dot-product attention over all heads at once with
ggml_flash_attn_ext(), instead of the per-head loop
ag_multihead_attention uses. Both the forward pass and its
gradient are one operation each, so the tape holds a single node rather than
the dozens a head loop records.
ag_flash_attention(q, k, v, n_heads, scale = NULL, mask = NULL, causal = FALSE)
q, k, v |
|
n_heads |
Number of attention heads. Must divide |
scale |
Softmax scale. Defaults to |
mask |
Optional attention mask, |
causal |
|
q, k and v are [d_model, seq] matrices whose rows
are split into n_heads contiguous blocks – the same head layout
ag_multihead_attention() uses. Projections are not included: apply
W_q, W_k, W_v before the call and W_o after it.
An ag_tensor of shape [d_model, seq_q].
d_model <- 16L; seq_len <- 8L
q <- ag_param(matrix(runif(d_model * seq_len, -1, 1), d_model, seq_len))
k <- ag_param(matrix(runif(d_model * seq_len, -1, 1), d_model, seq_len))
v <- ag_param(matrix(runif(d_model * seq_len, -1, 1), d_model, seq_len))
with_grad_tape({
out <- ag_flash_attention(q, k, v, n_heads = 4L)
loss <- ag_mse_loss(out, ag_tensor(matrix(0, d_model, seq_len)))
})
backward(loss)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.