| 1 | # Copyright 2025 HuggingFace Inc., Daniel Han-Chen & the Unsloth team and the LlamaFactory team. |
| 2 | # |
| 3 | # This code is inspired by the HuggingFace's Transformers and PEFT library, |
| 4 | # https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/modeling_utils.py |
| 5 | # https://github.com/huggingface/peft/blob/v0.10.0/src/peft/utils/other.py |
| 6 | # and the Unsloth library. |
| 7 | # https://github.com/unslothai/unsloth/blob/July-2024/unsloth/models/_utils.py |
| 8 | # |
| 9 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 10 | # you may not use this file except in compliance with the License. |
| 11 | # You may obtain a copy of the License at |
| 12 | # |
| 13 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 14 | # |
| 15 | # Unless required by applicable law or agreed to in writing, software |
| 16 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 18 | # See the License for the specific language governing permissions and |
| 19 | # limitations under the License. |
| 20 | |
| 21 | import inspect |
| 22 | from functools import WRAPPER_ASSIGNMENTS, partial, wraps |
| 23 | from types import MethodType |
| 24 | from typing import TYPE_CHECKING, Any, Callable, Optional, Union |
| 25 | |
| 26 | import torch |
| 27 | |
| 28 | from ..framework import logging |
| 29 | |
| 30 | if TYPE_CHECKING: |
| 31 | from transformers import PreTrainedModel |
| 32 | |
| 33 | from ..hparams import ModelArguments |
| 34 | |
| 35 | logger = logging.get_logger(__name__) |
| 36 | |
| 37 | |
| 38 | def get_custom_gradient_checkpointing_func( |
| 39 | gradient_checkpointing_func: Callable, |
| 40 | ) -> Callable: |
| 41 | r"""Only applies gradient checkpointing to trainable layers.""" |
| 42 | |
| 43 | @wraps(gradient_checkpointing_func, assigned=WRAPPER_ASSIGNMENTS + ("__self__",)) |
| 44 | def custom_gradient_checkpointing_func( |
| 45 | func: Callable, *args: Union["torch.Tensor", Any], **kwargs |
| 46 | ): |
| 47 | if isinstance(func, partial): |
| 48 | module: torch.nn.Module = func.func.__self__ |
| 49 | else: |
| 50 | module: torch.nn.Module = func.__self__ |
| 51 | |
| 52 | has_grad = False |
| 53 | if any(param.requires_grad for param in module.parameters()): |
| 54 | has_grad = True |
| 55 | for arg in args: |
| 56 | if torch.is_tensor(arg) and torch.is_floating_point(arg): |
| 57 | arg.requires_grad_(True) |
| 58 | break # assume the first tensor is always the hidden states |
| 59 | |
| 60 | if has_grad: |
| 61 | return gradient_checkpointing_func(func, *args, **kwargs) |
| 62 | else: |
| 63 | return func(*args, **kwargs) |
| 64 | |
| 65 | return custom_gradient_checkpointing_func |
| 66 | |
| 67 | |
| 68 | def _gradient_checkpointing_enable( |
| 69 | self: "PreTrainedModel", |
| 70 | gradient_checkpointing_kwargs: Optional[dict[str, Any]] = None, |
| 71 | ) -> None: |
| 72 | r"""Activates gradient checkpointing for the current model. |
| 73 | |
| 74 | Modification of the original method to enable gradient checkpointing for block-wise optimizer. |
| 75 | """ |
| 76 | from torch.utils.checkpoint import checkpoint |
| 77 | |
| 78 | if not self.supports_gradient_checkpointing: |
| 79 | raise ValueError( |
| 80 | f"{self.__class__.__name__} does not support gradient checkpointing." |
| 81 | ) |
| 82 | |
| 83 | if gradient_checkpointing_kwargs is None: |
| 84 | gradient_checkpointing_kwargs = {"use_reentrant": True} |
| 85 | |
| 86 | gradient_checkpointing_func = partial(checkpoint, **gradient_checkpointing_kwargs) |
| 87 | |
| 88 | gradient_checkpointing_func = get_custom_gradient_checkpointing_func( |
| 89 | gradient_checkpointing_func |
| 90 | ) |
| 91 | if ( |
| 92 | "value" in inspect.signature(self._set_gradient_checkpointing).parameters |
| 93 | ): # old GC format |
| 94 | self.apply(partial(self._set_gradient_checkpointing, value=True)) |
| 95 | self.enable_input_require_grads() |
| 96 | logger.warning_rank0_once( |
| 97 | "You are using the old GC format, some features (e.g. BAdam) will be invalid." |
| 98 | ) |
| 99 | else: # have already enabled input require gradients |
| 100 | self._set_gradient_checkpointing( |
| 101 | enable=True, gradient_checkpointing_func=gradient_checkpointing_func |
| 102 | ) |
| 103 | |
| 104 | |
| 105 | def prepare_model_for_training( |
| 106 | model: "PreTrainedModel", model_args: "ModelArguments" |
| 107 | ) -> None: |
| 108 | r"""Prepare the model before training.""" |
| 109 | if not model_args.disable_gradient_checkpointing: |
| 110 | if not getattr(model, "supports_gradient_checkpointing", False): |
| 111 | logger.warning_rank0( |
| 112 | "Current model does not support gradient checkpointing." |
| 113 | ) |
| 114 | else: |
| 115 | # use_reentrant=False might increase VRAM usage (have not been empirically verified yet) |
| 116 | # According to: https://github.com/huggingface/transformers/issues/28339 |
| 117 | gradient_checkpointing_enable = partial(_gradient_checkpointing_enable) |
| 118 | model.gradient_checkpointing_enable = MethodType( |
| 119 | gradient_checkpointing_enable, model |
| 120 | ) |
| 121 | model.gradient_checkpointing_enable( |
| 122 | gradient_checkpointing_kwargs={ |
| 123 | "use_reentrant": model_args.use_reentrant_gc |
| 124 | } |
| 125 | ) |
| 126 | setattr( |
| 127 | model.config, "use_cache", False |
| 128 | ) # turn off when gradient checkpointing is enabled |
| 129 | logger.info_rank0("Gradient checkpointing enabled.") |