utils.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # Copyright (c) 2023 PaddlePaddle Authors. 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 copy
  15. from typing import List, Tuple, Union
  16. import numpy as np
  17. import paddle
  18. import paddle.distributed as dist
  19. from paddle.framework import core
  20. def get_coordinator(mesh: Union[np.array, List[List[int]]], rank: int):
  21. mesh = paddle.to_tensor(mesh)
  22. rand_coordinator = (mesh == rank).nonzero()
  23. assert rand_coordinator.shape[0] in (
  24. 0,
  25. 1,
  26. ), f"rand_coordinator.shape: {rand_coordinator.shape}"
  27. return (
  28. rand_coordinator[0].tolist() if rand_coordinator.shape[0] > 0 else None
  29. )
  30. def compute_local_shape_and_global_offset(
  31. global_shape: List[int],
  32. process_mesh: core.ProcessMesh,
  33. placements: List[core.Placement],
  34. ) -> Tuple[Tuple[int], Tuple[int]]:
  35. mesh = np.array(process_mesh.process_ids).reshape(process_mesh.shape)
  36. # deal with cross mesh case
  37. if paddle.distributed.get_rank() not in mesh:
  38. return (None, None)
  39. rank_coordinator = get_coordinator(mesh, paddle.distributed.get_rank())
  40. local_shape = copy.copy(global_shape)
  41. global_offset = [0 for _ in global_shape]
  42. for dim, placement in enumerate(placements):
  43. if isinstance(placement, dist.Replicate):
  44. continue
  45. else:
  46. i = placement.get_dim()
  47. assert (
  48. global_shape[i] % process_mesh.shape[dim] == 0
  49. ), f"i:{i}, global_shape[i]:{global_shape[i]}, process_mesh.shape[dim]:{process_mesh.shape[dim]}"
  50. local_shape[i] = global_shape[i] // process_mesh.shape[dim]
  51. chunk_idx = rank_coordinator[dim]
  52. global_offset[i] = chunk_idx * local_shape[i]
  53. return tuple(local_shape), tuple(global_offset)
  54. def flatten_state_dict(state_dict):
  55. """
  56. Flatten the nested dict to a flat dict.
  57. {"model": {"w0": xxx}} -> {model.w0: xxx}
  58. """
  59. flatten_state_dict = {}
  60. mapping = {}
  61. def _flatten(key, value):
  62. if isinstance(value, dict):
  63. for k, v in value.items():
  64. assert isinstance(k, str), f"The key should be str, but is {k}"
  65. _flatten(key + (k,), v)
  66. elif isinstance(value, paddle.Tensor):
  67. flatten_key_str = ".".join(key)
  68. flatten_state_dict[flatten_key_str] = value
  69. mapping[flatten_key_str] = key
  70. else:
  71. raise ValueError(
  72. f"The value should be dict or paddle.Tensor, but is {value}"
  73. )
  74. _flatten((), state_dict)
  75. return flatten_state_dict, mapping
  76. def unflatten_state_dict(flat_state_dict, mapping):
  77. """
  78. Unflatten the flat dict to a nested dict.
  79. {model.w0: xxx} -> {"model": {"w0": xxx}}
  80. """
  81. state_dict = {}
  82. for key, value in flat_state_dict.items():
  83. key_tuple = mapping[key]
  84. assert isinstance(
  85. key_tuple, tuple
  86. ), f"The key should be tuple, but is {key_tuple}"
  87. tmp = state_dict
  88. for i in range(len(key_tuple) - 1):
  89. key = key_tuple[i]
  90. tmp = tmp.setdefault(key, {})
  91. tmp[key_tuple[-1]] = value
  92. return state_dict