memory_utils.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. import gc
  4. import os
  5. import sys
  6. import threading
  7. import numpy as np
  8. import psutil
  9. import torch
  10. def byte2gb(x):
  11. return int(x / 2**30)
  12. # This context manager is used to track the peak memory usage of the process
  13. class MemoryTrace:
  14. def __enter__(self):
  15. gc.collect()
  16. torch.cuda.empty_cache()
  17. torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
  18. self.begin = byte2gb(torch.cuda.memory_allocated())
  19. self.process = psutil.Process()
  20. self.cpu_begin = byte2gb(self.cpu_mem_used())
  21. self.peak_monitoring = True
  22. peak_monitor_thread = threading.Thread(target=self.peak_monitor_func)
  23. peak_monitor_thread.daemon = True
  24. peak_monitor_thread.start()
  25. return self
  26. def cpu_mem_used(self):
  27. """get resident set size memory for the current process"""
  28. return self.process.memory_info().rss
  29. def peak_monitor_func(self):
  30. self.cpu_peak = -1
  31. while True:
  32. self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
  33. # can't sleep or will not catch the peak right (this comment is here on purpose)
  34. # time.sleep(0.001) # 1msec
  35. if not self.peak_monitoring:
  36. break
  37. def __exit__(self, *exc):
  38. self.peak_monitoring = False
  39. gc.collect()
  40. torch.cuda.empty_cache()
  41. self.end = byte2gb(torch.cuda.memory_allocated())
  42. self.peak = byte2gb(torch.cuda.max_memory_allocated())
  43. cuda_info = torch.cuda.memory_stats()
  44. self.cuda_malloc_retires = cuda_info.get("num_alloc_retries", 0)
  45. self.peak_active_gb = byte2gb(cuda_info["active_bytes.all.peak"])
  46. self.m_cuda_ooms = cuda_info.get("num_ooms", 0)
  47. self.used = byte2gb(self.end - self.begin)
  48. self.peaked = byte2gb(self.peak - self.begin)
  49. self.max_reserved = byte2gb(torch.cuda.max_memory_reserved())
  50. self.cpu_end = self.cpu_mem_used()
  51. self.cpu_used = byte2gb(self.cpu_end - self.cpu_begin)
  52. self.cpu_peaked = byte2gb(self.cpu_peak - self.cpu_begin)
  53. # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")