-
-
Notifications
You must be signed in to change notification settings - Fork 611
MultiHeadAttention implementation #2146
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 19 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
a7c5952
move multiheadattention from Metalhead
CarloLucibello 40c706d
generic attention
CarloLucibello 59edf23
[ci skip] updates
CarloLucibello 3646956
[ci skip] updates
CarloLucibello 2644283
[ci skip] fix tullio impl
CarloLucibello 0c61daa
causal mask
CarloLucibello 6e7f538
[ci skip] mask
CarloLucibello e212b6b
[ci skip] updates
CarloLucibello 2df4d5e
[ci skip] add native implementation
CarloLucibello 30b22d7
support mask = :causal
CarloLucibello 38b8bdf
[ci skip] factor out impl
CarloLucibello 19fe8d9
[ci skip] remove jax
CarloLucibello 2b9b219
[ci skip] more benchs
CarloLucibello 5745555
finish up
CarloLucibello a1e8365
cleanup
CarloLucibello 2ecf19b
add cuda tests
CarloLucibello b2809b2
cleanup tests
CarloLucibello bd28c54
IntOrDims
CarloLucibello 111d814
cleanup
CarloLucibello 0b10823
remove with_scores
CarloLucibello 29afec7
improve docstring
CarloLucibello File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
|
||
const A3{T} = AbstractArray{T, 3} | ||
const IntOrDims{N} = Union{Int, Dims{N}} | ||
|
||
""" | ||
MultiHeadAttention(dims; [nheads, bias, init, dropout_prob]) | ||
|
||
The multi-head dot-product attention layer used in Transformer architectures [1]. | ||
|
||
[1] Vaswani et al. "Attention is all you need." Advances in Neural Information Processing Systems. 2017. | ||
|
||
# Arguments | ||
|
||
- `dims`: The embedding dimensions of inputs, intermediate tensors and outputs. | ||
In the most general case, it is given as | ||
`(q_in_dim, k_in_dim, v_in_dim) => (qk_dim, v_dim) => out_dim`. | ||
Can take also simpler forms as | ||
`dims::Int`, `in_dim::Int => (qk_dim, v_dim) => out_dim`, | ||
`in_dim::Int => qkv_dim => out_dim`. | ||
|
||
- `nheads`: number of heads. Default `8`. | ||
- `init`: weight initializer for the Dense layers. Default `glorot_uniform`. | ||
- `bias` : whether pointwise QKVO dense transforms use bias. Default `false`. | ||
- `dropout_prob`: dropout probability for the attention scores. Default `0.0`. | ||
|
||
# Forward | ||
|
||
(mha::MultiHeadAttention)(q_in, k_in, v_in, [bias]; [mask, withscores]) | ||
|
||
- `q_in`: input query array of size `(q_in_dim, q_len, batch_size...)`. | ||
- `k_in`: input key array of size `(k_in_dim, kv_len, batch_size...)`. | ||
- `v_in`: input value array of size `(v_in_dim, kv_len, batch_size...)`. | ||
- `mask`: input array broadcastable to size | ||
`(kv_len, q_len, nheads, batch_size)`. Default `nothing`. | ||
- `withscores`: Whether to return the attention scores. Default `false`. | ||
|
||
In alternative, `mha(q_in)` is equivalent to `mha(q_in, q_in, q_in)` (self-attention) | ||
and `mha(q_in, k_in)` is equivalent to `mha(q_in, k_in, k_in)` (key and value are the same). | ||
|
||
|
||
See also [`NNlib.dot_product_attention`](@ref). | ||
|
||
# Examples | ||
|
||
```julia | ||
mha = MultiHeadAttention(64, nheads = 8) | ||
q = rand(Float32, (64, 10, 32)) | ||
k = rand(Float32, (64, 20, 32)) | ||
v = rand(Float32, (64, 20, 32)) | ||
y = mha(q, k, v) # [y] = [64, 10, 32] | ||
|
||
mha = MultiHeadAttention(64 => 1024 => 1024, nheads = 8) | ||
y = mha(q) # self-attention; [y] = [1024, 10, 32] | ||
``` | ||
""" | ||
struct MultiHeadAttention{P1, D, P2} | ||
nheads::Int | ||
q_proj::P1 | ||
k_proj::P1 | ||
v_proj::P1 | ||
attn_drop::D | ||
out_proj::P2 | ||
end | ||
|
||
@functor MultiHeadAttention | ||
|
||
function MultiHeadAttention(dims; | ||
nheads::Int = 8, | ||
bias::Bool = false, | ||
init = glorot_uniform, | ||
dropout_prob = 0.0) | ||
|
||
dims = normalize_mha_dims(dims) | ||
@assert dims.qk % nheads == 0 "qk_dim should be divisible by nheads" | ||
@assert dims.v % nheads == 0 "v_dim should be divisible by nheads" | ||
q_proj = Dense(dims.q_in => dims.qk; bias, init) | ||
k_proj = Dense(dims.k_in => dims.qk; bias, init) | ||
v_proj = Dense(dims.v_in => dims.v; bias, init) | ||
attn_drop = Dropout(dropout_prob) | ||
out_proj = Dense(dims.v => dims.out; bias, init) | ||
return MultiHeadAttention(nheads, q_proj, k_proj, v_proj, attn_drop, out_proj) | ||
end | ||
|
||
# turns the dims argument into a named tuple | ||
normalize_mha_dims(dims::Int) = | ||
(; q_in=dims, k_in=dims, v_in=dims, qk=dims, v=dims, out=dims) | ||
|
||
function normalize_mha_dims((in, (qkv, out))::Pair{<:IntOrDims{3}, <:Pair{<:IntOrDims{2}, Int}}) | ||
if in isa Int | ||
q_in = k_in = v_in = in | ||
else | ||
q_in, k_in, v_in = in | ||
end | ||
if qkv isa Int | ||
qk = v = qkv | ||
else | ||
qk, v = qkv | ||
end | ||
return (; q_in, k_in, v_in, qk, v, out) | ||
end | ||
|
||
# self-attention | ||
(mha::MultiHeadAttention)(qkv; kws...) = mha(qkv, qkv, qkv; kws...) | ||
|
||
# key and value are the same | ||
(mha::MultiHeadAttention)(q, kv; kws...) = mha(q, kv, kv; kws...) | ||
|
||
function (mha::MultiHeadAttention)(q_in::A3, k_in::A3, v_in::A3, bias=nothing; | ||
withscores=false, mask=nothing) | ||
## [q_in] = [q_in_dim, q_len, batch_size] | ||
## [k_in] = [k_in_dim, kv_len, batch_size] | ||
## [v_in] = [v_in_dim, kv_len, batch_size] | ||
q = mha.q_proj(q_in) # [q] = [qk_dim, q_len, batch_size] | ||
k = mha.k_proj(k_in) # [k] = [qk_dim, kv_len, batch_size] | ||
v = mha.v_proj(v_in) # [v] = [v_dim, kv_len, batch_size] | ||
x, α = NNlib.dot_product_attention(q, k, v, bias; mha.nheads, mask, fdrop=mha.attn_drop) | ||
x = mha.out_proj(x) | ||
# [x] = [out_dim, q_len, batch_size] | ||
# [α] = [kv_len, q_len, nheads, batch_size] | ||
return withscores ? (x, α) : x | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
|
||
|
||
@testset "attention" begin | ||
dim = 4; nheads = 2; len = 3; batch_size = 5 | ||
mha = MultiHeadAttention(dim; nheads) | ||
q = rand(Float32, (dim, len, batch_size)) | ||
k = rand(Float32, (dim, len, batch_size)) | ||
v = rand(Float32, (dim, len, batch_size)) | ||
|
||
y, α = mha(q, k, v, withscores=true) | ||
@test y isa Array{Float32, 3} | ||
@test size(y) == (dim, len, batch_size) | ||
@test α isa Array{Float32, 4} | ||
@test size(α) == (len, len, nheads, batch_size) | ||
|
||
@testset "self-attention" begin | ||
y1 = mha(q) | ||
y2 = mha(q, q, q) | ||
@test y1 ≈ y2 | ||
end | ||
|
||
@testset "key and value are the same" begin | ||
y1 = mha(q, k) | ||
y2 = mha(q, k, k) | ||
@test y1 ≈ y2 | ||
end | ||
|
||
@testset "change dims" begin | ||
dims = 4 => 10 => 5 | ||
nhead = 5 | ||
mha2 = MultiHeadAttention(dims; nheads) | ||
y2 = mha2(q, k, v) | ||
@test size(y2) == (dims.second.second, len, batch_size) | ||
end | ||
|
||
@testset "mask" begin | ||
mask = NNlib.make_causal_mask(q) | ||
y, α = mha(q; mask, withscores=true) | ||
@test all(α[2, 1, :, :] .== 0) | ||
@test α[:, :, 1, 1] ≈ triu(α[:, :, 1, 1]) | ||
end | ||
|
||
@testset "bias" begin | ||
# use bias to produce a causal mask | ||
b = zeros(Float32, (len, len)) | ||
for i in 1:len, j in i:len | ||
b[i, j] = typemax(Float32) | ||
end | ||
y, α = mha(q, k, v, b, withscores=true) | ||
@test all(α[2, 1, :, :] .== 0) | ||
@test α[:, :, 1, 1] ≈ triu(α[:, :, 1, 1]) | ||
end | ||
|
||
@testset "gradient" begin | ||
gm, gq = gradient(mha, q) do mha, q | ||
y, α = mha(q, withscores=true) | ||
return sum(y.^2) + sum(α.^2) | ||
end | ||
check_grad_type(gm, mha) | ||
check_grad_type(gq, q) | ||
end | ||
end | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.