Is it safe to have device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") at the top of every of my files?

Is it safe to have:

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

there is not some unexpected error that can happen right?

If I import stuff those files will use the right device cuz they are all ran on the same machine, right?

(cuz I don’t really like using globals so I was trying to avoid that…but I can’t figure out what the standard in pytorch is or what is safe or distinguish between them…)

If cuda is available this code will automatically run in cuda. If you want to have options you can manually mention using some flags.