def forward(self, queries, keys, values, mask=None):
# queries: (batch, no. of queries, num_hiddens); keys and values:
# (batch, no. of key-value pairs, num_hiddens). mask: boolean,
# broadcastable to (batch, no. of queries, no. of keys), shared by
# all heads, or to (batch, num_heads, no. of queries, no. of keys)
q = self.split_heads(self.W_q(queries), self.num_heads)
k = self.split_heads(self.W_k(keys), self.num_kv_heads)
v = self.split_heads(self.W_v(values), self.num_kv_heads)
group = self.num_heads // self.num_kv_heads
k, v = k.repeat_interleave(group, 1), v.repeat_interleave(group, 1)
if mask is not None and mask.dim() == 3:
mask = mask[:, None] # The same mask for every head
# Shape of Y: (batch, num_heads, no. of queries, head width)
Y = self.attention(q, k, v, mask)
return self.W_o(self.merge_heads(Y))
@property
def attention_weights(self):
"""Weights of the last call: (batch, num_heads, queries, keys)."""
return self.attention.attention_weights