Search code examples
pythonpytorch

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!


Solution

  • 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.