Changing default device¶
It is common practice to write PyTorch code in a device-agnostic way,
and then switch between CPU and CUDA depending on what hardware is available.
Typically, to do this you might have used if-statements and
to do this:
This recipe requires PyTorch 2.0.0 or later.
PyTorch now also has a context manager which can take care of the device transfer automatically. Here is an example:
You can also set it globally like this:
This function imposes a slight performance cost on every Python call to the torch API (not just factory functions). If this is causing problems for you, please comment on this issue
Total running time of the script: ( 0 minutes 0.005 seconds)