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)
| 23 | |
| 24 | |
| 25 | def 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 | |
| 53 | to_device = todevice # alias |