I am trying to understand this piece of code (from here) which implements dot-product attention using matrix multiplication between two tensors. Specifically, the batch_dot() function from Keras backend is used between two tensors both with variable first dimension. batch_dot() seems to perform differently in this case as opposed to when the first dimension is specified.
MWE:
Fixed first dimension, works as expected
q = K.ones(shape=(36,8,24))
k = K.ones(shape=(36,8,24))
print(K.batch_dot(q,k,axes=[1,1]))
returns
Tensor("MatMul_8:0", shape=(?, 36, 24, 24), dtype=float32)
and,
print(K.batch_dot(q,k,axes=[2,2]))
returns
Tensor("MatMul_9:0", shape=(?, 36, 8, 8), dtype=float32)
However, defining q and k as follows:
q = Input(shape=(36,8,24))
k = Input(shape=(36,8,24))
print(q)
print(k)
(variable first dimension)
Tensor("input_24:0", shape=(?, 36, 8, 24), dtype=float32)
Tensor("input_25:0", shape=(?, 36, 8, 24), dtype=float32)
Output dimensions from batch_dot() operation is unexpected:
K.batch_dot(q,k,axes=[1,1])
<tf.Tensor 'MatMul_11:0' shape=(?, 36, 24, 24) dtype=float32>
K.batch_dot(q,k,axes=[2,2])
<tf.Tensor 'MatMul_12:0' shape=(?, 36, 24, 24) dtype=float32>
According to the documentation,arguments to axes specify the dimensions which get removed during the operation, however I am unable to connect this definition to the outputs above. Does the first dimension (with value ?) get counted for the arguments of axes?