fsdp_utils.py 3.5 KB

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