Skip to content

Commit 2d5b310

Browse files
BashkirovNstubbeljktromp1
authored andcommitted
Added ScriptFunction pkl exception for issue pytorch#61210 pytorch#61381 (pytorch#67076)
Summary: Fixes pytorch#61381, pytorch#61210 Pull Request resolved: pytorch#67076 Reviewed By: jbschlosser Differential Revision: D32908175 Pulled By: suo fbshipit-source-id: f6e175793243dc96cde5e44022d92f2623b934eb Co-authored-by: LucaStubbe <[email protected]> Co-authored-by: Kanon Tromp <[email protected]>
1 parent d21646c commit 2d5b310

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

test/test_jit.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,15 @@ def fn(x):
383383
files = zipfile.ZipFile(buf).filelist
384384
self.assertTrue(any(['archive/constants.pkl' == f.filename for f in files]))
385385

386+
def test_script_fn_pkl(self):
387+
with self.assertRaisesRegex(pickle.PickleError, "ScriptFunction cannot be pickled"):
388+
389+
@torch.jit.script
390+
def fn(x: torch.Tensor) -> torch.Tensor:
391+
return x
392+
393+
pkl_fn = pickle.dumps(fn, protocol=0)
394+
386395
def test_restore_device(self):
387396
class M(torch.jit.ScriptModule):
388397
def __init__(self, cpu_device_str):

torch/jit/_script.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,13 @@
5656
"""
5757
set_module(ScriptFunction, "torch.jit")
5858

59+
# Throws an error if a jit function is pickled.
60+
# Helps to avoid Python crashes for Python versions 3.9.5 + when protocol 0 or 1 is given as an argument.
61+
def _reduce(cls):
62+
raise pickle.PickleError("ScriptFunction cannot be pickled")
63+
64+
ScriptFunction.__reduce__ = _reduce # type: ignore[assignment]
65+
5966

6067
if _enabled:
6168
Attribute = collections.namedtuple("Attribute", ["value", "type"])

0 commit comments

Comments
 (0)