Pyinstaller executable fails importing torchvision

风格不统一 提交于 2020-06-27 08:29:10

问题


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...


回答1:


Downgrade torchvision to the previous version fix the error.

pip uninstall torchvision
pip install torchvision==0.2.2.post3



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/56325181/pyinstaller-executable-fails-importing-torchvision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!