-
Notifications
You must be signed in to change notification settings - Fork 10
/
utils.py
31 lines (28 loc) · 818 Bytes
/
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
import torch
from torch.autograd import Variable
def to_var(var):
if torch.is_tensor(var):
var = Variable(var)
if torch.cuda.is_available():
var = var.cuda()
return var
if isinstance(var, int) or isinstance(var, float) or isinstance(var, str):
return var
if isinstance(var, dict):
for key in var:
var[key] = to_var(var[key])
return var
if isinstance(var, list):
var = map(lambda x: to_var(x), var)
return var
def stop_gradient(x):
if isinstance(x, float):
return x
if isinstance(x, tuple):
return tuple(map(lambda y: Variable(y.data), x))
return Variable(x.data)
def zero_var(sz):
x = Variable(torch.zeros(sz))
if torch.cuda.is_available():
x = x.cuda()
return x