Device placement function, allow user to specify which device to place model or tensor Args: framework (str): tensorflow or pytorch. device (str): gpu or cpu to use, if you want to specify certain gpu, use gpu:$gpu_id or cuda:$gpu_id. Returns: Context
(framework, device_name='gpu:0')
| 38 | |
| 39 | @contextmanager |
| 40 | def device_placement(framework, device_name='gpu:0'): |
| 41 | """ Device placement function, allow user to specify which device to place model or tensor |
| 42 | Args: |
| 43 | framework (str): tensorflow or pytorch. |
| 44 | device (str): gpu or cpu to use, if you want to specify certain gpu, |
| 45 | use gpu:$gpu_id or cuda:$gpu_id. |
| 46 | |
| 47 | Returns: |
| 48 | Context manager |
| 49 | |
| 50 | Examples: |
| 51 | |
| 52 | >>> # Requests for using model on cuda:0 for gpu |
| 53 | >>> with device_placement('pytorch', device='gpu:0'): |
| 54 | >>> model = Model.from_pretrained(...) |
| 55 | """ |
| 56 | device_type, device_id = verify_device(device_name) |
| 57 | |
| 58 | if framework == Frameworks.tf: |
| 59 | import tensorflow as tf |
| 60 | if device_type == Devices.gpu and not tf.test.is_gpu_available(): |
| 61 | logger.debug( |
| 62 | 'tensorflow: cuda is not available, using cpu instead.') |
| 63 | device_type = Devices.cpu |
| 64 | if device_type == Devices.cpu: |
| 65 | with tf.device('/CPU:0'): |
| 66 | yield |
| 67 | else: |
| 68 | if device_type == Devices.gpu: |
| 69 | with tf.device(f'/device:gpu:{device_id}'): |
| 70 | yield |
| 71 | |
| 72 | elif framework == Frameworks.torch: |
| 73 | import torch |
| 74 | if device_type == Devices.gpu: |
| 75 | if torch.cuda.is_available(): |
| 76 | torch.cuda.set_device(f'cuda:{device_id}') |
| 77 | else: |
| 78 | logger.debug( |
| 79 | 'pytorch: cuda is not available, using cpu instead.') |
| 80 | yield |
| 81 | else: |
| 82 | yield |
| 83 | |
| 84 | |
| 85 | def create_device(device_name): |
searching dependent graphs…