"doc/doc_en/training_en.md" did not exist on "f09d1f730b71a9b220cceec14a765c24cd9c1d6f"
attention.py 21.1 KB
Newer Older
Hongkun Yu's avatar
Hongkun Yu committed
1
# Lint as: python3
Hongkun Yu's avatar
Hongkun Yu committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Keras-based attention layer."""
17
# pylint: disable=g-classes-have-attributes
Hongkun Yu's avatar
Hongkun Yu committed
18
19
20
21
22
from __future__ import absolute_import
from __future__ import division
# from __future__ import google_type_annotations
from __future__ import print_function

Hongkun Yu's avatar
Hongkun Yu committed
23
import collections
Hongkun Yu's avatar
Hongkun Yu committed
24
import math
Hongkun Yu's avatar
Hongkun Yu committed
25
26
27
import string

import numpy as np
Hongkun Yu's avatar
Hongkun Yu committed
28
29
30
31
import tensorflow as tf

from official.nlp.modeling.layers import masked_softmax

Hongkun Yu's avatar
Hongkun Yu committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
EinsumDense = tf.keras.layers.experimental.EinsumDense
_CHR_IDX = string.ascii_lowercase


def _build_attention_equation(qkv_rank, attn_axes):
  """Builds einsum equations for the attention computation.

  Query, key, value inputs after projection are expected to have the shape as:
  (bs, <non-attention dims>, <attention dims>, num_heads, channels).
  bs and <non-attention dims> are treated as <batch dims>.
  The attention operations can be generalized:
  (1) Query-key dot product:
  (<batch dims>, <query attention dims>, num_heads, channels), (<batch dims>,
  <key attention dims>, num_heads, channels) -> (<batch dims>,
  num_heads, <query attention dims>, <key attention dims>)
  (2) Combination:
  (<batch dims>, num_heads, <query attention dims>, <key attention dims>),
  (<batch dims>, <value attention dims>, num_heads, channels) -> (<batch dims>,
  <query attention dims>, num_heads, channels)

  Args:
    qkv_rank: the rank of query, key, value tensors.
    attn_axes: a list/tuple of axes, [1, rank), that will do attention.
55

Hongkun Yu's avatar
Hongkun Yu committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  Returns:
    Einsum equations.
  """
  target_notation = _CHR_IDX[:qkv_rank]
  # `batch_dims` includes the head dim.
  batch_dims = tuple(np.delete(range(qkv_rank), attn_axes + (qkv_rank - 1,)))
  letter_offset = qkv_rank
  source_notation = ""
  for i in range(qkv_rank):
    if i in batch_dims or i == qkv_rank - 1:
      source_notation += target_notation[i]
    else:
      source_notation += _CHR_IDX[letter_offset]
      letter_offset += 1

  product_notation = "".join([target_notation[i] for i in batch_dims] +
                             [target_notation[i] for i in attn_axes] +
                             [source_notation[i] for i in attn_axes])
  dot_product_equation = "%s,%s->%s" % (source_notation, target_notation,
                                        product_notation)
76
  attn_scores_rank = len(product_notation)
Hongkun Yu's avatar
Hongkun Yu committed
77
78
  combine_equation = "%s,%s->%s" % (product_notation, source_notation,
                                    target_notation)
79
  return dot_product_equation, combine_equation, attn_scores_rank
Hongkun Yu's avatar
Hongkun Yu committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107


def _build_proj_equation(free_dims, bound_dims, output_dims):
  """Builds an einsum equation for projections inside multi-head attention."""
  input_str = ""
  kernel_str = ""
  output_str = ""
  bias_axes = ""
  letter_offset = 0
  for i in range(free_dims):
    char = _CHR_IDX[i + letter_offset]
    input_str += char
    output_str += char

  letter_offset += free_dims
  for i in range(bound_dims):
    char = _CHR_IDX[i + letter_offset]
    input_str += char
    kernel_str += char

  letter_offset += bound_dims
  for i in range(output_dims):
    char = _CHR_IDX[i + letter_offset]
    kernel_str += char
    output_str += char
    bias_axes += char
  equation = "%s,%s->%s" % (input_str, kernel_str, output_str)

108
  return equation, bias_axes, len(output_str)
Hongkun Yu's avatar
Hongkun Yu committed
109
110
111
112
113


def _get_output_shape(output_rank, known_last_dims):
  return [None] * (output_rank - len(known_last_dims)) + list(known_last_dims)

Hongkun Yu's avatar
Hongkun Yu committed
114
115

@tf.keras.utils.register_keras_serializable(package="Text")
116
117
class MultiHeadAttention(tf.keras.layers.Layer):
  """MultiHeadAttention layer.
Hongkun Yu's avatar
Hongkun Yu committed
118
119

  This is an implementation of multi-headed attention based on "Attention
Hongkun Yu's avatar
Hongkun Yu committed
120
121
122
  is all you Need". If `query`, `key,` `value` are the same, then
  this is self-attention. Each timestep in `query` attends to the
  corresponding sequence in `key`, and returns a fixed-width vector.
Hongkun Yu's avatar
Hongkun Yu committed
123

Hongkun Yu's avatar
Hongkun Yu committed
124
125
  This layer first projects `query`, `key` and `value`. These are
  (effectively) a list of tensors of length `num_attention_heads`, where the
126
127
128
  corresponding shapes are [batch_size, <query dimensions>, key_size],
  [batch_size, <key/value dimensions>, key_size],
  [batch_size, <key/value dimensions>, value_size].
Hongkun Yu's avatar
Hongkun Yu committed
129
130
131
132

  Then, the query and key tensors are dot-producted and scaled. These are
  softmaxed to obtain attention probabilities. The value tensors are then
  interpolated by these probabilities, then concatenated back to a single
Hongkun Yu's avatar
Hongkun Yu committed
133
134
135
136
  tensor.

  Finally, the result tensor with the last dimension as value_size can take an
  linear projection and return.
Hongkun Yu's avatar
Hongkun Yu committed
137

138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
  Examples:

  Performs 1D cross-attention over two sequence inputs with an attention mask.
  Returns the additional attention weights over heads.

  >>> layer = MultiHeadAttention(num_heads=2, key_size=2,
  ...                            return_attention_scores=True)
  >>> target = tf.keras.Input(shape=[8, 16])
  >>> source = tf.keras.Input(shape=[4, 16])
  >>> mask_tensor = tf.keras.Input(shape=[8, 4])
  >>> output_tensor, weights = layer([input_tensor, input_tensor])
  >>> print(output_tensor.shape), print(weights.shape)
  (None, 8, 16)  (None, 2, 8, 4)

  Performs 2D self-attention over a 5D input tensor on axes 2 and 3.

  >>> layer = MultiHeadAttention(num_heads=2, key_size=2, attention_axes=(2, 3))
  >>> input_tensor = tf.keras.Input(shape=[5, 3, 4, 16])
  >>> output_tensor = layer([input_tensor, input_tensor])
  >>> print(output_tensor.shape)
  (None, 5, 3, 4, 16)

160
  Arguments:
Hongkun Yu's avatar
Hongkun Yu committed
161
    num_heads: Number of attention heads.
Hongkun Yu's avatar
Hongkun Yu committed
162
163
    key_size: Size of each attention head for query and key.
    value_size:  Size of each attention head for value.
Hongkun Yu's avatar
Hongkun Yu committed
164
    dropout: Dropout probability.
Hongkun Yu's avatar
Hongkun Yu committed
165
    use_bias: Boolean, whether the dense layers use bias vectors/matrices.
Hongkun Yu's avatar
Hongkun Yu committed
166
167
    output_shape: The expected shape of an output tensor, besides the batch and
      sequence dims. If not specified, projects back to the key feature dim.
168
169
170
171
    attention_axes: axes over which the attention is applied. `None` means
      attention over all axes, but batch, heads, and features.
    return_attention_scores: bool, if `True`, returns the multi-head
      attention scores as an additional output argument.
Hongkun Yu's avatar
Hongkun Yu committed
172
173
174
175
176
177
178
179
180
181
182
    kernel_initializer: Initializer for dense layer kernels.
    bias_initializer: Initializer for dense layer biases.
    kernel_regularizer: Regularizer for dense layer kernels.
    bias_regularizer: Regularizer for dense layer biases.
    activity_regularizer: Regularizer for dense layer activity.
    kernel_constraint: Constraint for dense layer kernels.
    bias_constraint: Constraint for dense layer kernels.
  """

  def __init__(self,
               num_heads,
Hongkun Yu's avatar
Hongkun Yu committed
183
184
               key_size,
               value_size=None,
185
               dropout=0.0,
Hongkun Yu's avatar
Hongkun Yu committed
186
187
               use_bias=True,
               output_shape=None,
188
189
               attention_axes=None,
               return_attention_scores=False,
Hongkun Yu's avatar
Hongkun Yu committed
190
191
192
193
194
195
196
197
               kernel_initializer="glorot_uniform",
               bias_initializer="zeros",
               kernel_regularizer=None,
               bias_regularizer=None,
               activity_regularizer=None,
               kernel_constraint=None,
               bias_constraint=None,
               **kwargs):
198
    super(MultiHeadAttention, self).__init__(**kwargs)
Hongkun Yu's avatar
Hongkun Yu committed
199
    self._num_heads = num_heads
Hongkun Yu's avatar
Hongkun Yu committed
200
201
    self._key_size = key_size
    self._value_size = value_size if value_size else key_size
202
    self._dropout = dropout
Hongkun Yu's avatar
Hongkun Yu committed
203
204
    self._use_bias = use_bias
    self._output_shape = output_shape
205
    self._return_attention_scores = return_attention_scores
Hongkun Yu's avatar
Hongkun Yu committed
206
207
208
209
210
211
    self._kernel_initializer = tf.keras.initializers.get(kernel_initializer)
    self._bias_initializer = tf.keras.initializers.get(bias_initializer)
    self._kernel_regularizer = tf.keras.regularizers.get(kernel_regularizer)
    self._bias_regularizer = tf.keras.regularizers.get(bias_regularizer)
    self._kernel_constraint = tf.keras.constraints.get(kernel_constraint)
    self._bias_constraint = tf.keras.constraints.get(bias_constraint)
212
213
214
215
216
    if attention_axes is not None and not isinstance(attention_axes,
                                                     collections.abc.Sized):
      self._attention_axes = (attention_axes,)
    else:
      self._attention_axes = attention_axes
Hongkun Yu's avatar
Hongkun Yu committed
217
218
219
220
221

  def get_config(self):
    config = {
        "num_heads":
            self._num_heads,
Hongkun Yu's avatar
Hongkun Yu committed
222
223
224
225
        "key_size":
            self._key_size,
        "value_size":
            self._value_size,
226
227
        "dropout":
            self._dropout,
Hongkun Yu's avatar
Hongkun Yu committed
228
229
230
231
        "use_bias":
            self._use_bias,
        "output_shape":
            self._output_shape,
232
233
234
235
        "attention_axes":
            self._attention_axes,
        "return_attention_scores":
            self._return_attention_scores,
Hongkun Yu's avatar
Hongkun Yu committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
        "kernel_initializer":
            tf.keras.initializers.serialize(self._kernel_initializer),
        "bias_initializer":
            tf.keras.initializers.serialize(self._bias_initializer),
        "kernel_regularizer":
            tf.keras.regularizers.serialize(self._kernel_regularizer),
        "bias_regularizer":
            tf.keras.regularizers.serialize(self._bias_regularizer),
        "activity_regularizer":
            tf.keras.regularizers.serialize(self._activity_regularizer),
        "kernel_constraint":
            tf.keras.constraints.serialize(self._kernel_constraint),
        "bias_constraint":
            tf.keras.constraints.serialize(self._bias_constraint)
    }
251
    base_config = super(MultiHeadAttention, self).get_config()
Hongkun Yu's avatar
Hongkun Yu committed
252
253
    return dict(list(base_config.items()) + list(config.items()))

Hongkun Yu's avatar
Hongkun Yu committed
254
  def build(self, input_shape):
Hongkun Yu's avatar
Hongkun Yu committed
255
256
257
258
259
260
261
262
263
264
265
266
    inputs_len = len(input_shape)
    if inputs_len > 3 or inputs_len < 2:
      raise ValueError(
          "Expects inputs list of length 2 or 3, namely [query, value] or "
          "[query, value, key]. "
          "Given length: %d" % inputs_len)
    tensor_shapes = tf.nest.map_structure(tf.TensorShape, input_shape)
    query_shape = tensor_shapes[0]
    value_shape = tensor_shapes[1]
    key_shape = tensor_shapes[2] if inputs_len == 3 else value_shape

    common_kwargs = dict(
Hongkun Yu's avatar
Hongkun Yu committed
267
268
269
270
271
272
        kernel_initializer=self._kernel_initializer,
        bias_initializer=self._bias_initializer,
        kernel_regularizer=self._kernel_regularizer,
        bias_regularizer=self._bias_regularizer,
        activity_regularizer=self._activity_regularizer,
        kernel_constraint=self._kernel_constraint,
Hongkun Yu's avatar
Hongkun Yu committed
273
274
275
276
277
278
279
        bias_constraint=self._bias_constraint)

    free_dims = query_shape.rank - 1
    einsum_equation, bias_axes, output_rank = _build_proj_equation(
        free_dims, bound_dims=1, output_dims=2)
    self._query_dense = EinsumDense(
        einsum_equation,
280
        output_shape=_get_output_shape(output_rank - 1,
Hongkun Yu's avatar
Hongkun Yu committed
281
282
283
284
285
286
287
288
                                       [self._num_heads, self._key_size]),
        bias_axes=bias_axes if self._use_bias else None,
        name="query",
        **common_kwargs)
    einsum_equation, bias_axes, output_rank = _build_proj_equation(
        key_shape.rank - 1, bound_dims=1, output_dims=2)
    self._key_dense = EinsumDense(
        einsum_equation,
289
        output_shape=_get_output_shape(output_rank - 1,
Hongkun Yu's avatar
Hongkun Yu committed
290
291
292
293
294
295
296
297
                                       [self._num_heads, self._key_size]),
        bias_axes=bias_axes if self._use_bias else None,
        name="key",
        **common_kwargs)
    einsum_equation, bias_axes, output_rank = _build_proj_equation(
        value_shape.rank - 1, bound_dims=1, output_dims=2)
    self._value_dense = EinsumDense(
        einsum_equation,
298
        output_shape=_get_output_shape(output_rank - 1,
Hongkun Yu's avatar
Hongkun Yu committed
299
300
301
302
303
                                       [self._num_heads, self._value_size]),
        bias_axes=bias_axes if self._use_bias else None,
        name="value",
        **common_kwargs)

304
305
306
307
    # Builds the attention computations for multi-head dot product attention.
    # These computations could be wrapped into the keras attention layer once it
    # support mult-head einsum computations.
    self._build_attention(output_rank)
Hongkun Yu's avatar
Hongkun Yu committed
308
309
310
311
312
313
314
315
316
317
318
    if self._output_shape:
      if not isinstance(self._output_shape, collections.abc.Sized):
        output_shape = [self._output_shape]
      else:
        output_shape = self._output_shape
    else:
      output_shape = [query_shape[-1]]
    einsum_equation, bias_axes, output_rank = _build_proj_equation(
        free_dims, bound_dims=2, output_dims=len(output_shape))
    self._output_dense = EinsumDense(
        einsum_equation,
319
        output_shape=_get_output_shape(output_rank - 1, output_shape),
Hongkun Yu's avatar
Hongkun Yu committed
320
321
322
        bias_axes=bias_axes if self._use_bias else None,
        name="attention_output",
        **common_kwargs)
Hongkun Yu's avatar
Hongkun Yu committed
323
324
    super(MultiHeadAttention, self).build(input_shape)

325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
  def _build_attention(self, qkv_rank):
    """Builds multi-head dot-product attention computations.

    This function builds attributes necessary for `_compute_attention` to
    costomize attention computation to replace the default dot-product
    attention.

    Args:
      qkv_rank: the rank of query, key, value tensors.
    """
    if self._attention_axes is None:
      self._attention_axes = tuple(range(1, qkv_rank - 2))
    else:
      self._attention_axes = tuple(self._attention_axes)
    self._dot_product_equation, self._combine_equation, attn_scores_rank = (
        _build_attention_equation(qkv_rank, attn_axes=self._attention_axes))
    norm_axes = tuple(
        range(attn_scores_rank - len(self._attention_axes), attn_scores_rank))
    self._masked_softmax = masked_softmax.MaskedSoftmax(
        mask_expansion_axes=[1], normalization_axes=norm_axes)
    self._dropout_layer = tf.keras.layers.Dropout(rate=self._dropout)

  def _compute_attention(self,
                         query_tensor,
                         key_tensor,
                         value_tensor,
                         attention_mask=None):
    """Applies Dot-product attention with query, key, value tensors.

    This function defines the computation inside `call` with projected
    multi-head Q, K, V inputs. Users can override this function for customized
    attention implementation.

    Args:
      query_tensor: Projected query `Tensor` of shape `[B, T, N, key_size]`.
      key_tensor: Projected key `Tensor` of shape `[B, T, N, key_size]`.
      value_tensor: Projected value `Tensor` of shape `[B, T, N, value_size]`.
      attention_mask: a boolean mask of shape `[B, T, S]`, that prevents
        attention to certain positions.

    Returns:
      attention_output: Multi-headed outputs of attention computation.
      attention_scores: Multi-headed attention weights.
    """
    # Take the dot product between "query" and "key" to get the raw
    # attention scores.
    attention_scores = tf.einsum(self._dot_product_equation, key_tensor,
                                 query_tensor)
    attention_scores = tf.multiply(attention_scores,
                                   1.0 / math.sqrt(float(self._key_size)))

    # Normalize the attention scores to probabilities.
    # `attention_scores` = [B, N, T, S]
    attention_scores = self._masked_softmax([attention_scores, attention_mask])

    # This is actually dropping out entire tokens to attend to, which might
    # seem a bit unusual, but is taken from the original Transformer paper.
    attention_scores_dropout = self._dropout_layer(attention_scores)

    # `context_layer` = [B, T, N, H]
    attention_output = tf.einsum(self._combine_equation,
                                 attention_scores_dropout, value_tensor)
    return attention_output, attention_scores

Hongkun Yu's avatar
Hongkun Yu committed
389
390
391
392
393
394
395
396
  def call(self, inputs, attention_mask=None):
    """Implements the forward pass.

    Size glossary:
      * Number of heads (H): the number of attention heads.
      * Value size (V): the size of each value embedding per head.
      * Key size (K): the size of each key embedding per head. Equally, the size
          of each query embedding per head. Typically K <= V.
397
398
399
      * Batch dimensions (B).
      * Query (target) attention axes shape (T).
      * Value (source) attention axes shape (S), the rank must match the target.
Hongkun Yu's avatar
Hongkun Yu committed
400
401
402
403
404
405
406
407
408
409
410

    Args:
      inputs: List of the following tensors:
        * query: Query `Tensor` of shape `[B, T, dim]`.
        * value: Value `Tensor` of shape `[B, S, dim]`.
        * key: Optional key `Tensor` of shape `[B, S, dim]`. If not given, will
          use `value` for both `key` and `value`, which is the most common case.
      attention_mask: a boolean mask of shape `[B, T, S]`, that prevents
        attention to certain positions.

    Returns:
411
412
413
414
415
416
417
      attention_output: The result of the computation, of shape [B, T, E],
        where `T` is for target sequence shapes and `E` is the query input last
        dimension if `output_shape` is `None`. Otherwise, the multi-head outputs
        are project to the shape specified by `output_shape`.
      attention_scores: [Optional] multi-head attention coeffients over
      attention
        axes.
Hongkun Yu's avatar
Hongkun Yu committed
418
419
420
421
422
423
424
425
426
427
    """
    inputs_len = len(inputs)
    if inputs_len > 3 or inputs_len < 2:
      raise ValueError(
          "Expects inputs list of length 2 or 3, namely [query, value] or "
          "[query, value, key]. "
          "Given length: %d" % inputs_len)
    query = inputs[0]
    value = inputs[1]
    key = inputs[2] if inputs_len == 3 else value
Hongkun Yu's avatar
Hongkun Yu committed
428
429
430

    #   N = `num_attention_heads`
    #   H = `size_per_head`
Hongkun Yu's avatar
Hongkun Yu committed
431
432
    # `query_tensor` = [B, T, N ,H]
    query_tensor = self._query_dense(query)
Hongkun Yu's avatar
Hongkun Yu committed
433

Hongkun Yu's avatar
Hongkun Yu committed
434
435
    # `key_tensor` = [B, S, N, H]
    key_tensor = self._key_dense(key)
Hongkun Yu's avatar
Hongkun Yu committed
436

Hongkun Yu's avatar
Hongkun Yu committed
437
438
    # `value_tensor` = [B, S, N, H]
    value_tensor = self._value_dense(value)
Hongkun Yu's avatar
Hongkun Yu committed
439

440
441
    attention_output, attention_scores = self._compute_attention(
        query_tensor, key_tensor, value_tensor, attention_mask)
Hongkun Yu's avatar
Hongkun Yu committed
442
    attention_output = self._output_dense(attention_output)
443
444
445

    if self._return_attention_scores:
      return attention_output, attention_scores
Hongkun Yu's avatar
Hongkun Yu committed
446
    return attention_output
447
448
449


@tf.keras.utils.register_keras_serializable(package="Text")
450
class CachedAttention(MultiHeadAttention):
451
452
  """Attention layer with cache used for auto-agressive decoding.

453
  Arguments are the same as `MultiHeadAttention` layer.
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
  """

  def _update_cache(self, key_tensor, value_tensor, cache, decode_loop_step):
    """Updates cache states and gets full-length key/value tensors."""
    # Combines cached keys and values with new keys and values.
    if decode_loop_step is not None:
      # TPU special case.
      key_seq_dim = cache["key"].shape.as_list()[1]
      indices = tf.reshape(
          tf.one_hot(decode_loop_step, key_seq_dim, dtype=key_tensor.dtype),
          [1, key_seq_dim, 1, 1])
      key_tensor = cache["key"] + key_tensor * indices
      value_seq_dim = cache["value"].shape.as_list()[1]
      indices = tf.reshape(
          tf.one_hot(decode_loop_step, value_seq_dim, dtype=value_tensor.dtype),
          [1, value_seq_dim, 1, 1])
      value_tensor = cache["value"] + value_tensor * indices
    else:
      key_tensor = tf.concat(
          [tf.cast(cache["key"], key_tensor.dtype), key_tensor], axis=1)
      value_tensor = tf.concat(
          [tf.cast(cache["value"], value_tensor.dtype), value_tensor], axis=1)

    # Update cache
    cache["key"] = key_tensor
    cache["value"] = value_tensor

    return key_tensor, value_tensor

Hongkun Yu's avatar
Hongkun Yu committed
483
484
485
486
487
  def call(self,
           inputs,
           attention_mask=None,
           cache=None,
           decode_loop_step=None):
488
489
    from_tensor = inputs[0]
    to_tensor = inputs[1]
Hongkun Yu's avatar
Hongkun Yu committed
490

491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
    # Scalar dimensions referenced here:
    #   B = batch size (number of sequences)
    #   F = `from_tensor` sequence length
    #   T = `to_tensor` sequence length
    #   N = `num_attention_heads`
    #   H = `size_per_head`
    # `query_tensor` = [B, F, N ,H]
    query_tensor = self._query_dense(from_tensor)

    # `key_tensor` = [B, T, N, H]
    key_tensor = self._key_dense(to_tensor)

    # `value_tensor` = [B, T, N, H]
    value_tensor = self._value_dense(to_tensor)

    if cache:
      key_tensor, value_tensor = self._update_cache(key_tensor, value_tensor,
                                                    cache, decode_loop_step)

    # Take the dot product between "query" and "key" to get the raw
    # attention scores.
Hongkun Yu's avatar
Hongkun Yu committed
512
513
    attention_scores = tf.einsum(self._dot_product_equation, key_tensor,
                                 query_tensor)
514
    attention_scores = tf.multiply(attention_scores,
Hongkun Yu's avatar
Hongkun Yu committed
515
                                   1.0 / math.sqrt(float(self._key_size)))
516
517

    # Normalize the attention scores to probabilities.
518
519
    # `attention_scores` = [B, N, F, T]
    attention_scores = self._masked_softmax([attention_scores, attention_mask])
520
521
522

    # This is actually dropping out entire tokens to attend to, which might
    # seem a bit unusual, but is taken from the original Transformer paper.
523
    attention_scores = self._dropout_layer(attention_scores)
524
    # `context_layer` = [B, F, N, H]
525
    attention_output = tf.einsum(self._combine_equation, attention_scores,
Hongkun Yu's avatar
Hongkun Yu committed
526
527
                                 value_tensor)
    attention_output = self._output_dense(attention_output)
528
529
    if self._return_attention_scores:
      return attention_output, attention_scores, cache
Hongkun Yu's avatar
Hongkun Yu committed
530
    return attention_output, cache