fsdp.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. from __future__ import annotations
  15. import os
  16. from typing import TYPE_CHECKING
  17. from ..utils import is_torch_available, strtobool
  18. if TYPE_CHECKING:
  19. from torch import nn
  20. def is_fsdp_managed_module(module: nn.Module) -> bool:
  21. if not is_torch_available():
  22. return False
  23. import torch
  24. if not torch.distributed.is_available():
  25. return False
  26. import torch.distributed.fsdp
  27. return isinstance(module, torch.distributed.fsdp.FullyShardedDataParallel) or getattr(
  28. module, "_is_fsdp_managed_module", False
  29. )
  30. def is_fsdp_enabled():
  31. if is_torch_available():
  32. import torch
  33. return (
  34. torch.distributed.is_available()
  35. and torch.distributed.is_initialized()
  36. and strtobool(os.environ.get("ACCELERATE_USE_FSDP", "False")) == 1
  37. and strtobool(os.environ.get("FSDP_CPU_RAM_EFFICIENT_LOADING", "False")) == 1
  38. )
  39. return False