Skip to content

Instantly share code, notes, and snippets.

@githubfoam
Created December 30, 2019 23:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save githubfoam/588c7ffb1349f4cf7f1035ebed8a6b88 to your computer and use it in GitHub Desktop.
Save githubfoam/588c7ffb1349f4cf7f1035ebed8a6b88 to your computer and use it in GitHub Desktop.
cuda cheat sheet
#check if pytorch is using the GPU
python -c 'import torch; print(torch.cuda.is_available())' #should print True
python -c 'import torch; print(torch.rand(2,3).cuda())'
watch -n 2 nvidia-smi
=========================================================================
import torch
dev = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
t1 = torch.randn(1,2)
t2 = torch.randn(1,2).to(dev)
print(t1) # tensor([[-0.2678, 1.9252]])
print(t2) # tensor([[ 0.5117, -3.6247]], device='cuda:0')
t1.to(dev)
print(t1) # tensor([[-0.2678, 1.9252]])
print(t1.is_cuda) # False
t1=t1.to(dev)
print(t1) # tensor([[-0.2678, 1.9252]], device='cuda:0')
print(t1.is_cuda) # True
model = M() # not on cuda
model.to(dev) # is on cuda (all parameters)
print(next(model.parameters()).is_cuda) #True
=========================================================================
# setting device on GPU if available, else CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
print()
#Additional Info when using cuda
if device.type == 'cuda':
print(torch.cuda.get_device_name(0))
print('Memory Usage:')
print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
print('Cached: ', round(torch.cuda.memory_cached(0)/1024**3,1), 'GB')
=========================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment