declare-lab/tango2
92
1# Copyright 2023 The HuggingFace Team. All rights reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14"""15Accelerate utilities: Utilities related to accelerate16"""17 18from packaging import version19 20from .import_utils import is_accelerate_available21 22 23if is_accelerate_available():24 import accelerate25 26 27def apply_forward_hook(method):28 """29 Decorator that applies a registered CpuOffload hook to an arbitrary function rather than `forward`. This is useful30 for cases where a PyTorch module provides functions other than `forward` that should trigger a move to the31 appropriate acceleration device. This is the case for `encode` and `decode` in [`AutoencoderKL`].32 33 This decorator looks inside the internal `_hf_hook` property to find a registered offload hook.34 35 :param method: The method to decorate. This method should be a method of a PyTorch module.36 """37 if not is_accelerate_available():38 return method39 accelerate_version = version.parse(accelerate.__version__).base_version40 if version.parse(accelerate_version) < version.parse("0.17.0"):41 return method42 43 def wrapper(self, *args, **kwargs):44 if hasattr(self, "_hf_hook") and hasattr(self._hf_hook, "pre_forward"):45 self._hf_hook.pre_forward(self)46 return method(self, *args, **kwargs)47 48 return wrapper49 