MultiheadAttention
¶
Bases: Module
Multi-head scaled dot-product attention with the semantics of
torch.nn.MultiheadAttention(..., batch_first=True).
Unlike mlx.nn.MultiHeadAttention, it has biases in all the
projections (as in PyTorch), a key_padding_mask and dropout on the
attention weights, which PyG's graph transformers (e.g.
GPSConv, the set transformer aggregations) rely on.
PyTorch packs the query, key and value projections in a single
in_proj_weight of shape [3 * dims, dims]; here they are the
separate query_proj, key_proj and value_proj layers (the
first, second and third block of in_proj_weight). The weights are
initialized as in PyTorch: Xavier uniform over the packed projection,
zero biases, and a PyTorch default out_proj weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
int
|
Size of the inputs and outputs ( |
required |
num_heads
|
int
|
Number of attention heads. |
required |
dropout
|
float
|
Dropout probability on the attention weights. Default: |
0.0
|
bias
|
bool
|
Whether the projections have a bias. Default: |
True
|
Example:
import mlx.core as mx
from mlx_graphs.nn.attention import MultiheadAttention
attn = MultiheadAttention(16, num_heads=4)
x = mx.random.normal((2, 5, 16))
mask = mx.array([[True] * 5, [True] * 3 + [False] * 2])
>>> attn(x, x, x, key_mask=mask).shape
(2, 5, 16)
Methods:
| Name | Description |
|---|---|
__call__ |
Computes the attention. |
Source code in mlx_graphs/nn/attention/multihead.py
__call__
¶
__call__(
queries: array, keys: array, values: array, key_mask: Optional[array] = None
) -> array
Computes the attention.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queries
|
array
|
Array of shape |
required |
keys
|
array
|
Array of shape |
required |
values
|
array
|
Array of shape |
required |
key_mask
|
Optional[array]
|
Optional boolean array of shape
|
None
|
Returns:
| Type | Description |
|---|---|
array
|
An array of shape |
Source code in mlx_graphs/nn/attention/multihead.py
from mlx_graphs.nn.attention import MultiheadAttention · mlx_graphs/nn/attention/multihead.py