shm.py 2.4 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. 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. num, unit = size_str[:-1], size_str[-1]
  33. assert unit in SIZE_UNIT, \
  34. "unknown shm size unit {}".format(unit)
  35. return float(num) * \
  36. (1024 ** (SIZE_UNIT.index(unit) - 1))
  37. def _get_shared_memory_size_in_M():
  38. try:
  39. df_infos = os.popen(SHM_QUERY_CMD).readlines()
  40. except:
  41. return None
  42. else:
  43. shm_infos = []
  44. for df_info in df_infos:
  45. info = df_info.strip()
  46. if info.find(SHM_KEY) >= 0:
  47. shm_infos.append(info.split())
  48. if len(shm_infos) == 0:
  49. return None
  50. elif len(shm_infos) == 1:
  51. return _parse_size_in_M(shm_infos[0][3])
  52. else:
  53. default_mount_infos = [
  54. si for si in shm_infos if si[-1] == SHM_DEFAULT_MOUNT
  55. ]
  56. if default_mount_infos:
  57. return _parse_size_in_M(default_mount_infos[0][3])
  58. else:
  59. return max([_parse_size_in_M(si[3]) for si in shm_infos])