|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
"""Keras layer that creates a self-attention mask.""" |
|
|
|
from __future__ import absolute_import |
|
from __future__ import division |
|
|
|
from __future__ import print_function |
|
|
|
import tensorflow as tf |
|
from official.modeling import tf_utils |
|
|
|
|
|
@tf.keras.utils.register_keras_serializable(package='Text') |
|
class SelfAttentionMask(tf.keras.layers.Layer): |
|
"""Create 3D attention mask from a 2D tensor mask. |
|
|
|
inputs[0]: from_tensor: 2D or 3D Tensor of shape |
|
[batch_size, from_seq_length, ...]. |
|
inputs[1]: to_mask: int32 Tensor of shape [batch_size, to_seq_length]. |
|
|
|
Returns: |
|
float Tensor of shape [batch_size, from_seq_length, to_seq_length]. |
|
""" |
|
|
|
def call(self, inputs): |
|
from_tensor = inputs[0] |
|
to_mask = inputs[1] |
|
from_shape = tf_utils.get_shape_list(from_tensor, expected_rank=[2, 3]) |
|
batch_size = from_shape[0] |
|
from_seq_length = from_shape[1] |
|
|
|
to_shape = tf_utils.get_shape_list(to_mask, expected_rank=2) |
|
to_seq_length = to_shape[1] |
|
|
|
to_mask = tf.cast( |
|
tf.reshape(to_mask, [batch_size, 1, to_seq_length]), |
|
dtype=from_tensor.dtype) |
|
|
|
|
|
|
|
|
|
|
|
|
|
broadcast_ones = tf.ones( |
|
shape=[batch_size, from_seq_length, 1], dtype=from_tensor.dtype) |
|
|
|
|
|
mask = broadcast_ones * to_mask |
|
|
|
return mask |
|
|