Traceback (most recent call last): File "D:\深度学习\InsightFace_Pytorch-\InsightFace_Pytorch-master\face_verify.py", line 40, in <module> targets, names = load_facebank(conf) File "D:\深度学习\InsightFace_Pytorch-\InsightFace_Pytorch-master\utils.py", line 70, in load_facebank embeddings = torch.load(conf.facebank_path/'facebank.pth') File "D:\深度学习\venv\lib\site-packages\torch\serialization.py", line 795, in load return _legacy_load(opened_file, map_location, pickle_module, **pickle_load_args) File "D:\深度学习\venv\lib\site-packages\torch\serialization.py", line 1002, in _legacy_load magic_number = pickle_module.load(f, **pickle_load_args) _pickle.UnpicklingError: invalid load key, 'v'.
时间: 2023-08-30 22:07:10 浏览: 226
这个错误通常是由于尝试反序列化一个被破坏或篡改的 pickle 对象导致的。这可能是因为 pickle 对象已经被篡改,或者是因为它是在不同版本的 Python 中创建的,导致了不兼容的 pickle 协议版本。你可以尝试使用其他的 unpickling 库(如 `pickletools`)来分析 pickle 对象并找出问题所在。如果你无法解决问题,最好的方法可能是重新创建 pickle 对象,并确保在序列化和反序列化过程中使用相同的 Python 版本和 pickle 协议版本。
相关问题
Traceback (most recent call last): File "/home/book/rk3566/ai_tools/yolov5-face-master/detect_face.py", line 224, in <module> model = load_model(opt.weights, device) File "/home/book/rk3566/ai_tools/yolov5-face-master/detect_face.py", line 30, in load_model model = attempt_load(weights, map_location=device) # load FP32 model File "/home/book/rk3566/ai_tools/yolov5-face-master/models/experimental.py", line 118, in attempt_load model.append(torch.load(w, map_location=map_location)['model'].float().fuse().eval()) # load FP32 model File "/home/book/anaconda3/envs/yolov5face/lib/python3.9/site-packages/torch/serialization.py", line 1470, in load 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. 报了新错误
<think>好的,用户现在遇到了一个新的错误,是关于PyTorch在加载模型权重时的UnpicklingError。首先,我需要仔细看一下错误信息,理解问题出在哪里。
根据用户提供的Traceback,错误发生在加载模型的时候,具体是在尝试使用torch.load加载权重文件时出现的。错误信息提到“Weights only load failed”,并且建议两种解决方法:要么在torch.load中设置weights_only=False,但要注意安全风险;要么将特定的全局变量添加到安全列表中。用户还提到了numpy.core.multiarray._reconstruct未被允许,导致加载失败。
首先,我需要回忆一下PyTorch的版本变化。在PyTorch 2.6之后,torch.load的默认参数weights_only从False改成了True,这意味着默认情况下只允许加载受信任的权重文件,以防止潜在的恶意代码执行。当用户使用较新版本的PyTorch加载旧版本保存的模型时,可能会遇到这个问题,特别是如果模型权重包含了需要反序列化的对象,而这些对象不在PyTorch的安全列表中。
接下来,我需要考虑用户可能的环境配置。用户之前可能使用的是PyTorch 2.6或更高版本,而他们下载的yolov5s-face.pt模型文件可能是用旧版本的PyTorch保存的,或者包含了需要额外权限的序列化对象,比如numpy的某些函数。
现在需要确定解决方案。根据错误提示,有两种方法:一种是设置weights_only=False,但需要用户确认模型来源可信;另一种是使用add_safe_globals将numpy的_reconstruct函数添加到安全列表中。不过,修改模型加载的代码可能对用户来说比较复杂,特别是如果他们不熟悉PyTorch内部的话。因此,最简单的解决方案是建议用户在使用torch.load时设置weights_only=False,或者降级PyTorch到2.6之前的版本。
但用户可能已经按照之前的指导调整了命令行参数,现在遇到的是模型加载的问题。这时候需要确保用户是否信任模型文件的来源,如果信任,可以指导他们修改detect_face.py中的load_model函数,在加载时添加weights_only=False参数。不过用户可能需要找到代码中调用torch.load的位置,通常是models/experimental.py中的attempt_load函数,修改那里的参数。
另外,考虑到用户可能不太熟悉代码修改,可能需要给出具体的代码修改示例,比如在加载模型的地方添加相应的参数。同时,也需要提醒用户注意安全风险,确保模型文件来源可靠。
此外,检查PyTorch版本也是一个关键点。如果用户使用的是PyTorch 2.6或更高版本,而模型是用旧版本保存的,可能需要调整。如果用户不想修改代码,降级PyTorch到2.5或更早版本可能解决问题,但需要指导他们如何操作。
总结下来,用户的错误是由于PyTorch版本升级导致的默认安全设置变化,解决方案包括调整加载参数、添加安全全局变量或降级PyTorch。需要根据用户的技术水平选择最合适的建议,并详细说明步骤,同时强调安全注意事项。</think>---
### **错误原因分析**
该错误由 **PyTorch 2.6+ 版本安全限制升级** 引发。关键信息如下:
1. **安全策略变更**:PyTorch 2.6 开始,`torch.load()` 默认启用 `weights_only=True`,禁止加载包含非受信序列化对象(如某些 numpy 函数)的模型文件
2. **模型文件依赖**:`yolov5s-face.pt` 可能包含旧版 PyTorch 生成的依赖项(如 `numpy.core.multiarray._reconstruct`)
---
### **解决方案**
#### 方法一:强制信任模型(推荐)
在 `detect_face.py` 中找到模型加载代码,**添加 `weights_only=False`**:
```python
# 原代码(models/experimental.py 中)
model.append(torch.load(w, map_location=map_location)['model'].float().fuse().eval())
# 修改为
model.append(torch.load(w, map_location=map_location, weights_only=False)['model'].float().fuse().eval())
```
#### 方法二:降级 PyTorch 版本
```bash
pip install torch==2.0.0 # 降级到 PyTorch 2.5 或更低版本
```
#### 方法三:添加安全全局(开发者适用)
在加载模型前声明信任 `numpy` 函数:
```python
import torch.serialization
from numpy.core.multiarray import _reconstruct
with torch.serialization.safe_globals([_reconstruct]):
model = torch.load(weights_path, weights_only=True)
```
---
### **注意事项**
1. **安全警告**:`weights_only=False` 会允许任意代码执行,**仅对可信模型使用**
2. **环境验证**:运行 `pip list | grep torch` 确认当前 PyTorch 版本
3. **模型来源**:确保 `yolov5s-face.pt` 来自官方仓库或可信渠道
---
### **操作示例**
假设选择**方法一**,具体修改步骤:
1. 打开文件 `models/experimental.py`
2. 定位到约第 118 行(原 `torch.load(w, ...)` 处)
3. 添加 `weights_only=False` 参数
4. 保存并重新运行检测命令
---
### **补充说明**
如果仍无法解决,建议:
1. 重新下载官方最新版 YOLOv5-face 模型
2. 检查 CUDA/cuDNN 与 PyTorch 版本兼容性
3. 提交 issue 到 [YOLOv5-face 官方仓库](https://github.com/deepcam-cn/yolov5-face)
最新修改后报错,怎么修改 C:\Users\QwQ\PyCharmMiscProject\.venv\Scripts\python.exe D:\funasr_test\main6-8b-5g.py Notice: ffmpeg is not installed. torchaudio is used to load audio If you want to use ffmpeg backend to load audio, please install it by: sudo apt install ffmpeg # ubuntu # brew install ffmpeg # mac funasr version: 1.2.4. Downloading Model to directory: C:\Users\QwQ\.cache\modelscope\hub\iic\speech_seaco_paraformer_large_asr_nat-zh-cn-16k-common-vocab8404-pytorch 2025-03-06 19:14:51,188 - modelscope - WARNING - Using branch: master as version is unstable, use with caution Downloading Model to directory: C:\Users\QwQ\.cache\modelscope\hub\iic\speech_fsmn_vad_zh-cn-16k-common-pytorch 2025-03-06 19:14:53,802 - modelscope - WARNING - Using branch: master as version is unstable, use with caution Downloading Model to directory: C:\Users\QwQ\.cache\modelscope\hub\iic\punc_ct-transformer_cn-en-common-vocab471067-large 2025-03-06 19:14:54,453 - modelscope - WARNING - Using branch: master as version is unstable, use with caution Building prefix dict from the default dictionary ... DEBUG:jieba:Building prefix dict from the default dictionary ... Loading model from cache C:\Users\QwQ\AppData\Local\Temp\jieba.cache DEBUG:jieba:Loading model from cache C:\Users\QwQ\AppData\Local\Temp\jieba.cache Loading model cost 0.339 seconds. DEBUG:jieba:Loading model cost 0.339 seconds. Prefix dict has been built successfully. DEBUG:jieba:Prefix dict has been built successfully. Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained. ERROR:root:模型加载失败: `rope_scaling` must be a dictionary with with two fields, `type` and `factor`, got {'factor': 8.0, 'low_freq_factor': 1.0, 'high_freq_factor': 4.0, 'original_max_position_embeddings': 8192, 'rope_type': 'llama3'} Traceback (most recent call last): File "D:\funasr_test\main6-8b-5g.py", line 103, in _load_model self.model = AutoModelForCausalLM.from_pretrained( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QwQ\PyCharmMiscProject\.venv\Lib\site-packages\transformers\models\auto\auto_factory.py", line 526, in from_pretrained config, kwargs = AutoConfig.from_pretrained( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QwQ\PyCharmMiscProject\.venv\Lib\site-packages\transformers\models\auto\configuration_auto.py", line 1099, in from_pretrained return config_class.from_dict(config_dict, **unused_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\QwQ\PyCharmMiscProject\.venv\Lib\site-packages\transformers\configuration_utils.py", line 774, in from_dict config = cls(**config_dict) ^^^^^^^^^^^^^^^^^^ File "C:\Users\QwQ\PyCharmMiscProject\.venv\Lib\site-packages\transformers\models\llama\configuration_llama.py", line 160, in __init__ self._rope_scaling_validation() File "C:\Users\QwQ\PyCharmMiscProject\.venv\Lib\site-packages\transformers\models\llama\configuration_llama.py", line 180, in _rope_scaling_validation raise ValueError( ValueError: `rope_scaling` must be a dictionary with with two fields, `type` and `factor`, got {'factor': 8.0, 'low_freq_factor': 1.0, 'high_freq_factor': 4.0, 'original_max_position_embeddings': 8192, 'rope_type': 'llama3'}
<think>嗯,用户遇到了一个关于模型加载失败的报错,错误信息是`rope_scaling`的配置不符合要求。我需要仔细看一下错误日志。首先,错误发生在加载Llama模型的时候,具体是在配置`rope_scaling`参数时出现了问题。根据报错信息,当前的`rope_scaling`参数包含了很多字段,但系统期望的只有`type`和`factor`两个。
可能用户使用的模型配置文件或代码中的`rope_scaling`设置不正确。比如,用户可能在配置中加入了额外的参数,比如`low_freq_factor`、`high_freq_factor`等,这些在最新版本的transformers库中可能不再被支持。或者,用户安装的库版本和模型要求的版本不兼容,导致参数结构不一致。
接下来,我需要回忆一下Llama模型的`rope_scaling`参数的正确用法。在Hugging Face的transformers库中,`rope_scaling`通常用于调整RoPE(Rotary Position Embedding)的扩展方式,比如线性扩展或者动态NTK扩展。正确的配置应该是一个字典,包含`type`和`factor`两个键。例如:`{"type": "linear", "factor": 8.0}`。但用户当前的配置里多出了其他键,可能是模型配置文件的问题,或者用户代码中手动设置了这些参数。
另外,用户提到的错误信息中的`rope_type`是llama3,这可能是用户在使用某个特定版本的模型,比如Llama3,而当前安装的transformers库可能还不支持这个参数,或者需要更新到最新版本才能兼容。因此,检查transformers库的版本是否过旧也是一个方向。
可能的解决方案包括:1)修改`rope_scaling`的配置,只保留`type`和`factor`;2)更新transformers库到最新版本,以支持新的参数结构;3)检查模型配置文件是否有误,或者是否有自定义的代码引入了额外的参数。
此外,用户的环境信息显示使用了Windows系统,路径中有PyCharm项目,可能涉及虚拟环境。需要确认在虚拟环境中安装的库是否正确,是否存在版本冲突。比如,用户可能同时安装了不同版本的transformers和模型代码所需的版本不匹配。
还需要考虑模型是否来自ModelScope,而ModelScope的模型是否与当前transformers版本兼容。例如,某些模型可能依赖于特定版本的库,或者需要额外的配置。用户可能需要查阅模型的文档,确认正确的配置方式。
总结来说,用户需要调整`rope_scaling`参数的结构,确保只包含必要的字段,并检查库的版本是否匹配。如果问题依旧,可能需要升级库或联系模型提供方获取支持。</think>根据报错信息分析,该错误是由于Llama模型的`rope_scaling`参数格式不符合最新要求导致的。以下是分步骤解决方案:
**错误原因定位**:
```
ValueError: `rope_scaling` must be a dictionary with two fields, `type` and `factor`
```
当前代码中传递的配置参数为:
$${'factor': 8.0, 'low_freq_factor': 1.0, 'high_freq_factor': 4.0, ...}$$
**解决方案**:
1. **修改rope_scaling参数格式**
将原有参数简化为仅包含`type`和`factor`的字典格式:
```python
# 修改前(错误示例)
rope_scaling = {
"factor": 8.0,
"low_freq_factor": 1.0,
"high_freq_factor": 4.0,
"original_max_position_embeddings": 8192,
"rope_type": "llama3"
}
# 修改后(正确示例)
rope_scaling = {
"type": "linear", # 或 "dynamic_ntk"
"factor": 8.0
}
```
2. **升级transformers库版本**
执行以下命令更新库:
```bash
pip install --upgrade transformers
# 建议版本 >=4.35.0 (支持Llama3的版本)
```
3. **检查模型兼容性**
如果使用ModelScope下载的模型:
```python
# 建议显式指定revision参数
model = AutoModelForCausalLM.from_pretrained(
"iic/speech_seaco_paraformer_large_asr_nat-zh-cn-16k-common-vocab8404-pytorch",
revision="v1.2.4" # 指定稳定版本
)
```
4. **验证环境配置**
检查Python环境是否存在多版本冲突:
```bash
pip list | grep -E 'transformers|torch|modelscope'
# 应确保:
# transformers >=4.35.0
# modelscope >=1.11.0
# torch >=2.0.0
```
**补充建议**:
1. 如果使用Llama3模型,建议使用官方推荐配置:
```python
config = AutoConfig.from_pretrained(
"meta-llama/Meta-Llama-3-8B-Instruct",
rope_scaling={"type": "dynamic_ntk", "factor": 2.0}
)
```
2. 清理缓存后重试:
```bash
rm -rf ~/.cache/modelscope/hub/*
```
若问题仍未解决,建议提供完整的模型加载代码段,以便进一步分析参数传递路径。
阅读全文
相关推荐











