env.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright (c) 2021 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 os
  15. import platform
  16. import random
  17. import multiprocessing as mp
  18. import numpy as np
  19. import paddle
  20. def get_environ_info():
  21. """collect environment information"""
  22. env_info = dict()
  23. # TODO is_compiled_with_cuda() has not been moved
  24. compiled_with_cuda = paddle.is_compiled_with_cuda()
  25. if compiled_with_cuda:
  26. if 'gpu' in paddle.get_device():
  27. gpu_nums = paddle.distributed.get_world_size()
  28. else:
  29. gpu_nums = 0
  30. if gpu_nums == 0:
  31. os.environ['CUDA_VISIBLE_DEVICES'] = ''
  32. place = 'gpu' if compiled_with_cuda and gpu_nums else 'cpu'
  33. env_info['place'] = place
  34. env_info['num'] = int(os.environ.get('CPU_NUM', 1))
  35. if place == 'gpu':
  36. env_info['num'] = gpu_nums
  37. return env_info
  38. def get_num_workers(num_workers):
  39. if not platform.system() == 'Linux':
  40. # Dataloader with multi-process model is not supported
  41. # on MacOS and Windows currently.
  42. return 0
  43. if num_workers == 'auto':
  44. num_workers = mp.cpu_count() // 2 if mp.cpu_count() // 2 < 2 else 2
  45. return num_workers
  46. def init_parallel_env():
  47. env = os.environ
  48. if 'FLAGS_allocator_strategy' not in os.environ:
  49. os.environ['FLAGS_allocator_strategy'] = 'auto_growth'
  50. dist = 'PADDLE_TRAINER_ID' in env and 'PADDLE_TRAINERS_NUM' in env
  51. if dist:
  52. trainer_id = int(env['PADDLE_TRAINER_ID'])
  53. local_seed = (99 + trainer_id)
  54. random.seed(local_seed)
  55. np.random.seed(local_seed)
  56. if paddle.distributed.get_world_size() > 1:
  57. paddle.distributed.init_parallel_env()