prints.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright The Lightning team.
  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 os
  15. import warnings
  16. from functools import partial, wraps
  17. from typing import Any, Callable
  18. from torchmetrics import _logger as log
  19. def rank_zero_only(fn: Callable) -> Callable:
  20. """Call a function only on rank 0 in distributed settings.
  21. Meant to be used as an decorator.
  22. """
  23. @wraps(fn)
  24. def wrapped_fn(*args: Any, **kwargs: Any) -> Any:
  25. if rank_zero_only.rank == 0:
  26. return fn(*args, **kwargs)
  27. return None
  28. return wrapped_fn
  29. # add the attribute to the function but don't overwrite in case Trainer has already set it
  30. rank_zero_only.rank = getattr(rank_zero_only, "rank", int(os.environ.get("LOCAL_RANK", 0)))
  31. def _warn(*args: Any, **kwargs: Any) -> None:
  32. warnings.warn(*args, **kwargs)
  33. def _info(*args: Any, **kwargs: Any) -> None:
  34. log.info(*args, **kwargs)
  35. def _debug(*args: Any, **kwargs: Any) -> None:
  36. log.debug(*args, **kwargs)
  37. rank_zero_debug = rank_zero_only(_debug)
  38. rank_zero_info = rank_zero_only(_info)
  39. rank_zero_warn = rank_zero_only(_warn)
  40. _future_warning = partial(warnings.warn, category=FutureWarning)
  41. def _deprecated_root_import_class(name: str, domain: str) -> None:
  42. """Warn user that he is importing class from location it has been deprecated."""
  43. _future_warning(
  44. f"Importing `{name}` from `torchmetrics` was deprecated and will be removed in 2.0."
  45. f" Import `{name}` from `torchmetrics.{domain}` instead."
  46. )
  47. def _deprecated_root_import_func(name: str, domain: str) -> None:
  48. """Warn user that he is importing function from location it has been deprecated."""
  49. _future_warning(
  50. f"Importing `{name}` from `torchmetrics.functional` was deprecated and will be removed in 2.0."
  51. f" Import `{name}` from `torchmetrics.{domain}` instead."
  52. )