Skip to content
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

Fix gradient checkpointing + fp16 autocast for most models #24247

Merged
merged 15 commits into from
Jun 21, 2023
Merged
4 changes: 4 additions & 0 deletions src/transformers/models/opt/modeling_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
SequenceClassifierOutputWithPast,
)
from ...modeling_utils import PreTrainedModel
from ...pytorch_utils import get_checkpointing_kwargs
from ...utils import (
add_code_sample_docstrings,
add_start_docstrings,
Expand Down Expand Up @@ -700,12 +701,15 @@ def custom_forward(*inputs):

return custom_forward

gradient_checkpointing_kwargs = get_checkpointing_kwargs()

layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(decoder_layer),
hidden_states,
causal_attention_mask,
head_mask[idx] if head_mask is not None else None,
None,
**gradient_checkpointing_kwargs,
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't know at all if it better or not, but we could wrap the import of and maybe
torch.utils.checkpoint.checkpoint = custom_checkpoint

Copy link
Collaborator

Choose a reason for hiding this comment

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

Yes I was thinking of having a util function wrapping torch.utils.checkpoint.checkpoint not just the kwargs creation, soory if I was unclear.

)
else:
layer_outputs = decoder_layer(
Expand Down
12 changes: 12 additions & 0 deletions src/transformers/pytorch_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,3 +289,15 @@ def id_tensor_storage(tensor: torch.Tensor) -> Tuple[torch.device, int, int]:
non-overlapping lifetimes may have the same id.
"""
return tensor.device, storage_ptr(tensor), storage_size(tensor)


def get_checkpointing_kwargs() -> dict:
r"""
Get the correct kwargs to correctly use `torch.utils.checkpoint.checkpoint` as the default call leads to silent
bugs that leads to the gradients of the last layers not being updated. For more in depth detail of the issue,
please have a look at: https://github.com/huggingface/transformers/pull/24247
"""
returned_kwargs = {}
if "use_reentrant" in list(inspect.signature(torch.utils.checkpoint.checkpoint).parameters):
returned_kwargs["use_reentrant"] = False
return returned_kwargs