File tree Expand file tree Collapse file tree
transformer_nuggets/utils Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -134,30 +134,37 @@ def profile_function(
134134 return prof
135135
136136
137- @contextmanager
138- def max_memory_usage (log : bool = False , precision : int = 2 ) -> int :
139- """Prints the maximum CUDA memory usage at the end of a context manager
137+ class max_memory_usage :
138+ """Tracks maximum CUDA memory usage within a context manager region
140139
141140 Args:
142141 log (bool): Whether to print the memory usage to the console
143142 precision (int): The number of decimal places to print
144143
145144 Usage:
146145 ```
147- with print_max_memory_usage() :
146+ with max_memory_usage() as mem :
148147 # code to profile
148+ print(mem.max_memory)
149149 ```
150- Returns:
151- max_memory (int): The maximum CUDA memory usage in GiB
152150 """
153- try :
154- yield
155- finally :
156- max_memory = torch .cuda .max_memory_allocated ()
157- if log :
158- max_memory_gib = max_memory / (1024 ** 3 )
159- print (f"Max CUDA Memory Allocated: { max_memory_gib :.{precision }f} GiB" )
160- return max_memory
151+
152+ def __init__ (self , log = False , precision = 2 ):
153+ self .log = log
154+ self .precision = precision
155+ self .max_memory = 0
156+
157+ def __enter__ (self ):
158+ torch .cuda .reset_peak_memory_stats ()
159+ torch .cuda .synchronize ()
160+ return self
161+
162+ def __exit__ (self , exc_type , exc_val , exc_tb ):
163+ torch .cuda .synchronize ()
164+ self .max_memory = torch .cuda .max_memory_allocated ()
165+ if self .log :
166+ max_memory_gib = self .max_memory / (1024 ** 3 )
167+ print (f"Max CUDA Memory Allocated: { max_memory_gib :.{self .precision }f} GiB" )
161168
162169
163170class cuda_memory_usage :
You can’t perform that action at this time.
0 commit comments