# Compute q, k, v
kqv = tf.layers.conv2d(inputs, 2 dk + dv, 1)
k, q, v = tf.split(kqv, [dk, dk, dv], axis=3)
q= dkh   0.5 # scaled dot product
# After splitting, shape is [B, Nh, H, W, dkh or dvh]
q = split heads 2d(q, Nh)
k = split heads 2d(k, Nh)
v = split heads 2d(v, Nh)
# [B, Nh, HW, HW]
logits = tf.matmul(flatten hw(q, dkh), flatten hw(k, dkh),
transpose b=True)
if relative:
rellogits h, rel logits w = relative logits(q, H, W, Nh,
dkh)
logits += rel logits h
logits += rel logits w
weights = tf.nn.softmax(logits)
attn out = tf.matmul(weights, flatten hw(v, dvh))
Convolutional networks have been the paradigm of choice in many computer
vision applications. The convolution operation however has a significant
weakness in that it only operates on a local neighborhood, thus missing global
information. Self-attention, on the other hand, has emerged as a recent advance
to capture long range interactions, but has mostly been applied to sequence
modeling and generative modeling tasks. In this paper, we consider the use of
self-attention for discriminative visual tasks as an alternative to
convolutions. We introduce a novel two-dimensional relative self-attention
mechanism that proves competitive in replacing convolutions as a stand-alone
computational primitive for image classification. We find in control
experiments that the best results are obtained when combining both convolutions
and self-attention. We therefore propose to augment convolutional operators
with this self-attention mechanism by concatenating convolutional feature maps
with a set of feature maps produced via self-attention. Extensive experiments
show that Attention Augmentation leads to consistent improvements in image
classification on ImageNet and object detection on COCO across many different
models and scales, including ResNets and a state-of-the art mobile constrained
network, while keeping the number of parameters similar. In particular, our
method achieves a $1.3\%$ top-1 accuracy improvement on ImageNet classification
over a ResNet50 baseline and outperforms other attention mechanisms for images
such as Squeeze-and-Excitation. It also achieves an improvement of 1.4 mAP in
COCO Object Detection on top of a RetinaNet baseline.
Irwan Bello Barret Zoph Ashish Vaswani Jonathon Shlens Quoc V. Le