解决Error loading model: Weights only load failed. 报错
文章摘要:PyTorch 2.6+版本中torch.load()默认启用weights_only=True参数,导致加载含自定义类ultralytics.nn.tasks.DetectionModel的模型文件时失败。解决方法有两种:1)在可信源前提下使用weights_only=False加载;2)通过add_safe_globals()将自定义类加入白名单。建议在模型加载时显式添加ckpt =
·
具体报错:
Error loading model: 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 ultralytics.nn.tasks.DetectionModel was not an allowed global by default. Please use `torch.serialization.add_safe_globals([ultralytics.nn.tasks.DetectionModel])` or the `torch.serialization.safe_globals([ultralytics.nn.tasks.DetectionModel])` 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 torch.load — PyTorch 2.7 documentation torch.load — PyTorch 2.7 documentation .
原因: PyTorch 2.6+ 默认启用 weights_only=True 导致的加载失败
PyTorch 2.6 起,torch.load 的默认参数变成了 weights_only=True,只允许反序列化 白名单内 的类型。
你的权重文件里保存了 自定义类 ultralytics.nn.tasks.DetectionModel,它不在白名单里,于是 torch.load 拒绝加载并给出提示。
解决方法:在模型加载处添加weights_only=False
ckpt = torch.load('yolo11n.pt', weights_only=False)
更多推荐
所有评论(0)