| 1 |
# Copyright 2025 The HuggingFace Team. 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 |
|
| 15 |
import gc |
| 16 |
import json |
| 17 |
import os |
| 18 |
import threading |
| 19 |
import time |
| 20 |
|
| 21 |
import psutil |
| 22 |
import torch |
| 23 |
|
| 24 |
from accelerate import PartialState |
| 25 |
|
| 26 |
|
| 27 |
class MemoryTracker: |
| 28 |
def __init__( |
| 29 |
self, |
| 30 |
device: torch.device, |
| 31 |
output_directory: str, |
| 32 |
run_name: str, |
| 33 |
save_memory_snapshot: bool, |
| 34 |
log_interval: float = 0.01, |
| 35 |
): |
| 36 |
"""Class for tracking gpu and cpu memory usage of the process. |
| 37 |
|
| 38 |
Args: |
| 39 |
device (`torch.device`): |
| 40 |
PyTorch device to monitor. |
| 41 |
output_directory (`str`): |
| 42 |
Directory to save the memory usage data to, will be created if it doesn't exist. |
| 43 |
run_name (`str`): |
| 44 |
Name of the run, will be used to name the output files. |
| 45 |
save_memory_snapshot (`bool`): |
| 46 |
Whether to also save `torch.cuda.memory._dump_snapshot` to the output directory. |
| 47 |
log_interval (`float`, *optional*): |
| 48 |
Interval in seconds between memory measurements. Defaults to 0.01. |
| 49 |
""" |
| 50 |
self.log_interval = log_interval |
| 51 |
self.save_memory_snapshot = save_memory_snapshot |
| 52 |
self.output_directory = output_directory |
| 53 |
self.run_name = run_name |
| 54 |
|
| 55 |
self.timestamps = [] |
| 56 |
self.allocated_memory = [] |
| 57 |
self.reserved_memory = [] |
| 58 |
self.virtual_memory = [] |
| 59 |
|
| 60 |
self.start_time = None |
| 61 |
self.running = False |
| 62 |
|
| 63 |
self._thread = None |
| 64 |
self._state = PartialState() |
| 65 |
self._process = psutil.Process() |
| 66 |
self._device = device |
| 67 |
self.torch_accelerator_module = getattr(torch, device.type, torch.cuda) |
| 68 |
|
| 69 |
def _monitor(self): |
| 70 |
self.start_time = time.time() |
| 71 |
|
| 72 |
while self.running: |
| 73 |
allocated = self.torch_accelerator_module.memory_allocated(self._device) / (1024 * 1024) |
| 74 |
reserved = self.torch_accelerator_module.memory_reserved(self._device) / (1024 * 1024) |
| 75 |
virtual_memory = self._process.memory_info().rss / (1024 * 1024) |
| 76 |
|
| 77 |
self.allocated_memory.append(allocated) |
| 78 |
self.reserved_memory.append(reserved) |
| 79 |
self.virtual_memory.append(virtual_memory) |
| 80 |
self.timestamps.append(time.time() - self.start_time) |
| 81 |
|
| 82 |
time.sleep(self.log_interval) |
| 83 |
|
| 84 |
def start(self): |
| 85 |
gc.collect() |
| 86 |
self.torch_accelerator_module.empty_cache() |
| 87 |
|
| 88 |
if self.output_directory: |
| 89 |
os.makedirs(self.output_directory, exist_ok=True) |
| 90 |
|
| 91 |
if self.save_memory_snapshot: |
| 92 |
self.torch_accelerator_module.memory._record_memory_history() |
| 93 |
|
| 94 |
self.running = True |
| 95 |
self._thread = threading.Thread(target=self._monitor) |
| 96 |
self._thread.daemon = True |
| 97 |
self._thread.start() |
| 98 |
|
| 99 |
def stop(self): |
| 100 |
self.running = False |
| 101 |
if self._thread: |
| 102 |
self._thread.join() |
| 103 |
|
| 104 |
if self.save_memory_snapshot and self._state.is_main_process and self.output_directory: |
| 105 |
output_file = os.path.join(self.output_directory, f"{self.run_name}_memory_snapshot.pkl") |
| 106 |
self.torch_accelerator_module.memory._dump_snapshot(output_file) |
| 107 |
|
| 108 |
if self._state.is_main_process and self.output_directory: |
| 109 |
path = os.path.join(self.output_directory, f"{self.run_name}_memory_usage.json") |
| 110 |
with open(path, "w") as f: |
| 111 |
json.dump( |
| 112 |
{ |
| 113 |
"timestamps": self.timestamps, |
| 114 |
"allocated_memory": self.allocated_memory, |
| 115 |
"reserved_memory": self.reserved_memory, |
| 116 |
"virtual_memory": self.virtual_memory, |
| 117 |
}, |
| 118 |
f, |
| 119 |
) |
| 120 |
if self.save_memory_snapshot: |
| 121 |
self.torch_accelerator_module.memory._record_memory_history(False) |
| 122 |
self.torch_accelerator_module.empty_cache() |
| 123 |
|
| 124 |
@property |
| 125 |
def peak_allocated_memory(self): |
| 126 |
return max(self.allocated_memory) |
| 127 |
|
| 128 |
@property |
| 129 |
def peak_reserved_memory(self): |
| 130 |
return max(self.reserved_memory) |