Put the data to the target cuda device just before the forward function. Args: batch: The batch data out of the dataloader. device: (str | torch.device): The target device for the data. Returns: The data to the target device.
(batch, device, non_blocking=False)
| 7 | |
| 8 | |
| 9 | def to_device(batch, device, non_blocking=False): |
| 10 | """Put the data to the target cuda device just before the forward function. |
| 11 | Args: |
| 12 | batch: The batch data out of the dataloader. |
| 13 | device: (str | torch.device): The target device for the data. |
| 14 | |
| 15 | Returns: The data to the target device. |
| 16 | |
| 17 | """ |
| 18 | if isinstance(batch, ModelOutputBase): |
| 19 | for idx in range(len(batch)): |
| 20 | batch[idx] = to_device(batch[idx], device) |
| 21 | return batch |
| 22 | elif isinstance(batch, dict) or isinstance(batch, Mapping): |
| 23 | if hasattr(batch, '__setitem__'): |
| 24 | # Reuse mini-batch to keep attributes for prediction. |
| 25 | for k, v in batch.items(): |
| 26 | batch[k] = to_device(v, device) |
| 27 | return batch |
| 28 | else: |
| 29 | return type(batch)( |
| 30 | {k: to_device(v, device) |
| 31 | for k, v in batch.items()}) |
| 32 | elif isinstance(batch, (tuple, list)): |
| 33 | return type(batch)(to_device(v, device) for v in batch) |
| 34 | elif isinstance(batch, torch.Tensor): |
| 35 | return batch.to(device, non_blocking=non_blocking) |
| 36 | else: |
| 37 | return batch |
searching dependent graphs…