MultiQueryAttention
MultiheadAttentionMultiQueryAttention(embed_dim: int, num_heads: int, dropout: float = 0.0, bias: bool = True, add_bias_kv: bool = False, add_zero_attn: bool = False, kdim: int | None = None, vdim: int | None = None, batch_first: bool = False, device: DeviceLike = None, dtype: DTypeLike = None)Multi-query attention — multi-head attention with a single key/value head.
A thin MultiheadAttention that fixes num_kv_heads = 1 (so it takes
no num_kv_heads argument): all num_heads query heads share one key/value
head — the extreme of grouped-query attention. This minimises the key/value
projection and, decisively, the K/V cache (one head's worth of K/V per layer
instead of num_heads), trading some quality for the smallest decode-memory
footprint. Exactly equivalent to MultiheadAttention(..., num_kv_heads=1)
(forward, shapes, and the KV-cache contract are inherited verbatim); this
subclass only reshapes the constructor for discoverability.
Parameters
embed_dimintnum_heads.num_headsintdropoutfloat= 0.0biasbool= TrueTrue, add a learnable bias to the input and output projections.add_bias_kvbool= FalseTrue, prepend a learnable bias row to the keys and values.add_zero_attnbool= FalseTrue, append a zero row to the keys and values so a query can attend
to "nothing".kdimint or None= Noneembed_dim.vdimint or None= Noneembed_dim.batch_firstbool= FalseTrue, inputs/outputs are (batch, seq, feature); otherwise
(seq, batch, feature).deviceDeviceLike= NonedtypeDTypeLike= NoneNotes
The single key/value head is projected once (k_proj_weight /
v_proj_weight of shape (head_dim, …)) and repeated num_heads times
via lucid.nn.functional.repeat_kv before the attention scores, so the
output is bit-identical to standard attention whose K/V heads are all tied.
Reference: Shazeer, "Fast Transformer Decoding: One Write-Head is All You Need", 2019 (arXiv:1911.02150).
Examples
>>> import lucid, lucid.nn as nn
>>> mqa = nn.MultiQueryAttention(embed_dim=512, num_heads=8, batch_first=True)
>>> mqa.num_kv_heads
1
>>> tuple(mqa.k_proj_weight.shape) # 1 K/V head × head_dim 64
(64, 512)Used by 1
Constructors
1__init__
→None__init__(embed_dim: int, num_heads: int, dropout: float = 0.0, bias: bool = True, add_bias_kv: bool = False, add_zero_attn: bool = False, kdim: int | None = None, vdim: int | None = None, batch_first: bool = False, device: DeviceLike = None, dtype: DTypeLike = None)Initialise multi-query attention (num_kv_heads = 1).