parallel_helper.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (c) 2019 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 jin 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. from ..framework import Parameter
  16. __parallel_ctx__clz__ = None
  17. def _is_data_parallel_mode():
  18. global __parallel_ctx__clz__
  19. return (
  20. __parallel_ctx__clz__ is not None
  21. and int(os.getenv("PADDLE_TRAINERS_NUM", "1")) > 1
  22. )
  23. def _is_parallel_ctx_initialized():
  24. global __parallel_ctx__clz__
  25. return __parallel_ctx__clz__ is not None
  26. def _set_parallel_ctx(ccl_parallel_context):
  27. global __parallel_ctx__clz__
  28. assert (
  29. __parallel_ctx__clz__ is None
  30. ), "ParallelContext can only be initialized once."
  31. __parallel_ctx__clz__ = ccl_parallel_context
  32. def _init_parallel_ctx():
  33. global __parallel_ctx__clz__
  34. assert (
  35. __parallel_ctx__clz__ is not None
  36. ), "ParallelContext should be initialized."
  37. __parallel_ctx__clz__.init()
  38. def _broadcast_parameters(parameters):
  39. from ..distributed import broadcast
  40. for param in parameters:
  41. # In model parallel, some parameters are split into multiple devices,
  42. # so we could not broadcast these parameters.
  43. if param.is_distributed:
  44. continue
  45. if isinstance(param, Parameter) and param.trainable:
  46. broadcast(param, 0, sync_op=True)