fsdp_utils.py 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. from torch.distributed._tensor.device_mesh import init_device_mesh
  4. import os
  5. def fsdp_auto_wrap_policy(model, transformer_layer_name):
  6. import functools
  7. from torch.distributed.fsdp.wrap import _or_policy, lambda_auto_wrap_policy, transformer_auto_wrap_policy
  8. from peft.tuners import PrefixEncoder, PromptEmbedding, PromptEncoder
  9. def lambda_policy_fn(module):
  10. if (
  11. len(list(module.named_children())) == 0
  12. and getattr(module, "weight", None) is not None
  13. and module.weight.requires_grad
  14. ):
  15. return True
  16. return False
  17. lambda_policy = functools.partial(lambda_auto_wrap_policy, lambda_fn=lambda_policy_fn)
  18. transformer_wrap_policy = functools.partial(
  19. transformer_auto_wrap_policy,
  20. transformer_layer_cls=(
  21. PrefixEncoder,
  22. PromptEncoder,
  23. PromptEmbedding,
  24. transformer_layer_name,
  25. # FullyShardedDataParallelPlugin.get_module_class_from_name(
  26. # model, transformer_layer_name
  27. # ),
  28. ),
  29. )
  30. auto_wrap_policy = functools.partial(_or_policy, policies=[lambda_policy, transformer_wrap_policy])
  31. return auto_wrap_policy
  32. def hsdp_device_mesh(replica_group_size, sharding_group_size, device=None):
  33. """
  34. Initializes a device mesh for use with Hybrid Sharding strategy in FSDP (HSDP) training.
  35. This function requires explicit sizes for replica and sharding groups to accommodate models
  36. whose GPU fit is unknown, providing flexibility in distributed training setups.
  37. Args:
  38. replica_group_size (int): The size of each replica group. Must be provided to ensure
  39. the model fits within the available resources.
  40. sharding_group_size (int): The size of each sharding group that the model can fit. Must be provided to
  41. ensure the correct distribution of model parameters.
  42. device (str, optional): The device to use (e.g., "cuda:0"). If None, defaults to "cuda"
  43. with the local rank as the device index.
  44. Returns:
  45. A device mesh object compatible with FSDP.
  46. Raises:
  47. ValueError: If replica_group_size or sharding_group_size are not provided, or if the
  48. world size is not evenly divisible by the sharding group size.
  49. RuntimeError: If a valid device mesh cannot be created.
  50. Usage:
  51. If your model fits on 4 GPUS, and you have 3 nodes of 8 GPUs, then:
  52. Sharding_Group_Size = 4
  53. Replica_Groups_Size = (24 total gpus, 4 per sharding group) = 6 Replica Groups
  54. >>> device_mesh = initialize_device_mesh(replica_group_size, sharding_group_size)
  55. >>> sharded_model = FSDP(model, device_mesh=device_mesh, ...)
  56. """
  57. if replica_group_size is None or sharding_group_size is None:
  58. raise ValueError("Both replica_group_size and sharding_group_size must be provided.")
  59. local_rank = int(os.getenv("LOCAL_RANK", "0"))
  60. world_size = int(os.getenv("WORLD_SIZE", "1"))
  61. device = device or f"cuda"
  62. if world_size % sharding_group_size != 0:
  63. raise ValueError(f"World size {world_size} is not evenly divisible by "
  64. f"sharding group size {sharding_group_size}.")
  65. if (world_size // sharding_group_size) % replica_group_size != 0:
  66. raise ValueError(f"The calculated number of replica groups is not evenly divisible by "
  67. f"replica_group_size {replica_group_size}.")
  68. device_mesh = init_device_mesh(device, (replica_group_size, sharding_group_size))
  69. if device_mesh is None:
  70. raise RuntimeError("Failed to create a valid device mesh.")
  71. return device_mesh