MCPcopy Create free account
hub / github.com/ddbourgin/numpy-ml / MultiHeadedAttentionModule

Class MultiHeadedAttentionModule

numpy_ml/neural_nets/modules/modules.py:1192–1427  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1190
1191
1192class MultiHeadedAttentionModule(ModuleBase):
1193 def __init__(self, n_heads=8, dropout_p=0, init="glorot_uniform", optimizer=None):
1194 """
1195 A mutli-headed attention module.
1196
1197 Notes
1198 -----
1199 Multi-head attention allows a model to jointly attend to information from
1200 different representation subspaces at different positions. With a
1201 single head, this information would get averaged away when the
1202 attention weights are combined with the value
1203
1204 .. math::
1205
1206 \\text{MultiHead}(\mathbf{Q}, \mathbf{K}, \mathbf{V})
1207 = [\\text{head}_1; ...; \\text{head}_h] \\mathbf{W}^{(O)}
1208
1209 where
1210
1211 .. math::
1212
1213 \\text{head}_i = \\text{SDP_attention}(
1214 \mathbf{Q W}_i^{(Q)}, \mathbf{K W}_i^{(K)}, \mathbf{V W}_i^{(V)})
1215
1216 and the projection weights are parameter matrices:
1217
1218 .. math::
1219
1220 \mathbf{W}_i^{(Q)} &\in
1221 \mathbb{R}^{(\\text{kqv_dim} \ \\times \ \\text{latent_dim})} \\\\
1222 \mathbf{W}_i^{(K)} &\in
1223 \mathbb{R}^{(\\text{kqv_dim} \ \\times \ \\text{latent_dim})} \\\\
1224 \mathbf{W}_i^{(V)} &\in
1225 \mathbb{R}^{(\\text{kqv_dim} \ \\times \ \\text{latent_dim})} \\\\
1226 \mathbf{W}^{(O)} &\in
1227 \mathbb{R}^{(\\text{n_heads} \cdot \\text{latent_dim} \ \\times \ \\text{kqv_dim})}
1228
1229 Importantly, the current module explicitly assumes that
1230
1231 .. math::
1232
1233 \\text{kqv_dim} = \\text{dim(query)} = \\text{dim(keys)} = \\text{dim(values)}
1234
1235 and that
1236
1237 .. math::
1238
1239 \\text{latent_dim} = \\text{kqv_dim / n_heads}
1240
1241 **[MH Attention Head h]**:
1242
1243 .. code-block:: text
1244
1245 K --> W_h^(K) ------\\
1246 V --> W_h^(V) ------- > DP_Attention --> head_h
1247 Q --> W_h^(Q) ------/
1248
1249 The full **[MultiHeadedAttentionModule]** then becomes

Callers 1

Calls

no outgoing calls

Tested by 1