Cannot import torch in Jupyter lab after following instructions

Hello, I cannot import Torch into Jupyter notebooks.

I installed anaconda and then installed Torch using the Anaconda method (from here: https://pytorch.org/get-started/locally/ )

conda install pytorch torchvision -c pytorch

But then when I try to import torch into Jupyter notebooks I get an error message, that the module is not found. This seems bizarre as I followed all the instructions correctly, and the torch installation apparently worked.

I would greatly appreciate any help as I have been trying to resolve this for days with no luck.

Environment set-up is inherently complex. Even if you followed the directions now, it can be hard to rectify things if you had done something in the past. There is a lot of help on stackoverflow about ways to go about determining where your Jupyter notebooks are running from. (See here for links to just a few of them I had collected.) However, if you can afford the space on your drive to not really care about installing twice in different places, I’d suggest just at this point running the following command inside a running notebook:

%conda install -c pytorch pytorch torchvision

That magic , noted by the percent symbol at the start, is the latest way to insure in Jupyter things get installed in the environment your notebooks are using. After that command is run, your import should work. For completeness, I’ll add there is a related %pip install magic command to also run in notebook cells.

You can see more about those new-ish magic commands and how they are now the best way to do installs to the same environment your kernel is running from here. More explanation/background can be seen here (way down on the page about the new magic for improving the mechanism) and here.

2 Likes