|
| 1 | +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# ============================================================================== |
| 15 | +"""Implementation of multiheaded attention and self-attention layers.""" |
| 16 | + |
| 17 | +from __future__ import absolute_import |
| 18 | +from __future__ import division |
| 19 | +from __future__ import print_function |
| 20 | + |
| 21 | +import tensorflow as tf |
| 22 | +import tensorlayer as tl |
| 23 | + |
| 24 | + |
| 25 | +class MultiHeadAttentionLayer(tl.layers.Layer): |
| 26 | + """Multi-headed attention layer.""" |
| 27 | + |
| 28 | + def __init__(self, num_heads, hidden_size, keep_prob): |
| 29 | + """Initialize Attention. |
| 30 | +
|
| 31 | + Args: |
| 32 | + hidden_size: int, output dim of hidden layer. |
| 33 | + num_heads: int, number of heads to repeat the same attention structure. |
| 34 | + keep_prob: float, keep rate for dropout mechanism inside attention for training. |
| 35 | + """ |
| 36 | + if hidden_size % num_heads: |
| 37 | + raise ValueError( |
| 38 | + "Hidden size ({}) must be divisible by the number of heads ({}).".format(hidden_size, num_heads) |
| 39 | + ) |
| 40 | + |
| 41 | + super(MultiHeadAttentionLayer, self).__init__() |
| 42 | + self.hidden_size = hidden_size |
| 43 | + self.num_heads = num_heads |
| 44 | + self.attention_dropout = 1 - keep_prob |
| 45 | + |
| 46 | + self.build(None) |
| 47 | + self._built = True |
| 48 | + |
| 49 | + def get_config(self): |
| 50 | + return { |
| 51 | + "hidden_size": self.hidden_size, |
| 52 | + "num_heads": self.num_heads, |
| 53 | + "attention_dropout": self.attention_dropout, |
| 54 | + } |
| 55 | + |
| 56 | + def build(self, inputs_shape): |
| 57 | + # Transformation for linearly projecting the queries, keys, and values. |
| 58 | + self.q_transformation = self._get_weights( |
| 59 | + "q_project", shape=(self.hidden_size, self.hidden_size), init=tf.keras.initializers.get('glorot_uniform') |
| 60 | + ) |
| 61 | + self.v_transformation = self._get_weights( |
| 62 | + "v_project", shape=(self.hidden_size, self.hidden_size), init=tf.keras.initializers.get('glorot_uniform') |
| 63 | + ) |
| 64 | + self.k_transformation = self._get_weights( |
| 65 | + "k_project", shape=(self.hidden_size, self.hidden_size), init=tf.keras.initializers.get('glorot_uniform') |
| 66 | + ) |
| 67 | + self.out_transformation = self._get_weights( |
| 68 | + "out_project", shape=(self.hidden_size, self.hidden_size), init=tf.keras.initializers.get('glorot_uniform') |
| 69 | + ) |
| 70 | + |
| 71 | + def split_heads(self, x): |
| 72 | + """Split x into different heads, and transpose the resulting value. |
| 73 | +
|
| 74 | + The tensor is transposed to insure the inner dimensions hold the correct |
| 75 | + values during the matrix multiplication. |
| 76 | +
|
| 77 | + Args: |
| 78 | + x: A tensor with shape [batch_size, length, hidden_size] |
| 79 | +
|
| 80 | + Returns: |
| 81 | + A tensor with shape [batch_size, num_heads, length, hidden_size/num_heads] |
| 82 | + """ |
| 83 | + with tf.name_scope("split_heads"): |
| 84 | + batch_size = tf.shape(x)[0] |
| 85 | + length = tf.shape(x)[1] |
| 86 | + |
| 87 | + # Calculate depth of last dimension after it has been split. |
| 88 | + depth = (self.hidden_size // self.num_heads) |
| 89 | + |
| 90 | + # Split the last dimension |
| 91 | + x = tf.reshape(x, [batch_size, length, self.num_heads, depth]) |
| 92 | + |
| 93 | + # Transpose the result |
| 94 | + return tf.transpose(x, [0, 2, 1, 3]) |
| 95 | + |
| 96 | + def combine_heads(self, x): |
| 97 | + """Combine tensor that has been split. |
| 98 | +
|
| 99 | + Args: |
| 100 | + x: A tensor [batch_size, num_heads, length, hidden_size/num_heads] |
| 101 | +
|
| 102 | + Returns: |
| 103 | + A tensor with shape [batch_size, length, hidden_size] |
| 104 | + """ |
| 105 | + with tf.name_scope("combine_heads"): |
| 106 | + batch_size = tf.shape(x)[0] |
| 107 | + length = tf.shape(x)[2] |
| 108 | + x = tf.transpose(x, [0, 2, 1, 3]) # --> [batch, length, num_heads, depth] |
| 109 | + return tf.reshape(x, [batch_size, length, self.hidden_size]) |
| 110 | + |
| 111 | + def forward(self, inputs, mask, cache=None): |
| 112 | + """Apply attention mechanism to x and y. |
| 113 | +
|
| 114 | + Args: |
| 115 | + x: a tensor with shape [batch_size, length_x, hidden_size] |
| 116 | + y: a tensor with shape [batch_size, length_y, hidden_size] |
| 117 | + mask: attention bias that will be added to the result of the dot product. |
| 118 | + training: boolean, whether in training mode or not. |
| 119 | + cache: (Used during prediction) dictionary with tensors containing results |
| 120 | + of previous attentions. The dictionary must have the items: |
| 121 | + {"k": tensor with shape [batch_size, i, key_channels], |
| 122 | + "v": tensor with shape [batch_size, i, value_channels]} |
| 123 | + where i is the current decoded length. |
| 124 | +
|
| 125 | + Returns: |
| 126 | + Attention layer output with shape [batch_size, length_x, hidden_size] |
| 127 | + """ |
| 128 | + # Linearly project the query (q), key (k) and value (v) using different |
| 129 | + # learned projections. This is in preparation of splitting them into |
| 130 | + # multiple heads. Multi-head attention uses multiple queries, keys, and |
| 131 | + # values rather than regular attention (which uses a single q, k, v). |
| 132 | + |
| 133 | + if (len(inputs) == 2): |
| 134 | + q = inputs[0] |
| 135 | + k = v = inputs[1] |
| 136 | + |
| 137 | + if (len(inputs) == 3): |
| 138 | + q = inputs[0] |
| 139 | + k = inputs[1] |
| 140 | + v = inputs[2] |
| 141 | + |
| 142 | + q = tf.tensordot(q, self.q_transformation, axes=[[2], [0]]) |
| 143 | + k = tf.tensordot(k, self.k_transformation, axes=[[2], [0]]) |
| 144 | + v = tf.tensordot(v, self.v_transformation, axes=[[2], [0]]) |
| 145 | + |
| 146 | + if cache is not None: |
| 147 | + |
| 148 | + # Combine cached keys and values with new keys and values. |
| 149 | + k = tf.concat([cache["k"], k], axis=1) |
| 150 | + v = tf.concat([cache["v"], v], axis=1) |
| 151 | + |
| 152 | + # Update cache |
| 153 | + cache["k"] = k |
| 154 | + cache["v"] = v |
| 155 | + |
| 156 | + # Split q, k, v into heads. |
| 157 | + q = self.split_heads(q) |
| 158 | + k = self.split_heads(k) |
| 159 | + v = self.split_heads(v) #(Batch, num_head, length_v, dk) |
| 160 | + |
| 161 | + # Scale q to prevent the dot product between q and k from growing too large. |
| 162 | + depth = (self.hidden_size // self.num_heads) |
| 163 | + q *= depth**-0.5 |
| 164 | + |
| 165 | + # Calculate dot product attention |
| 166 | + logits = tf.matmul(q, k, transpose_b=True) #(Batch, num_head, length_q, length_k) |
| 167 | + logits += mask |
| 168 | + weights = tf.nn.softmax(logits, name="attention_weights") #(Batch, num_head, length_q, length_k) |
| 169 | + if self.is_train: |
| 170 | + weights = tf.nn.dropout(weights, rate=self.attention_dropout) |
| 171 | + |
| 172 | + attention_output = tf.matmul(weights, v) |
| 173 | + |
| 174 | + # Recombine heads --> [batch_size, length, hidden_size] |
| 175 | + attention_output = self.combine_heads(attention_output) |
| 176 | + |
| 177 | + # Run the combined outputs through another linear projection layer. |
| 178 | + attention_output = tf.tensordot(attention_output, self.out_transformation, axes=[[2], [0]]) |
| 179 | + return attention_output |
| 180 | + |
| 181 | + |
| 182 | +class SelfAttentionLayer(MultiHeadAttentionLayer): |
| 183 | + """Multiheaded self-attention layer.""" |
| 184 | + |
| 185 | + def forward(self, inputs, mask, cache=None): |
| 186 | + return super(SelfAttentionLayer, self).forward(inputs=[inputs, inputs], mask=mask, cache=cache) |
0 commit comments