[Python] Unable to torch.load due to pickling/safety error

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to use a pytorch model present on this link:

    https://drive.google.com/drive/folders/1wQbRgvOftE9ra-yAC9DnDbmLe_MdSLDt

    since it is used by this project I am trying to run:

    https://github.com/amaljoseph/EndTo...Verification_System_using_YOLOv5-and-CycleGAN

    When I do

    torch.load(model, "cpu")


    I get

    raise pickle.UnpicklingError(_get_wo_message(str(e))) from None
    _pickle.UnpicklingError: Weights only load failed. This file can still be loaded, to do so you have two options, do those steps only if you trust the source of the checkpoint.
    (1) In PyTorch 2.6, we changed the default value of the `weights_only` argument in `torch.load` from `False` to `True`. 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.
    (2) Alternatively, to load with `weights_only=True` please check the recommended steps in the following error message.
    WeightsUnpickler error: Unsupported global: GLOBAL numpy.core.multiarray._reconstruct was not an allowed global by default. Please use `torch.serialization.add_safe_globals([_reconstruct])` or the `torch.serialization.safe_globals([_reconstruct])` context manager to allowlist this global if you trust this class/function.

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


    I don't want to follow suggestion (1) since I don't fully trust the creator, and trying with solution (2) I would do something like:

    from numpy.core.multiarray import _reconstruct
    import torch

    torch.serialization.add_safe_globals([_reconstruct])
    torch.load(model, "cpu")


    or

    with torch.serialization.safe_globals([_reconstruct]):
    torch.load(model, "cpu")


    But I get the exact same error. How can I load the model in a safe way?

    Details:

    • Python version: 3.12.3
    • Pytorch version: 2.6.0+cu124
    • Numpy version: 2.1.3
    • OS: Ubuntu 24.04.2 LTS x86_64

    Continue reading...

Compartilhe esta Página