forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_utils.py
79 lines (64 loc) · 2.47 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import torch
def _type(self, new_type=None, async=False):
"""Casts this object to the specified type.
If this is already of the correct type, no copy is performed and the
original object is returned.
Args:
new_type (type or string): The desired type
async (bool): If True, and the source is in pinned memory and
destination is on the GPU or vice versa, the copy is
performed asynchronously with respect to the host.
Otherwise, the argument has no effect.
"""
if new_type is None:
return self.__module__ + '.' + self.__class__.__name__
if isinstance(new_type, str):
new_type = _import_dotted_name(new_type)
if new_type == type(self):
return self
return new_type(self.size()).copy_(self, async)
def _cuda(self, device=None, async=False):
"""Returns a copy of this object in CUDA memory.
If this object is already in CUDA memory and on the correct device, then
no copy is performed and the original object is returned.
Args:
device (int): The destination GPU id. Defaults to the current device.
async (bool): If True and the source is in pinned memory, the copy will
be asynchronous with respect to the host. Otherwise, the
argument has no effect.
"""
if self.is_cuda:
if device is None:
device = torch.cuda.current_device()
if self.get_device() != device:
with torch.cuda.device(device):
return type(self)(self.size()).copy_(self, async)
else:
return self
else:
if device is None:
device = -1
with torch.cuda.device(device):
return self.type(getattr(torch.cuda, self.__class__.__name__), async)
def _range(*args, **kwargs):
return __builtins__['range'](*args, **kwargs)
def _import_dotted_name(name):
components = name.split('.')
obj = __import__(components[0])
for component in components[1:]:
obj = getattr(obj, component)
return obj
# Taken from python 3.5 docs
def _accumulate(iterable, fn=lambda x, y: x + y):
'Return running totals'
# _accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# _accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
try:
total = next(it)
except StopIteration:
return
yield total
for element in it:
total = fn(total, element)
yield total