Pytorch doesn't work with CUDA in PyCharm/IntelliJ

Question:

I have just downloaded PyTorch with CUDA via Anaconda and when I type into the Anaconda terminal:

import torch
if torch.cuda.is_available():
    print('it works')

then he outputs that; that means that it worked and it works with PyTorch.

But when I go to my IDE (PyCharm and IntelliJ) and write the same code, it doesn’t output anything.

Could someone please explain to me how I can somehow get this to work in the IDE?

Asked By: basti394

||

Answers:

It was driving me mad as well… What finally helped me was the first link that says to use PyCharm "Terminal" to run the pip install command (from the PyTorch website). That fixed all my problems. (I had installed pytorch 3 times by that time and tried different interpreters…)

https://www.datasciencelearner.com/how-to-install-pytorch-in-pycharm/

pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio===0.8.0 -f https://download.pytorch.org/whl/torch_stable.html

I hope this helps save someone hours of headache. 🙂

Answered By: Entony

I also spent over 10 hours trying to figure out what was wrong. I ended up checking if there is something wrong with interpreter.
What was the problem is version of python (I had v. 3.8). After upgrading to newest version, problem was solved.

Check your version using command:

python --version

If your version is old (current is 3.9.2), install newest one from official python site:
https://www.python.org/downloads/release/python-392/

After installation make sure you using newer version (use command above)

Answered By: Drogheda

Another possible root of the problem is running a Flatpak version of Pycharm. Took me some time to figure out, but Flatpak does not load user specific environment variables files (i.e. ~/.profile, ~/.bash_profile and conda environment). I have deleted Flatpak version and installed a snap version (sudo snap install [pycharm-professional|pycharm-community] --classic) and it loads the proper PATH which allows loading CUDA correctly.

Answered By: the-lay

I had a similar issue.

Inspired by @the-lay answer, calling import os; os.system('') resolved my issue.

Answered By: Yuval Atzmon

An addition to entonys answer: (Thank you Entony!)

This command didn’t give me dependency errors in PyCharm:

pip install torch==1.13.0+cu117 torchvision==0.14.0+cu117 torchaudio===0.13.0 -f https://download.pytorch.org/whl/torch_stable.html

Answered By: tejal