-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.py
52 lines (40 loc) · 1.35 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from torch import nn
import torch
import threading
def save_model(x, name):
if isinstance(x, nn.DataParallel):
torch.save(x.module.state_dict(), name)
else:
torch.save(x.state_dict(), name)
class AsyncCall(object):
def __init__(self, fnc, callback=None):
self.Callable = fnc
self.Callback = callback
self.result = None
def __call__(self, *args, **kwargs):
self.Thread = threading.Thread(target=self.run, name=self.Callable.__name__, args=args, kwargs=kwargs)
self.Thread.start()
return self
def wait(self, timeout=None):
self.Thread.join(timeout)
if self.Thread.isAlive():
raise TimeoutError
else:
return self.result
def run(self, *args, **kwargs):
self.result = self.Callable(*args, **kwargs)
if self.Callback:
self.Callback(self.result)
class AsyncMethod(object):
def __init__(self, fnc, callback=None):
self.Callable = fnc
self.Callback = callback
def __call__(self, *args, **kwargs):
return AsyncCall(self.Callable, self.Callback)(*args, **kwargs)
def async_func(fnc=None, callback=None):
if fnc is None:
def add_async_callback(f):
return AsyncMethod(f, callback)
return add_async_callback
else:
return AsyncMethod(fnc, callback)