shm_utils.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. SIZE_UNIT = ['K', 'M', 'G', 'T']
  16. SHM_QUERY_CMD = 'df -h'
  17. SHM_KEY = 'shm'
  18. SHM_DEFAULT_MOUNT = '/dev/shm'
  19. # [ shared memory size check ]
  20. # In detection models, image/target data occupies a lot of memory, and
  21. # will occupy lots of shared memory in multi-process DataLoader, we use
  22. # following code to get shared memory size and perform a size check to
  23. # disable shared memory use if shared memory size is not enough.
  24. # Shared memory getting process as follows:
  25. # 1. use `df -h` get all mount info
  26. # 2. pick up spaces whose mount info contains 'shm'
  27. # 3. if 'shm' space number is only 1, return its size
  28. # 4. if there are multiple 'shm' space, try to find the default mount
  29. # directory '/dev/shm' is Linux-like system, otherwise return the
  30. # biggest space size.
  31. def _parse_size_in_M(size_str):
  32. if size_str[-1] == 'B':
  33. num, unit = size_str[:-2], size_str[-2]
  34. else:
  35. num, unit = size_str[:-1], size_str[-1]
  36. assert unit in SIZE_UNIT, \
  37. "unknown shm size unit {}".format(unit)
  38. return float(num) * \
  39. (1024 ** (SIZE_UNIT.index(unit) - 1))
  40. def _get_shared_memory_size_in_M():
  41. try:
  42. df_infos = os.popen(SHM_QUERY_CMD).readlines()
  43. except:
  44. return None
  45. else:
  46. shm_infos = []
  47. for df_info in df_infos:
  48. info = df_info.strip()
  49. if info.find(SHM_KEY) >= 0:
  50. shm_infos.append(info.split())
  51. if len(shm_infos) == 0:
  52. return None
  53. elif len(shm_infos) == 1:
  54. return _parse_size_in_M(shm_infos[0][3])
  55. else:
  56. default_mount_infos = [
  57. si for si in shm_infos if si[-1] == SHM_DEFAULT_MOUNT
  58. ]
  59. if default_mount_infos:
  60. return _parse_size_in_M(default_mount_infos[0][3])
  61. else:
  62. return max([_parse_size_in_M(si[3]) for si in shm_infos])