Within the transformer units of BERT, there are modules called Query, Key, and Value, or simply Q,K,V.
Based on the BERT paper and code (particularly in modeling.py), my pseudocode understanding of the forward-pass of an attention module (using Q,K,V) with a single attention-head is as follows:
q_param = a matrix of learned parameters
k_param = a matrix of learned parameters
v_param = a matrix of learned parameters
d = one of the matrix dimensions (scalar value)
def attention(to_tensor, from_tensor, attention_mask):
q = from_tensor * q_param
k = to_tensor * k_param
v = to_tensor * v_param
attention_scores = q * transpose(k) / sqrt(d)
attention_scores += some_function(attention_mask) #attention_mask is usually just ones
attention_probs = dropout(softmax(attention_scores))
context = attention_probs * v
return context
Note that BERT uses "self-attention," so from_tensor and to_tensor are the same in BERT; I think both of these are simply the output from the previous layer.
Questions
- Why are the matrices called Query, Key, and Value?
- Did I make any mistakes in my pseudocode representation of the algorithm?