| 34 | |
| 35 | |
| 36 | class Util: |
| 37 | def __init__(self, device): |
| 38 | self.device = device |
| 39 | self.USE_CUDA = True if 'cuda' in device.type else False |
| 40 | |
| 41 | def to_numpy(self, var, is_deep_copy=True): |
| 42 | |
| 43 | # list type [ Tensor, Tensor ] |
| 44 | if isinstance(var, list) and len(var) > 0: |
| 45 | var_ = [] |
| 46 | for v in var: |
| 47 | temp = v.cpu().data.numpy() if self.USE_CUDA else v.data.numpy() |
| 48 | |
| 49 | # this part is meaningless if Tensor is in gpu |
| 50 | if is_deep_copy: |
| 51 | var_.append(copy.deepcopy(temp)) |
| 52 | return var_ |
| 53 | |
| 54 | # dict type { key, Tensor } |
| 55 | if isinstance(var, dict) and len(var) > 0: |
| 56 | var_ = {} |
| 57 | for k, v in var.iteritems(): |
| 58 | temp = v.cpu().data.numpy() if self.USE_CUDA else v.data.numpy() |
| 59 | |
| 60 | # this part is meaningless if Tensor is in gpu |
| 61 | if is_deep_copy: |
| 62 | var_[k] = copy.deepcopy(temp) |
| 63 | return var_ |
| 64 | |
| 65 | var = var.cpu().data.numpy() if self.USE_CUDA else var.data.numpy() |
| 66 | # this part is meaningless if Tensor is in gpu |
| 67 | if is_deep_copy: |
| 68 | var = copy.deepcopy(var) |
| 69 | return var |
| 70 | |
| 71 | def to_tensor(self, ndarray, requires_grad=False, is_deep_copy=True): |
| 72 | if ndarray is None: |
| 73 | return ndarray |
| 74 | |
| 75 | # this part is meaningless if tensor is in gpu |
| 76 | if is_deep_copy: |
| 77 | ndarray = copy.deepcopy(ndarray) |
| 78 | |
| 79 | if isinstance(ndarray, list) and len(ndarray) > 0: |
| 80 | var_ = [] |
| 81 | for v in ndarray: |
| 82 | temp = torch.from_numpy(v) |
| 83 | temp = temp.to(self.device) |
| 84 | temp.requires_grad = requires_grad |
| 85 | var_.append(temp) |
| 86 | return var_ |
| 87 | if isinstance(ndarray, dict) and len(ndarray) > 0: |
| 88 | var_ = {} |
| 89 | for k, v in ndarray.iteritems(): |
| 90 | temp = torch.from_numpy(v) |
| 91 | temp = temp.to(self.device) |
| 92 | temp.requires_grad = requires_grad |
| 93 | var_[k] = temp |