Created
December 8, 2023 13:00
-
-
Save sizhky/5a4a2d9fe92cdcdf216196e9d4d6e2aa to your computer and use it in GitHub Desktop.
clean memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import traceback, gc | |
def clean_ipython_hist(): | |
# Code in this function mainly copied from IPython source | |
if not 'get_ipython' in globals(): return | |
ip = get_ipython() | |
user_ns = ip.user_ns | |
ip.displayhook.flush() | |
pc = ip.displayhook.prompt_count + 1 | |
for n in range(1, pc): user_ns.pop('_i'+repr(n),None) | |
user_ns.update(dict(_i='',_ii='',_iii='')) | |
hm = ip.history_manager | |
hm.input_hist_parsed[:] = [''] * pc | |
hm.input_hist_raw[:] = [''] * pc | |
hm._i = hm._ii = hm._iii = hm._i00 = '' | |
def clean_tb(): | |
# h/t Piotr Czapla | |
if hasattr(sys, 'last_traceback'): | |
traceback.clear_frames(sys.last_traceback) | |
delattr(sys, 'last_traceback') | |
if hasattr(sys, 'last_type'): delattr(sys, 'last_type') | |
if hasattr(sys, 'last_value'): delattr(sys, 'last_value') | |
def clean_mem(): | |
clean_tb() | |
clean_ipython_hist() | |
gc.collect() | |
torch.cuda.empty_cache() | |
clean_mem() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment