Returns a context manager that specifies the default device to use. The `device_name_or_function` argument may either be a device name string, a device function, or None: * If it is a device name string, all operations constructed in this context will be assigned to the device wi
(self, device_name_or_function)
| 4326 | |
| 4327 | @tf_contextlib.contextmanager |
| 4328 | def device(self, device_name_or_function): |
| 4329 | # pylint: disable=line-too-long |
| 4330 | """Returns a context manager that specifies the default device to use. |
| 4331 | |
| 4332 | The `device_name_or_function` argument may either be a device name |
| 4333 | string, a device function, or None: |
| 4334 | |
| 4335 | * If it is a device name string, all operations constructed in |
| 4336 | this context will be assigned to the device with that name, unless |
| 4337 | overridden by a nested `device()` context. |
| 4338 | * If it is a function, it will be treated as a function from |
| 4339 | Operation objects to device name strings, and invoked each time |
| 4340 | a new Operation is created. The Operation will be assigned to |
| 4341 | the device with the returned name. |
| 4342 | * If it is None, all `device()` invocations from the enclosing context |
| 4343 | will be ignored. |
| 4344 | |
| 4345 | For information about the valid syntax of device name strings, see |
| 4346 | the documentation in |
| 4347 | [`DeviceNameUtils`](https://www.tensorflow.org/code/tensorflow/core/util/device_name_utils.h). |
| 4348 | |
| 4349 | For example: |
| 4350 | |
| 4351 | ```python |
| 4352 | with g.device('/device:GPU:0'): |
| 4353 | # All operations constructed in this context will be placed |
| 4354 | # on GPU 0. |
| 4355 | with g.device(None): |
| 4356 | # All operations constructed in this context will have no |
| 4357 | # assigned device. |
| 4358 | |
| 4359 | # Defines a function from `Operation` to device string. |
| 4360 | def matmul_on_gpu(n): |
| 4361 | if n.type == "MatMul": |
| 4362 | return "/device:GPU:0" |
| 4363 | else: |
| 4364 | return "/cpu:0" |
| 4365 | |
| 4366 | with g.device(matmul_on_gpu): |
| 4367 | # All operations of type "MatMul" constructed in this context |
| 4368 | # will be placed on GPU 0; all other operations will be placed |
| 4369 | # on CPU 0. |
| 4370 | ``` |
| 4371 | |
| 4372 | **N.B.** The device scope may be overridden by op wrappers or |
| 4373 | other library code. For example, a variable assignment op |
| 4374 | `v.assign()` must be colocated with the `tf.Variable` `v`, and |
| 4375 | incompatible device scopes will be ignored. |
| 4376 | |
| 4377 | Args: |
| 4378 | device_name_or_function: The device name or function to use in the |
| 4379 | context. |
| 4380 | |
| 4381 | Yields: |
| 4382 | A context manager that specifies the default device to use for newly |
| 4383 | created ops. |
| 4384 | |
| 4385 | Raises: |