liznerski / fcdd

Repository for the Explainable Deep One-Class Classification paper
MIT License
225 stars 62 forks source link

"OsError: Can't get source code <function>" when Packaging FCDD using PyInstaller #37

Closed GreatScherzo closed 2 years ago

GreatScherzo commented 2 years ago

After packaging FCDD using PyInstaller, a bug within torch seems to prevent the packaged program to run smoothly. I was able to solve this, and I hope this can be solved within FCDD.

Details

After packaging FCDD and running the exe file, I got an exception and traceback as below.

image

It turns out there's a bug within torchvision. More on this bug can be found here. FCDD uses the Kornia library, which in turn uses torch.jit.script (at kornia\ jit\init.py), which causes the problem to occur.

Replacing jit.script with jit._script_if_tracing as below seems to solve it.

import torch
import kornia as K

#ORIGINAL
# # expose functions to torch.jit
# # TODO: find an automatic way to do this
# rgb_to_grayscale = torch.jit.script(K.color.rgb_to_grayscale)
# bgr_to_grayscale = torch.jit.script(K.color.bgr_to_grayscale)
#
# spatial_soft_argmax2d = torch.jit.script(K.geometry.spatial_soft_argmax2d)
# spatial_softmax2d = torch.jit.script(K.geometry.dsnt.spatial_softmax2d)
# spatial_expectation2d = torch.jit.script(K.geometry.dsnt.spatial_expectation2d)
# render_gaussian2d = torch.jit.script(K.geometry.dsnt.render_gaussian2d)
# warp_perspective = torch.jit.script(K.geometry.warp_perspective)

# monkey patch
bgr_to_grayscale = torch.jit._script_if_tracing(K.color.bgr_to_grayscale)
rgb_to_grayscale = torch.jit._script_if_tracing(K.color.rgb_to_grayscale)

spatial_soft_argmax2d = torch.jit._script_if_tracing(K.geometry.spatial_soft_argmax2d)
spatial_softmax2d = torch.jit._script_if_tracing(K.geometry.dsnt.spatial_softmax2d)
spatial_expectation2d = torch.jit._script_if_tracing(K.geometry.dsnt.spatial_expectation2d)
render_gaussian2d = torch.jit._script_if_tracing(K.geometry.dsnt.render_gaussian2d)
warp_perspective = torch.jit._script_if_tracing(K.geometry.warp_perspective)

I hope this can be a reference for others!