C2MV commited on
Commit
f62d0aa
1 Parent(s): 5a4e280

Create decorators.py

Browse files
Files changed (1) hide show
  1. decorators.py +36 -0
decorators.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # decorators.py
2
+
3
+ import functools
4
+ import torch
5
+ import threading
6
+ import time
7
+
8
+ class spaces:
9
+ @staticmethod
10
+ def GPU(duration=0):
11
+ def decorator(func):
12
+ @functools.wraps(func)
13
+ def wrapper(*args, **kwargs):
14
+ if not torch.cuda.is_available():
15
+ raise RuntimeError("GPU is not available.")
16
+
17
+ result = [None]
18
+ exception = [None]
19
+
20
+ def target():
21
+ try:
22
+ result[0] = func(*args, **kwargs)
23
+ except Exception as e:
24
+ exception[0] = e
25
+
26
+ thread = threading.Thread(target=target)
27
+ thread.start()
28
+ thread.join(duration)
29
+
30
+ if thread.is_alive():
31
+ raise TimeoutError(f"Function execution exceeded {duration} seconds.")
32
+ if exception[0]:
33
+ raise exception[0]
34
+ return result[0]
35
+ return wrapper
36
+ return decorator