Qiu and colleagues add one small step to a standard attention layer. After a head has mixed the values with its softmax weights, the result is multiplied by a gate computed from the hidden state of the token that is doing the attending. Implement a causal multi-head attention layer with this gate, in the three forms the paper compares.
gated_attention(X, W_Q, W_K, W_V, W_O, W_theta, granularity="elementwise", shared=False)
X has shape , one row per token in order.W_Q, W_K, W_V have shape : one projection per head. For head , , , .granularity="elementwise": W_theta has shape . Columns to belong to head , so token gets a score vector of length for every head.granularity="headwise": W_theta has shape . Column gives one scalar per token that scales the whole output of head .shared=True (elementwise only): compute the elementwise scores, then average them over the heads. Every head uses that same average vector.W_O, shape .Return (O, score): O is the layer output, a NumPy array of shape ; score is the array of scores that was applied, of shape for elementwise (with shared=True all slices are equal) and for headwise.
ValueError for an unknown granularity, and for shared=True with granularity="headwise".