alii-shahh
alii-shahh

Reputation: 31

PyTorch can't find the name?? (NameError: name 'device' is not defined)

sorry - I'm a complete beginner!

I am trying to build a 'mini-system' using the Torchreid libraries from https://kaiyangzhou.github.io/deep-person-reid/index.html#

In their version they use CUDA but my Mac is not compatible with CUDA and it doesn't have a CUDA enabled GPU so I installed the CPU-only version of PyTorch instead - therefore I changed model = model.cuda() to model = model.to(device) and added in device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') as you can see below. I thought this would work but I keep getting the NameError: name 'device' is not defined and I don't know what to do. Please help!

(I also tried putting device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') at the top instead of the bottom to see if it made any difference but I just got another error - NameError: name 'torch' is not defined)

model = torchreid.models.build_model(
    name='resnet50',
    num_classes=datamanager.num_train_pids,
    loss='softmax',
    pretrained=True
)

model = model.to(device)

optimizer = torchreid.optim.build_optimizer(
    model,
    optim='adam',
    lr=0.0003
)

scheduler = torchreid.optim.build_lr_scheduler(
    optimizer,
    lr_scheduler='single_step',
    stepsize=20
)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

Upvotes: 2

Views: 22610

Answers (2)

trsvchn
trsvchn

Reputation: 8981

Define device variable before the usage:

import torch
...
model = torchreid.models.build_model(
    name='resnet50',
    num_classes=datamanager.num_train_pids,
    loss='softmax',
    pretrained=True
)

# Just right before the actual usage
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)
...

Upvotes: 8

Import the torch module.

Put

import torch

at the top of the code.

(And remember always import the libraries you're using)

Upvotes: 0

Related Questions