Skip to content

Add changing default device recipe #2220

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 25 commits into from
Mar 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions recipes_source/recipes/changing_default_device.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
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 ``cuda()`` calls
to do this:

"""
import torch

USE_CUDA = False

mod = torch.nn.Linear(20, 30)
if USE_CUDA:
mod.cuda()

device = 'cpu'
if USE_CUDA:
device = 'cuda'
inp = torch.randn(128, 20, device=device)
print(mod(inp).device)

###################################################################
# PyTorch now also has a context manager which can take care of the
# device transfer automatically. Here is an example:

with torch.device('cuda'):
mod = torch.nn.Linear(20, 30)
print(mod.weight.device)
print(mod(torch.randn(128, 20)).device)

#########################################
# You can also set it globally like this:

torch.set_default_device('cuda')

mod = torch.nn.Linear(20, 30)
print(mod.weight.device)
print(mod(torch.randn(128, 20)).device)

################################################################
# 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 <https://github.com/pytorch/pytorch/issues/92701>`__