Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jantic
GitHub Repository: jantic/deoldify
Path: blob/master/fastai/utils/ipython.py
781 views
1
"ipython utils"
2
3
import os, functools, traceback, gc
4
5
def is_in_ipython():
6
"Is the code running in the ipython environment (jupyter including)"
7
8
program_name = os.path.basename(os.getenv('_', ''))
9
10
if ('jupyter-notebook' in program_name or # jupyter-notebook
11
'ipython' in program_name or # ipython
12
'JPY_PARENT_PID' in os.environ): # ipython-notebook
13
return True
14
else:
15
return False
16
17
IS_IN_IPYTHON = is_in_ipython()
18
19
def is_in_colab():
20
"Is the code running in Google Colaboratory?"
21
if not IS_IN_IPYTHON: return False
22
try:
23
from google import colab
24
return True
25
except: return False
26
27
IS_IN_COLAB = is_in_colab()
28
29
def get_ref_free_exc_info():
30
"Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory"
31
type, val, tb = sys.exc_info()
32
traceback.clear_frames(tb)
33
return (type, val, tb)
34
35
def gpu_mem_restore(func):
36
"Reclaim GPU RAM if CUDA out of memory happened, or execution was interrupted"
37
@functools.wraps(func)
38
def wrapper(*args, **kwargs):
39
tb_clear_frames = os.environ.get('FASTAI_TB_CLEAR_FRAMES', None)
40
if not IS_IN_IPYTHON or tb_clear_frames=="0":
41
return func(*args, **kwargs)
42
43
try:
44
return func(*args, **kwargs)
45
except Exception as e:
46
if ("CUDA out of memory" in str(e) or
47
"device-side assert triggered" in str(e) or
48
tb_clear_frames == "1"):
49
type, val, tb = get_ref_free_exc_info() # must!
50
gc.collect()
51
if "device-side assert triggered" in str(e):
52
warn("""When 'device-side assert triggered' error happens, it's not possible to recover and you must restart the kernel to continue. Use os.environ['CUDA_LAUNCH_BLOCKING']="1" before restarting to debug""")
53
raise type(val).with_traceback(tb) from None
54
else: raise # re-raises the exact last exception
55
return wrapper
56
57
class gpu_mem_restore_ctx():
58
"context manager to reclaim RAM if an exception happened under ipython"
59
def __enter__(self): return self
60
def __exit__(self, exc_type, exc_val, exc_tb):
61
if not exc_val: return True
62
traceback.clear_frames(exc_tb)
63
gc.collect()
64
raise exc_type(exc_val).with_traceback(exc_tb) from None
65
66