Trouble importing Pytorch from a MATLAB code

18 views (last 30 days)
Byungwoo
Byungwoo on 30 Aug 2023
Answered: Neha on 4 Sep 2023
Hi,
I'm getting an error when I'm trying to Import Pytorch from MATLAB. I'm using Windows 10, and MATLAB version is R2021a Update5. Here is how to reproduce this error.
  1. Create a conda environment with Python version 3.8: conda create -n torch python=3.8
  2. Activate the enviornment and donwload pytorch (https://pytorch.org/): conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
  3. In a terminal (say Anaconda Powershell Prompt), type python and inside the interactive mode, type import torch. It imports without a problem.
  4. In a matlab, Do pe = pyenv('Version', 'C:\Users\scanimage\anaconda3\envs\torch\python'). It loads python without a problem. For example, py.importlib.import_module('numpy') loads numpy correctly.
  5. But, py.importlib.import_module('torch') produces the following error.
Python Error: OSError: [WinError 127] The specified procedure could not be found. Error loading
"C:\Users\scanimage\anaconda3\envs\torch\lib\site-packages\torch\lib\nvfuser_codegen.dll" or one of its dependencies.
Error in <frozen importlib>_call_with_frames_removed (line 219)
Error in <frozen importlib>exec_module (line 843)
Error in <frozen importlib>_load_unlocked (line 671)
Error in <frozen importlib>_find_and_load_unlocked (line 975)
Error in <frozen importlib>_find_and_load (line 991)
Error in <frozen importlib>_gcd_import (line 1014)
Error in __init__>import_module (line 127)
This problem persists when I use cuda the version 11.7, But goes away when I install the CPU only version of Pytorch. Could you please help me solve this issue as it is important for me to run GPU version of PyTorch from MATLAB?

Answers (1)

Neha
Neha on 4 Sep 2023
Hi Byungwoo,
I understand that you are facing some errors while importing PyTorch from MATLAB. To resolve this, please ensure that you have set the path to the python file executable using "pyenv".
pyenv('Version', '<path-to-python-executable')
If the path has already been set, the issue is caused by a library conflict. You can set the MATLAB execution mode to "OutOfProcess" to resolve the issue. Please refer to the following documentation link for more information:
Hope this helps!

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!