aerin
aerin

Reputation: 22624

AttributeError: module 'torch' has no attribute "device"

---> 13 device = torch.device({"cuda"} if torch.cuda.is_available() else {"cpu"})
     14
     15

AttributeError: module 'torch' has no attribute 'device'

I'm 99% sure this is because I didn't upgrade pytorch from 0.31 to 0.4 however I can't upgrade pytorch for now.

I need to translate .device (0.4) to something that works in 0.31.

I check the migration document however it doesn't provide how I can convert torch.device in retrospect. Please help!

Upvotes: 3

Views: 24546

Answers (2)

szelesaron
szelesaron

Reputation: 69

In version 1.5

if torch.cuda.is_available():
    device = torch.device("cuda:0")
    print("running on the GPU")
else:
    device = torch.device("cpu")
    print("running on the CPU")

Upvotes: 0

Wasi Ahmad
Wasi Ahmad

Reputation: 37681

torch.cuda.device() is a context manager.

torch.cuda.set_device(0)
# On device 0
with torch.cuda.device(1):
    print("Inside device is 1")    
    # On device 1
print("Outside is still 0")
# On device 0

And the above works from 0.2 version.

Upvotes: 6

Related Questions