Skip to content

TF: XLA-trainable DeBERTa v2 #18546

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 19 additions & 23 deletions src/transformers/models/deberta/modeling_tf_deberta.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,27 +101,6 @@ def call(self, inputs: tf.Tensor, mask: tf.Tensor):
return output


def get_mask(input, dropout):
mask = tf.cast(
1 - tf.compat.v1.distributions.Bernoulli(probs=1 - dropout).sample(sample_shape=shape_list(input)), tf.bool
)
return mask, dropout


@tf.custom_gradient
def TFDebertaXDropout(input, local_ctx):
mask, dropout = get_mask(input, local_ctx)
scale = tf.convert_to_tensor(1.0 / (1 - dropout), dtype=tf.float32)
input = tf.cond(dropout > 0, lambda: tf.where(mask, 0.0, input) * scale, lambda: input)

def custom_grad(upstream_grad):
return tf.cond(
scale > 1, lambda: (tf.where(mask, 0.0, upstream_grad) * scale, None), lambda: (upstream_grad, None)
)

return input, custom_grad


class TFDebertaStableDropout(tf.keras.layers.Layer):
"""
Optimized dropout module for stabilizing the training
Expand All @@ -134,9 +113,26 @@ def __init__(self, drop_prob, **kwargs):
super().__init__(**kwargs)
self.drop_prob = tf.convert_to_tensor(drop_prob, dtype=tf.float32)

@tf.custom_gradient
def xdropout(self, input):
"""
Applies dropout to the input, as vanilla dropout, but also scales the remaining elements up by 1/drop_prob.
"""
mask = tf.cast(
1 - tf.compat.v1.distributions.Bernoulli(probs=1 - self.drop_prob).sample(sample_shape=shape_list(input)),
tf.bool,
)
scale = tf.convert_to_tensor(1.0 / (1 - self.drop_prob), dtype=tf.float32)
input = tf.cond(self.drop_prob > 0, lambda: tf.where(mask, 0.0, input) * scale, lambda: input)

def grad(upstream):
return tf.cond(scale > 1, lambda: tf.where(mask, 0.0, upstream) * scale, lambda: upstream)

return input, grad

def call(self, inputs: tf.Tensor, training: tf.Tensor = False):
if training and self.drop_prob > 0:
return TFDebertaXDropout(inputs, self.drop_prob)
if training:
return self.xdropout(inputs)
return inputs


Expand Down
60 changes: 31 additions & 29 deletions src/transformers/models/deberta_v2/modeling_tf_deberta_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,29 +102,6 @@ def call(self, inputs: tf.Tensor, mask: tf.Tensor):
return output


# Copied from transformers.models.deberta.modeling_tf_deberta.get_mask
def get_mask(input, dropout):
mask = tf.cast(
1 - tf.compat.v1.distributions.Bernoulli(probs=1 - dropout).sample(sample_shape=shape_list(input)), tf.bool
)
return mask, dropout


@tf.custom_gradient
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaXDropout
def TFDebertaV2XDropout(input, local_ctx):
mask, dropout = get_mask(input, local_ctx)
scale = tf.convert_to_tensor(1.0 / (1 - dropout), dtype=tf.float32)
input = tf.cond(dropout > 0, lambda: tf.where(mask, 0.0, input) * scale, lambda: input)

def custom_grad(upstream_grad):
return tf.cond(
scale > 1, lambda: (tf.where(mask, 0.0, upstream_grad) * scale, None), lambda: (upstream_grad, None)
)

return input, custom_grad


# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaStableDropout with Deberta->DebertaV2
class TFDebertaV2StableDropout(tf.keras.layers.Layer):
"""
Expand All @@ -138,9 +115,26 @@ def __init__(self, drop_prob, **kwargs):
super().__init__(**kwargs)
self.drop_prob = tf.convert_to_tensor(drop_prob, dtype=tf.float32)

@tf.custom_gradient
def xdropout(self, input):
"""
Applies dropout to the input, as vanilla dropout, but also scales the remaining elements up by 1/drop_prob.
"""
mask = tf.cast(
1 - tf.compat.v1.distributions.Bernoulli(probs=1 - self.drop_prob).sample(sample_shape=shape_list(input)),
tf.bool,
)
scale = tf.convert_to_tensor(1.0 / (1 - self.drop_prob), dtype=tf.float32)
input = tf.cond(self.drop_prob > 0, lambda: tf.where(mask, 0.0, input) * scale, lambda: input)

def grad(upstream):
return tf.cond(scale > 1, lambda: tf.where(mask, 0.0, upstream) * scale, lambda: upstream)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason to use tf.cond over standard Python if statements here? It feels harder to read, and self.drop_prob and scale shouldn't vary between calls!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original code converted self.drop_prob into a tensor, so all if/elses had to be tf.cond.

But there is no good reason for self.drop_prob to be a tensor, so I've removed the conversion and replaced tf.cond by if/elses! Thanks for the suggestion 👍


return input, grad

def call(self, inputs: tf.Tensor, training: tf.Tensor = False):
if training and self.drop_prob > 0:
return TFDebertaV2XDropout(inputs, self.drop_prob)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aaaa, was this instantiating a new class in each call?!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not quite because TFDebertaV2XDropout, despite the camel case, was a function 😂

if training:
return self.xdropout(inputs)
return inputs


Expand Down Expand Up @@ -525,10 +519,18 @@ def pos_dynamic_expand(pos_index, p2c_att, key_layer):
def take_along_axis(x, indices):
# Only a valid port of np.take_along_axis when the gather axis is -1

flat_x = tf.reshape(x, (-1, x.shape[-1]))
flat_indices = tf.reshape(indices, (-1, indices.shape[-1]))
gathered = tf.gather(flat_x, flat_indices, batch_dims=1)
gathered = tf.reshape(gathered, indices.shape)
# TPU + gathers and reshapes don't go along well -- see https://github.com/huggingface/transformers/issues/18239
if isinstance(tf.distribute.get_strategy(), tf.distribute.TPUStrategy):
# [B, S, P] -> [B, S, P, D]
one_hot_indices = tf.one_hot(indices, depth=x.shape[-1], dtype=x.dtype)

# if we ignore the first two dims, this is equivalent to multiplying a matrix (one hot) by a vector (x)
# grossly abusing notation: [B, S, P, D] . [B, S, D] = [B, S, P]
gathered = tf.einsum("ijkl,ijl->ijk", one_hot_indices, x)

# GPUs, on the other hand, prefer gathers instead of large one-hot+matmuls
else:
gathered = tf.gather(x, indices, batch_dims=2)

return gathered

Expand Down