Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyinstaller executable fails importing torchvision

This is my main.py:

import torchvision
input("Press key")

It runs correctly in the command line: python main.py

I need an executable for windows. So I did : pyinstaller main.py

But when I launched the main.exe, inside /dist/main I got this error:

Traceback (most recent call last):
  File "main.py", line 1, in <module>

  ... (omitted)

  File "site-packages\torchvision\ops\misc.py", line 135, in <module>
  File "site-packages\torchvision\ops\misc.py", line 148, in FrozenBatchNorm2d
  File "site-packages\torch\jit\__init__.py", line 850, in script_method
  File "site-packages\torch\jit\frontend.py", line 152, in get_jit_def
  File "inspect.py", line 973, in getsource
  File "inspect.py", line 955, in getsourcelines
  File "inspect.py", line 786, in findsource
OSError: could not get source code
[2836] Failed to execute script main

It seems that some source code is not correctly imported from pyinstaller. I am not sure if the problems is the torch module or torchvision.

Additional info:

  • I recently installed Visual Studio 2019

System info:

  • Window 10
  • Python 3.7
  • torch-1.1.0
  • torchvision-0.3.0

[EDIT]

I found that the problem is in the definition of the class FrozenBatchNorm2d inside torchvision. The following script produce the same error as the one before posted:

main.py

import torch

class FrozenBatchNorm2d(torch.jit.ScriptModule):

    def __init__(self, n):
        super(FrozenBatchNorm2d, self).__init__()

    @torch.jit.script_method

    def forward(self):
        pass

I copied all the torch source file. But I still got the error...

like image 966
FabioDev Avatar asked May 27 '19 11:05

FabioDev


3 Answers

Downgrade torchvision to the previous version fix the error.

pip uninstall torchvision
pip install torchvision==0.2.2.post3
like image 181
FabioDev Avatar answered Nov 17 '22 15:11

FabioDev


Try this monkey patch.

def script_method(fn, _rcb=None):
    return fn
def script(obj, optimize=True, _frames_up=0, _rcb=None):
    return obj    
import torch.jit
torch.jit.script_method = script_method 
torch.jit.script = script
like image 33
Sebastijan Sebi Stevanovic Avatar answered Nov 17 '22 17:11

Sebastijan Sebi Stevanovic


The monkey patch didn't work for me since I had the error when importing torch.jit.

So before importing torch I used the following workaround in my main.py:

os.environ["PYTORCH_JIT"] = "0"

Obviously you lose the JIT optimization but at least, the executable works.

like image 1
Shiriru Avatar answered Nov 17 '22 17:11

Shiriru