deprecation.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. # Copyright 2024 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 at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # 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 and
  13. # limitations under the License.
  14. import inspect
  15. import warnings
  16. from functools import wraps
  17. import packaging.version
  18. from .. import __version__
  19. from . import ExplicitEnum, is_torch_available, is_torchdynamo_compiling
  20. # This is needed in case we deprecate a kwarg of a function/method being compiled
  21. if is_torch_available():
  22. import torch # noqa: F401
  23. class Action(ExplicitEnum):
  24. NONE = "none"
  25. NOTIFY = "notify"
  26. NOTIFY_ALWAYS = "notify_always"
  27. RAISE = "raise"
  28. def deprecate_kwarg(
  29. old_name: str,
  30. version: str,
  31. new_name: str | None = None,
  32. warn_if_greater_or_equal_version: bool = False,
  33. raise_if_greater_or_equal_version: bool = False,
  34. raise_if_both_names: bool = False,
  35. additional_message: str | None = None,
  36. ):
  37. """
  38. Function or method decorator to notify users about deprecated keyword arguments, replacing them with a new name if specified.
  39. Note that is decorator is `torch.compile`-safe, i.e. it will not cause graph breaks (but no warning will be displayed if compiling).
  40. This decorator allows you to:
  41. - Notify users when a keyword argument is deprecated.
  42. - Automatically replace deprecated keyword arguments with new ones.
  43. - Raise an error if deprecated arguments are used, depending on the specified conditions.
  44. By default, the decorator notifies the user about the deprecated argument while the `transformers.__version__` < specified `version`
  45. in the decorator. To keep notifications with any version `warn_if_greater_or_equal_version=True` can be set.
  46. Parameters:
  47. old_name (`str`):
  48. Name of the deprecated keyword argument.
  49. version (`str`):
  50. The version in which the keyword argument was (or will be) deprecated.
  51. new_name (`Optional[str]`, *optional*):
  52. The new name for the deprecated keyword argument. If specified, the deprecated keyword argument will be replaced with this new name.
  53. warn_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
  54. Whether to show warning if current `transformers` version is greater or equal to the deprecated version.
  55. raise_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
  56. Whether to raise `ValueError` if current `transformers` version is greater or equal to the deprecated version.
  57. raise_if_both_names (`bool`, *optional*, defaults to `False`):
  58. Whether to raise `ValueError` if both deprecated and new keyword arguments are set.
  59. additional_message (`Optional[str]`, *optional*):
  60. An additional message to append to the default deprecation message.
  61. Raises:
  62. ValueError:
  63. If raise_if_greater_or_equal_version is True and the current version is greater than or equal to the deprecated version, or if raise_if_both_names is True and both old and new keyword arguments are provided.
  64. Returns:
  65. Callable:
  66. A wrapped function that handles the deprecated keyword arguments according to the specified parameters.
  67. Example usage with renaming argument:
  68. ```python
  69. @deprecate_kwarg("reduce_labels", new_name="do_reduce_labels", version="6.0.0")
  70. def my_function(do_reduce_labels):
  71. print(do_reduce_labels)
  72. my_function(reduce_labels=True) # Will show a deprecation warning and use do_reduce_labels=True
  73. ```
  74. Example usage without renaming argument:
  75. ```python
  76. @deprecate_kwarg("max_size", version="6.0.0")
  77. def my_function(max_size):
  78. print(max_size)
  79. my_function(max_size=1333) # Will show a deprecation warning
  80. ```
  81. """
  82. deprecated_version = packaging.version.parse(version)
  83. current_version = packaging.version.parse(__version__)
  84. is_greater_or_equal_version = current_version >= deprecated_version
  85. if is_greater_or_equal_version:
  86. version_message = f"and removed starting from version {version}"
  87. else:
  88. version_message = f"and will be removed in version {version}"
  89. def wrapper(func):
  90. # Required for better warning message
  91. sig = inspect.signature(func)
  92. function_named_args = set(sig.parameters.keys())
  93. is_instance_method = "self" in function_named_args
  94. is_class_method = "cls" in function_named_args
  95. @wraps(func)
  96. def wrapped_func(*args, **kwargs):
  97. # Get class + function name (just for better warning message)
  98. func_name = func.__name__
  99. if is_instance_method:
  100. func_name = f"{args[0].__class__.__name__}.{func_name}"
  101. elif is_class_method:
  102. func_name = f"{args[0].__name__}.{func_name}"
  103. minimum_action = Action.NONE
  104. message = None
  105. # deprecated kwarg and its new version are set for function call -> replace it with new name
  106. if old_name in kwargs and new_name in kwargs:
  107. minimum_action = Action.RAISE if raise_if_both_names else Action.NOTIFY_ALWAYS
  108. message = f"Both `{old_name}` and `{new_name}` are set for `{func_name}`. Using `{new_name}={kwargs[new_name]}` and ignoring deprecated `{old_name}={kwargs[old_name]}`."
  109. kwargs.pop(old_name)
  110. # only deprecated kwarg is set for function call -> replace it with new name
  111. elif old_name in kwargs and new_name is not None and new_name not in kwargs:
  112. minimum_action = Action.NOTIFY
  113. message = f"`{old_name}` is deprecated {version_message} for `{func_name}`. Use `{new_name}` instead."
  114. kwargs[new_name] = kwargs.pop(old_name)
  115. # deprecated kwarg is not set for function call and new name is not specified -> just notify
  116. elif old_name in kwargs:
  117. minimum_action = Action.NOTIFY
  118. message = f"`{old_name}` is deprecated {version_message} for `{func_name}`."
  119. if message is not None and additional_message is not None:
  120. message = f"{message} {additional_message}"
  121. # update minimum_action if argument is ALREADY deprecated (current version >= deprecated version)
  122. if is_greater_or_equal_version:
  123. # change to (NOTIFY, NOTIFY_ALWAYS) -> RAISE if specified
  124. # in case we want to raise error for already deprecated arguments
  125. if raise_if_greater_or_equal_version and minimum_action != Action.NONE:
  126. minimum_action = Action.RAISE
  127. # change to NOTIFY -> NONE if specified (NOTIFY_ALWAYS can't be changed to NONE)
  128. # in case we want to ignore notifications for already deprecated arguments
  129. elif not warn_if_greater_or_equal_version and minimum_action == Action.NOTIFY:
  130. minimum_action = Action.NONE
  131. # raise error or notify user
  132. if minimum_action == Action.RAISE:
  133. raise ValueError(message)
  134. # If we are compiling, we do not raise the warning as it would break compilation
  135. elif minimum_action in (Action.NOTIFY, Action.NOTIFY_ALWAYS) and not is_torchdynamo_compiling():
  136. # DeprecationWarning is ignored by default, so we use FutureWarning instead
  137. warnings.warn(message, FutureWarning, stacklevel=2)
  138. return func(*args, **kwargs)
  139. return wrapped_func
  140. return wrapper