8000 Improve error message for weights_only load by mikaylagawarecki · Pull Request #129705 · pytorch/pytorch · GitHub
[go: up one dir, main page]

Skip to content

Improve error message for weights_only load #129705

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions test/test_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -1112,6 +1112,22 @@ def fake_set_state(obj, *args):
torch.serialization.clear_safe_globals()
ClassThatUsesBuildInstruction.__setstate__ = None

@parametrize("unsafe_global", [True, False])
def test_weights_only_error(self, unsafe_global):
sd = {'t': TwoTensor(torch.randn(2), torch.randn(2))}
pickle_protocol = torch.serialization.DEFAULT_PROTOCOL if unsafe_global else 5
with BytesIOContext() as f:
torch.save(sd, f, pickle_protocol=pickle_protocol)
f.seek(0)
if unsafe_global:
with self.assertRaisesRegex(pickle.UnpicklingError,
r"use `torch.serialization.add_safe_globals\(\[TwoTensor\]\)` to allowlist"):
torch.load(f, weights_only=True)
else:
with self.assertRaisesRegex(pickle.UnpicklingError,
"file an issue with the following so that we can make `weights_only=True`"):
torch.load(f, weights_only=True)

@parametrize('weights_only', (False, True))
def test_serialization_math_bits(self, weights_only):
t = torch.randn(1, dtype=torch.cfloat)
Expand Down
4 changes: 2 additions & 2 deletions torch/_weights_only_unpickler.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,8 @@ def load(self):
else:
raise RuntimeError(
f"Unsupported global: GLOBAL {full_path} was not an allowed global by default. "
"Please use `torch.serialization.add_safe_globals` to allowlist this global "
"if you trust this class/function."
f"Please use `torch.serialization.add_safe_globals([{name}])` to allowlist "
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just one of the possibly many functions that one would need to add to safe_globals right?
As a follow-up we could maybe get the full list?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here's an issue for this one #129698

"this global if you trust this class/function."
)
elif key[0] == NEWOBJ[0]:
args = self.stack.pop()
Expand Down
36 changes: 29 additions & 7 deletions torch/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import io
import os
import pickle
import re
import shutil
import struct
import sys
Expand Down Expand Up @@ -1107,12 +1108,33 @@ def load(
"""
torch._C._log_api_usage_once("torch.load")
UNSAFE_MESSAGE = (
"Weights only load failed. Re-running `torch.load` with `weights_only` set to `False`"
" will likely succeed, but it can result in arbitrary code execution."
" Do it only if you get the file from a trusted source. Alternatively, to load"
" with `weights_only` please check the recommended steps in the following error message."
" WeightsUnpickler error: "
"Re-running `torch.load` with `weights_only` set to `False` will likely succeed, "
"but it can result in arbitrary code execution. Do it only if you got the file from a "
"trusted source."
)
DOCS_MESSAGE = (
"\n\nCheck the documentation of torch.load to learn more about types accepted by default with "
"weights_only https://pytorch.org/docs/stable/generated/torch.load.html."
)

def _get_wo_message(message: str) -> str:
pattern = r"GLOBAL (\S+) was not an allowed global by default."
has_unsafe_global = re.search(pattern, message) is not None
if has_unsafe_global:
updated_message = (
"Weights only load failed. This file can still be loaded, to do so you have two options "
f"\n\t(1) {UNSAFE_MESSAGE}\n\t(2) Alternatively, to load with `weights_only=True` please check "
"the recommended steps in the following error message.\n\tWeightsUnpickler error: "
+ message
)
else:
updated_message = (
f"Weights only load failed. {UNSAFE_MESSAGE}\n Please file an issue with the following "
"so that we can make `weights_only=True` compatible with your use case: WeightsUnpickler "
"error: " + message
)
return updated_message + DOCS_MESSAGE

if weights_only is None:
weights_only, warn_weights_only = False, True
else:
Expand Down Expand Up @@ -1200,7 +1222,7 @@ def load(
**pickle_load_args,
)
except RuntimeError as e:
raise pickle.UnpicklingError(UNSAFE_MESSAGE + str(e)) from None
raise pickle.UnpicklingError(_get_wo_message(str(e))) from None
return _load(
opened_zipfile,
map_location,
Expand All @@ -1224,7 +1246,7 @@ def load(
**pickle_load_args,
)
except RuntimeError as e:
raise pickle.UnpicklingError(UNSAFE_MESSAGE + str(e)) from None
raise pickle.UnpicklingError(_get_wo_message(str(e))) from None
return _legacy_load(
opened_file, map_location, pickle_module, **pickle_load_args
)
Expand Down
Loading
0