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)
| 9 | |
| 10 | |
| 11 | def todevice(batch, device, callback=None, non_blocking=False): |
| 12 | ''' Transfer some variables to another device (i.e. GPU, CPU:torch, CPU:numpy). |
| 13 | |
| 14 | batch: list, tuple, dict of tensors or other things |
| 15 | device: pytorch device or 'numpy' |
| 16 | callback: function that would be called on every sub-elements. |
| 17 | ''' |
| 18 | if callback: |
| 19 | batch = callback(batch) |
| 20 | |
| 21 | if isinstance(batch, dict): |
| 22 | return {k: todevice(v, device) for k, v in batch.items()} |
| 23 | |
| 24 | if isinstance(batch, (tuple, list)): |
| 25 | return type(batch)(todevice(x, device) for x in batch) |
| 26 | |
| 27 | x = batch |
| 28 | if device == 'numpy': |
| 29 | if isinstance(x, torch.Tensor): |
| 30 | x = x.detach().cpu().numpy() |
| 31 | elif x is not None: |
| 32 | if isinstance(x, np.ndarray): |
| 33 | x = torch.from_numpy(x) |
| 34 | if torch.is_tensor(x): |
| 35 | x = x.to(device, non_blocking=non_blocking) |
| 36 | return x |
| 37 | |
| 38 | |
| 39 | to_device = todevice # alias |
no outgoing calls
no test coverage detected