TFViTSelfAttention

建立於 差異永不過期
2 刪除
73 行
0 新增
73 行
class TFViTMAESelfAttention(tf.keras.layers.Layer):
class TFViTSelfAttention(tf.keras.layers.Layer):
def __init__(self, config: ViTMAEConfig, **kwargs):
def __init__(self, config: ViTConfig, **kwargs):
super().__init__(**kwargs)
super().__init__(**kwargs)


if config.hidden_size % config.num_attention_heads != 0:
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number "
f"The hidden size ({config.hidden_size}) is not a multiple of the number "
f"of attention heads ({config.num_attention_heads})"
f"of attention heads ({config.num_attention_heads})"
)
)


self.num_attention_heads = config.num_attention_heads
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
self.sqrt_att_head_size = math.sqrt(self.attention_head_size)


self.query = tf.keras.layers.Dense(
self.query = tf.keras.layers.Dense(
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
)
)
self.key = tf.keras.layers.Dense(
self.key = tf.keras.layers.Dense(
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
)
)
self.value = tf.keras.layers.Dense(
self.value = tf.keras.layers.Dense(
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
)
)
self.dropout = tf.keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
self.dropout = tf.keras.layers.Dropout(rate=config.attention_probs_dropout_prob)


def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))


# Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
# Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
return tf.transpose(tensor, perm=[0, 2, 1, 3])
return tf.transpose(tensor, perm=[0, 2, 1, 3])


def call(
def call(
self,
self,
hidden_states: tf.Tensor,
hidden_states: tf.Tensor,
head_mask: tf.Tensor,
head_mask: tf.Tensor,
output_attentions: bool,
output_attentions: bool,
training: bool = False,
training: bool = False,
) -> Tuple[tf.Tensor]:
) -> Tuple[tf.Tensor]:
batch_size = shape_list(hidden_states)[0]
batch_size = shape_list(hidden_states)[0]
mixed_query_layer = self.query(inputs=hidden_states)
mixed_query_layer = self.query(inputs=hidden_states)
mixed_key_layer = self.key(inputs=hidden_states)
mixed_key_layer = self.key(inputs=hidden_states)
mixed_value_layer = self.value(inputs=hidden_states)
mixed_value_layer = self.value(inputs=hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
value_layer = self.transpose_for_scores(mixed_value_layer, batch_size)
value_layer = self.transpose_for_scores(mixed_value_layer, batch_size)


# Take the dot product between "query" and "key" to get the raw attention scores.
# Take the dot product between "query" and "key" to get the raw attention scores.
# (batch size, num_heads, seq_len_q, seq_len_k)
# (batch size, num_heads, seq_len_q, seq_len_k)
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
attention_scores = tf.divide(attention_scores, dk)
attention_scores = tf.divide(attention_scores, dk)


# Normalize the attention scores to probabilities.
# Normalize the attention scores to probabilities.
attention_probs = tf.nn.softmax(logits=attention_scores, axis=-1)
attention_probs = tf.nn.softmax(logits=attention_scores, axis=-1)


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


# Mask heads if we want to
# Mask heads if we want to
if head_mask is not None:
if head_mask is not None:
attention_probs = tf.multiply(attention_probs, head_mask)
attention_probs = tf.multiply(attention_probs, head_mask)


attention_output = tf.matmul(attention_probs, value_layer)
attention_output = tf.matmul(attention_probs, value_layer)
attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])


# (batch_size, seq_len_q, all_head_size)
# (batch_size, seq_len_q, all_head_size)
attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)


return outputs
return outputs