MCPcopy Create free account
hub / github.com/Inception3D/TTT3R / todevice

Function todevice

viser_utils.py:25–50  ·  view source on GitHub ↗

Transfer some variables to another device (i.e. GPU, CPU:torch, CPU:numpy). batch: list, tuple, dict of tensors or other things device: pytorch device or 'numpy' callback: function that would be called on every sub-elements.

(batch, device, callback=None, non_blocking=False)

Source from the content-addressed store, hash-verified

23
24
25def todevice(batch, device, callback=None, non_blocking=False):
26 """Transfer some variables to another device (i.e. GPU, CPU:torch, CPU:numpy).
27
28 batch: list, tuple, dict of tensors or other things
29 device: pytorch device or 'numpy'
30 callback: function that would be called on every sub-elements.
31 """
32 if callback:
33 batch = callback(batch)
34
35 if isinstance(batch, dict):
36 return {k: todevice(v, device) for k, v in batch.items()}
37
38 if isinstance(batch, (tuple, list)):
39 return type(batch)(todevice(x, device) for x in batch)
40
41 x = batch
42 if device == "numpy":
43 if isinstance(x, torch.Tensor):
44 x = x.detach().cpu().numpy()
45 elif x is not None:
46 if isinstance(x, np.ndarray):
47 x = torch.from_numpy(x)
48 if torch.is_tensor(x):
49 x = x.to(device, non_blocking=non_blocking)
50 return x
51
52
53to_device = todevice # alias

Callers 1

to_numpyFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected